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
641f48f66ba12fa530212cca2033b7043172ef61
3,238
c
C
std/obj/dark_orb.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
std/obj/dark_orb.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
std/obj/dark_orb.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
/* Light absorbing orb cloned by the conjuring dark spell. See /bin/user/_dark.c for more info. By Valodin, Jan 16, 1993 */ inherit "/std/Object"; int dark_level, dark_time; object creator; create() { set_id( ({ "orb", "orb of darkness", "magical orb" }) ); set_name("orb"); set_short("An orb of darkness"); set_weight(0); set_value(0); dark_level = 0; dark_time = 0; } void init() { add_action("shatter", "shatter"); } set_creator(object ob) { creator = ob; } dark(int level, int time) { dark_level = level; dark_time = time; environment(this_object())->set_property("light", -level); call_out("brighten", time); } int shatter(string str) { if(!id(str)) { notify_fail("Shatter what?\n"); return 0; } if(this_player() != creator) { notify_fail("Only the creator of this orb can shatter it!\n"); return 0; } write("You shatter your orb.\n"); say(this_player()->query_cap_name()+" shatters " + this_player()->query_possessive() + " orb.\n", this_player()); tell_room(environment(this_player()), "The thousands of shards of darkness are quickly " + "absorbed by the light.\n"); environment(this_object())->set_property("light", dark_level); remove_call_out("brighten"); dark_level = 0; remove(); return 1; } brighten() { dark_level = dark_level - 1; environment(this_object())->set_property("light", 1); if(dark_level == 0) { if(!living(environment(this_object()))) /* must be a room or bag */ tell_object(environment(this_object()), "The orb fades out of existence.\n"); else /* in a person */ { tell_room(environment(environment(this_object())), "The orb that " + capitalize((string)environment(this_object())->query_name()) + " is carrying fades out of existence.\n", environment(this_object())); tell_object(environment(this_object()), "The orb that you are carrying fades out of existence.\n"); } remove(); } else { if(!living(environment(this_object()))) /* must be a room or bag */ tell_object(environment(this_object()), "The orb brightens slightly.\n"); else /* in a person */ { tell_room(environment(environment(this_object())), "The orb that " + capitalize((string)environment(this_object())->query_name()) + " is carrying brightens slightly.\n", environment(this_object())); tell_object(environment(this_object()), "The orb that you are carrying brightens slightly.\n"); } call_out("brighten", dark_time); } } int move(mixed dest) { int x; if(environment(this_object())) { environment(this_object())->set_property("light", dark_level); } x = ::move(dest); if(environment(this_object())) { environment(this_object())->set_property("light", -dark_level); } return x; } int remove() { if(dark_level) { if(environment(this_object())) environment(this_object())->set_property("light", -dark_level); } return ::remove(); }
24.164179
78
0.598518
[ "object" ]
64211c5a526bb13c541e20a2d536430504530a47
15,110
c
C
ds/ds/src/ntdsa/dra/draupdrr.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/ds/src/ntdsa/dra/draupdrr.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/ds/src/ntdsa/dra/draupdrr.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1996 - 1999 // // File: draupdrr.c // //-------------------------------------------------------------------------- #include <NTDSpch.h> #pragma hdrstop #include <ntdsctr.h> // PerfMon hook support // Core DSA headers. #include <ntdsa.h> #include <scache.h> // schema cache #include <dbglobal.h> // The header for the directory database #include <mdglobal.h> // MD global definition header #include <mdlocal.h> // MD local definition header #include <dsatools.h> // needed for output allocation // Logging headers. #include "dsevent.h" /* header Audit\Alert logging */ #include "mdcodes.h" /* header for error codes */ // Assorted DSA headers. #include "anchor.h" #include "objids.h" /* Defines for selected classes and atts*/ #include <hiertab.h> #include "dsexcept.h" #include "permit.h" #include "dstaskq.h" #include "dsconfig.h" #include "debug.h" /* standard debugging header */ #define DEBSUB "DRAUPDRR:" /* define the subsystem for debugging */ // DRA headers #include "drsuapi.h" #include "drsdra.h" #include "drserr.h" #include "drautil.h" #include "draerror.h" #include "drancrep.h" #include "dramail.h" #include "dsaapi.h" #include "usn.h" #include "drameta.h" #include <fileno.h> #define FILENO FILENO_DRAUPDRR DWORD AddDSARefToAtt(DBPOS *pDB, REPLICA_LINK *pRepsToRef) // // Note: This routine may fail to set 'fReplNotify' on the // NAMING_CONTEXT_LIST entry if the NC List is not up-to-date. // { BOOL fFound = FALSE; ATTCACHE * pAC; DWORD iExistingRef = 0; DWORD cbExistingAlloced = 0; DWORD cbExistingRet; REPLICA_LINK * pExistingRef; BOOL fRefHasUuid; DWORD err; NAMING_CONTEXT_LIST *pncl; DWORD ncdnt; pAC = SCGetAttById(pDB->pTHS, ATT_REPS_TO); // // PREFIX: PREFIX complains that pAC hasn't been checked to // make sure that it is not NULL. This is not a bug. Since // a predefined constant was passed to SCGetAttById, pAC will // never be NULL. // Assert(NULL != pAC); VALIDATE_REPLICA_LINK_VERSION(pRepsToRef); fRefHasUuid = !fNullUuid(&pRepsToRef->V1.uuidDsaObj); while (!DBGetAttVal_AC(pDB, ++iExistingRef, pAC, DBGETATTVAL_fREALLOC, cbExistingAlloced, &cbExistingRet, (BYTE **) &pExistingRef) ) { cbExistingAlloced = max(cbExistingAlloced, cbExistingRet); VALIDATE_REPLICA_LINK_VERSION(pExistingRef); // If either the network addresses or UUIDs match... if ( ( ( RL_POTHERDRA(pExistingRef)->mtx_namelen == RL_POTHERDRA(pRepsToRef)->mtx_namelen ) && !_memicmp( RL_POTHERDRA(pExistingRef)->mtx_name, RL_POTHERDRA(pRepsToRef)->mtx_name, RL_POTHERDRA(pExistingRef)->mtx_namelen ) ) || ( fRefHasUuid && !memcmp( &pExistingRef->V1.uuidDsaObj, &pRepsToRef->V1.uuidDsaObj, sizeof(UUID ) ) ) ) { // Reference already exists! return DRAERR_RefAlreadyExists; } } err = DBAddAttVal_AC(pDB, pAC, pRepsToRef->V1.cb, pRepsToRef); switch (err) { case DB_success: err = DBGetSingleValue(pDB, FIXED_ATT_DNT, &ncdnt, sizeof(ncdnt), NULL); Assert(err == DB_success); // NC List is not always consistent with DIT so this might fail pncl = FindNCLFromNCDNT(ncdnt, FALSE); if( NULL!=pncl ) { pncl->fReplNotify = TRUE; } else { // Couldn't set the notify flag. Ignore this problem for now // and it will be repaired later, once the NC List is updated. } break; case DB_ERR_VALUE_EXISTS: err = DRAERR_RefAlreadyExists; break; default: RAISE_DRAERR_INCONSISTENT( err ); } return err; } DWORD DelDSARefToAtt(DBPOS *pDB, REPLICA_LINK *pRepsToRef) { BOOL fFound = FALSE; ATTCACHE * pAC; DWORD iExistingRef = 0; DWORD cbExistingAlloced = 0; DWORD cbExistingRet; REPLICA_LINK * pExistingRef; BOOL fRefHasUuid; ULONG err; NAMING_CONTEXT_LIST *pncl; DWORD ncdnt; pAC = SCGetAttById(pDB->pTHS, ATT_REPS_TO); // // PREFIX: PREFIX complains that pAC hasn't been checked to // make sure that it is not NULL. This is not a bug. Since // a predefined constant was passed to SCGetAttById, pAC will // never be NULL. // Assert(NULL != pAC); VALIDATE_REPLICA_LINK_VERSION(pRepsToRef); fRefHasUuid = !fNullUuid(&pRepsToRef->V1.uuidDsaObj); while (!DBGetAttVal_AC(pDB, ++iExistingRef, pAC, DBGETATTVAL_fREALLOC, cbExistingAlloced, &cbExistingRet, (BYTE **) &pExistingRef) ) { cbExistingAlloced = max(cbExistingAlloced, cbExistingRet); VALIDATE_REPLICA_LINK_VERSION(pExistingRef); // If either the network addresses or UUIDs match... if ( ( ( RL_POTHERDRA(pExistingRef)->mtx_namelen == RL_POTHERDRA(pRepsToRef)->mtx_namelen ) && !_memicmp( RL_POTHERDRA(pExistingRef)->mtx_name, RL_POTHERDRA(pRepsToRef)->mtx_name, RL_POTHERDRA(pExistingRef)->mtx_namelen ) ) || ( fRefHasUuid && !memcmp( &pExistingRef->V1.uuidDsaObj, &pRepsToRef->V1.uuidDsaObj, sizeof(UUID ) ) ) ) { // Found matching Reps-To; remove it. fFound = TRUE; err = DBRemAttVal_AC(pDB, pAC, cbExistingRet, pExistingRef); if (err) { // Attribute removal failed! DRA_EXCEPT(DRAERR_DBError, err); } } } if ( (iExistingRef == 1) && fFound && DBHasValues(pDB, ATT_REPS_TO)) { err = DBGetSingleValue(pDB, FIXED_ATT_DNT, &ncdnt, sizeof(ncdnt), NULL); pncl = FindNCLFromNCDNT(ncdnt, FALSE); pncl->fReplNotify = FALSE; } return fFound ? 0 : DRAERR_RefNotFound; } ULONG UpdateRefsHelper( THSTATE *pTHS, DSNAME *pNC, MTX_ADDR *pDSAMtx_addr, UUID * puuidDSA, ULONG ulOptions, ULONG cConsecutiveFailures, DSTIME timeLastSuccess, DSTIME timeLastAttempt, ULONG ulResultThisAttempt ) // // Do the actual work of updating a repsTo. // - Find the NC that this repsTo lives in // - Build a REPLICA_LINK object // - Delete the existing matching REPLICA_LINK (optional) // - Add the REPLICA_LINK (optional) // // Note that this function does not use a transaction; callers must open a // transaction themselves. // { DWORD ret = 0; REPLICA_LINK *pRepsToRef; ULONG cbRepsToRef; // We must have a valid thread state, valid dbpos, and a transaction is open Assert(pTHS->JetCache.transLevel > 0); Assert(VALID_THSTATE(pTHS)); Assert(VALID_DBPOS(pTHS->pDB)); // Log parameters LogEvent(DS_EVENT_CAT_REPLICATION, DS_EVENT_SEV_EXTENSIVE, DIRLOG_DRA_UPDATEREFS_ENTRY, szInsertWC(pNC->StringName), szInsertSz(pDSAMtx_addr->mtx_name), szInsertHex(ulOptions)); if (!(ulOptions & (DRS_ADD_REF | DRS_DEL_REF))) { return DRAERR_InvalidParameter; } // Find the NC. The setting of DRS_WRIT_REP reflects writeability of // the destination's NC. The source's NC writeability should be // compatible for sourcing the destination NC. // if (FindNC(pTHS->pDB, pNC, ((ulOptions & DRS_WRIT_REP) ? FIND_MASTER_NC : FIND_MASTER_NC | FIND_REPLICA_NC), NULL)) { return DRAERR_BadNC; } cbRepsToRef = (sizeof(REPLICA_LINK) + MTX_TSIZE(pDSAMtx_addr)); pRepsToRef = (REPLICA_LINK*)THAllocEx(pTHS, cbRepsToRef); pRepsToRef->dwVersion = VERSION_V1; pRepsToRef->V1.cb = cbRepsToRef; pRepsToRef->V1.ulReplicaFlags = ulOptions & DRS_WRIT_REP; pRepsToRef->V1.cbOtherDraOffset = (DWORD)(pRepsToRef->V1.rgb - (char *)pRepsToRef); pRepsToRef->V1.cbOtherDra = MTX_TSIZE(pDSAMtx_addr); pRepsToRef->V1.cConsecutiveFailures = cConsecutiveFailures; pRepsToRef->V1.timeLastSuccess = timeLastSuccess; pRepsToRef->V1.timeLastAttempt = timeLastAttempt, pRepsToRef->V1.ulResultLastAttempt = ulResultThisAttempt; if (puuidDSA) { pRepsToRef->V1.uuidDsaObj = *puuidDSA; } memcpy(RL_POTHERDRA(pRepsToRef), pDSAMtx_addr, MTX_TSIZE(pDSAMtx_addr)); if (ulOptions & DRS_DEL_REF) { ret = DelDSARefToAtt (pTHS->pDB, pRepsToRef); // If we are doing a DEL and an ADD, the return value is lost by design. } if (ulOptions & DRS_ADD_REF) { ret = AddDSARefToAtt (pTHS->pDB, pRepsToRef); } if (!ret) { DBRepl(pTHS->pDB, pTHS->fDRA, 0, NULL, META_STANDARD_PROCESSING); } // DelDSARefToAtt can return RefNotFound. If this is returned, it will be logged // by draasync.c:DispatchPao. When this routine is called by GetNCChanges for a // reps-to verification (DRS_GETCHG_CHECK), we can ignore these errors. if ( (ulOptions & DRS_GETCHG_CHECK) && ( (ret == DRAERR_RefNotFound) || (ret == DRAERR_RefAlreadyExists) ) ) { ret = ERROR_SUCCESS; } return ret; } ULONG DRA_UpdateRefs( THSTATE *pTHS, DSNAME *pNC, MTX_ADDR *pDSAMtx_addr, UUID * puuidDSA, ULONG ulOptions) { DWORD ret = 0; BeginDraTransaction(SYNC_WRITE); __try { ret = UpdateRefsHelper( pTHS, pNC, pDSAMtx_addr, puuidDSA, ulOptions, 0, // Count of consecutive failures 0, // Time of last success 0, // Time of last attempt 0 // Result of last attempt ); } __finally { // If we had success, commit, else rollback if (EndDraTransaction(!(ret || AbnormalTermination()))) { Assert( !"EndTransaction failed" ); ret = DRAERR_InternalError; } } return ret; } ULONG UpdateRepsTo( THSTATE * pTHS, DSNAME * pNC, UUID * puuidDSA, MTX_ADDR *pDSAMtx_addr, ULONG ulResultThisAttempt ) // // Add or update a Reps-To attribute value with the given state information. // // This function assumes that the Reps-To value already exists. If it does not, // DRAERR_NoReplica will be returned. // // A change to the reps-to is limited to an update period to reduce nc head contention. // { // Necessary local variables ULONG ret = 0; BOOL AttExists; ULONG len; REPLICA_LINK * pRepsTo = NULL; DWORD cConsecutiveFailures; DSTIME timeLastAttempt; DSTIME timeLastSuccess; Assert( NULL==pTHS->pDB ); DBOpen(&pTHS->pDB); __try { // Verify that the NC exists if (DBFindDSName(pTHS->pDB, pNC)) { return DRAERR_BadNC; } // Try to find this name in the repsTo attribute. // BUGBUG: PERF: Since repsTos are stored as binary blobs, they cannot // be found efficiently. The notification code sends a notify for each repsTo // and then calls this function to update it. Since FindDSAinRepAtt() does a // linear search, we will end up doing O( |RepsTos|^2 ) work. if ( !FindDSAinRepAtt( pTHS->pDB, ATT_REPS_TO, DRS_FIND_DSA_BY_UUID, puuidDSA, NULL, &AttExists, &pRepsTo, &len ) ) { // Existing att val for this DSA found VALIDATE_REPLICA_LINK_VERSION(pRepsTo); VALIDATE_REPLICA_LINK_SIZE(pRepsTo); } else { ret = DRAERR_NoReplica; __leave; } timeLastAttempt = DBTime(); if (timeLastAttempt > pRepsTo->V1.timeLastAttempt) { DSTIME timeSinceLastAttempt = (timeLastAttempt - pRepsTo->V1.timeLastAttempt); if (timeSinceLastAttempt < DRA_REPSTO_UPDATE_PERIOD) { __leave; } } if( ERROR_SUCCESS==ulResultThisAttempt ) { // This attempt was successful. timeLastSuccess = timeLastAttempt; // No failures. cConsecutiveFailures = 0; } else { // We did not successfully notify the remote machine. // timeLastSuccess is not updated. timeLastSuccess = pRepsTo->V1.timeLastSuccess; // Consecutive failure count is incremented. cConsecutiveFailures = pRepsTo->V1.cConsecutiveFailures+1; } ret = UpdateRefsHelper( pTHS, pNC, pDSAMtx_addr, puuidDSA, (pRepsTo->V1.ulReplicaFlags | DRS_ADD_REF | DRS_DEL_REF), cConsecutiveFailures, timeLastSuccess, timeLastAttempt, ulResultThisAttempt ); } __finally { // If we had success, commit, else rollback if (DBClose(pTHS->pDB, !(ret || AbnormalTermination()))) { Assert( !"DBClose failed" ); ret = DRAERR_InternalError; } } return ret; }
32.35546
88
0.535539
[ "object" ]
64267d09b25f32de09d54c4d06dca8192f192bad
4,155
h
C
src/qemu/src-pmp/include/qemu/filemonitor.h
pmp-tool/PMP
ef5e05fb4612bb622a9e1039f772c6234b87df7d
[ "MIT" ]
8
2020-09-06T12:49:00.000Z
2022-03-09T04:02:06.000Z
src/qemu/src-pmp/include/qemu/filemonitor.h
newthis/PMP
ef5e05fb4612bb622a9e1039f772c6234b87df7d
[ "MIT" ]
null
null
null
src/qemu/src-pmp/include/qemu/filemonitor.h
newthis/PMP
ef5e05fb4612bb622a9e1039f772c6234b87df7d
[ "MIT" ]
7
2020-09-08T15:14:34.000Z
2021-06-24T18:03:49.000Z
/* * QEMU file monitor helper * * Copyright (c) 2018 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * */ #ifndef QEMU_FILE_MONITOR_H #define QEMU_FILE_MONITOR_H #include "qemu-common.h" typedef struct QFileMonitor QFileMonitor; typedef enum { /* File has been created in a dir */ QFILE_MONITOR_EVENT_CREATED, /* File has been modified in a dir */ QFILE_MONITOR_EVENT_MODIFIED, /* File has been deleted in a dir */ QFILE_MONITOR_EVENT_DELETED, /* File has attributes changed */ QFILE_MONITOR_EVENT_ATTRIBUTES, /* Dir is no longer being monitored (due to deletion) */ QFILE_MONITOR_EVENT_IGNORED, } QFileMonitorEvent; /** * QFileMonitorHandler: * @id: id from qemu_file_monitor_add_watch() * @event: the file change that occurred * @filename: the name of the file affected * @opaque: opaque data provided to qemu_file_monitor_add_watch() * * Invoked whenever a file changes. If @event is * QFILE_MONITOR_EVENT_IGNORED, @filename will be * empty. * */ typedef void (*QFileMonitorHandler)(int64_t id, QFileMonitorEvent event, const char *filename, void *opaque); /** * qemu_file_monitor_new: * @errp: pointer to a NULL-initialized error object * * Create a handle for a file monitoring object. * * This object does locking internally to enable it to be * safe to use from multiple threads * * If the platform does not support file monitoring, an * error will be reported. Likewise if file monitoring * is supported, but cannot be initialized * * Currently this is implemented on Linux platforms with * the inotify subsystem. * * Returns: the new monitoring object, or NULL on error */ QFileMonitor *qemu_file_monitor_new(Error **errp); /** * qemu_file_monitor_free: * @mon: the file monitor context * * Free resources associated with the file monitor, * including any currently registered watches. */ void qemu_file_monitor_free(QFileMonitor *mon); /** * qemu_file_monitor_add_watch: * @mon: the file monitor context * @dirpath: the directory whose contents to watch * @filename: optional filename to filter on * @cb: the function to invoke when @dirpath has changes * @opaque: data to pass to @cb * @errp: pointer to a NULL-initialized error object * * Register to receive notifications of changes * in the directory @dirpath. All files in the * directory will be monitored. If the caller is * only interested in one specific file, @filename * can be used to filter events. * * Returns: a positive integer watch ID, or -1 on error */ int64_t qemu_file_monitor_add_watch(QFileMonitor *mon, const char *dirpath, const char *filename, QFileMonitorHandler cb, void *opaque, Error **errp); /** * qemu_file_monitor_remove_watch: * @mon: the file monitor context * @dirpath: the directory whose contents to unwatch * @id: id of the watch to remove * * Removes the file monitoring watch @id, associated * with the directory @dirpath. This must never be * called from a QFileMonitorHandler callback, or a * deadlock will result. */ void qemu_file_monitor_remove_watch(QFileMonitor *mon, const char *dirpath, int64_t id); #endif /* QEMU_FILE_MONITOR_H */
32.209302
79
0.677256
[ "object" ]
6427968b78dcdfac6fc6565407c140d89860eec9
3,046
h
C
misc/debugcounter.h
WqyJh/badvpn
2771742c25378660705a8fa260d6aa807c2c8b11
[ "BSD-3-Clause" ]
1,759
2015-01-01T11:08:18.000Z
2022-03-31T03:38:34.000Z
misc/debugcounter.h
WqyJh/badvpn
2771742c25378660705a8fa260d6aa807c2c8b11
[ "BSD-3-Clause" ]
111
2015-02-17T17:04:50.000Z
2021-08-15T20:16:58.000Z
misc/debugcounter.h
WqyJh/badvpn
2771742c25378660705a8fa260d6aa807c2c8b11
[ "BSD-3-Clause" ]
449
2015-01-01T11:08:23.000Z
2022-03-29T13:36:55.000Z
/** * @file debugcounter.h * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * Counter for detecting leaks. */ #ifndef BADVPN_MISC_DEBUGCOUNTER_H #define BADVPN_MISC_DEBUGCOUNTER_H #include <stdint.h> #include <misc/debug.h> /** * Counter for detecting leaks. */ typedef struct { #ifndef NDEBUG int32_t c; #else int dummy_field; // struct must have at least one field #endif } DebugCounter; #define DEBUGCOUNTER_STATIC { 0 } /** * Initializes the object. * The object is initialized with counter value zero. * * @param obj the object */ static void DebugCounter_Init (DebugCounter *obj) { #ifndef NDEBUG obj->c = 0; #endif } /** * Frees the object. * This does not have to be called when the counter is no longer needed. * The counter value must be zero. * * @param obj the object */ static void DebugCounter_Free (DebugCounter *obj) { #ifndef NDEBUG ASSERT(obj->c == 0 || obj->c == INT32_MAX) #endif } /** * Increments the counter. * Increments the counter value by one. * * @param obj the object */ static void DebugCounter_Increment (DebugCounter *obj) { #ifndef NDEBUG ASSERT(obj->c >= 0) if (obj->c != INT32_MAX) { obj->c++; } #endif } /** * Decrements the counter. * The counter value must be >0. * Decrements the counter value by one. * * @param obj the object */ static void DebugCounter_Decrement (DebugCounter *obj) { #ifndef NDEBUG ASSERT(obj->c > 0) if (obj->c != INT32_MAX) { obj->c--; } #endif } #endif
26.034188
82
0.713066
[ "object" ]
64298a6656b1ae622d388596fadb4180c8e26a4c
6,663
h
C
toonz/sources/include/toonzqt/intpairfield.h
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/include/toonzqt/intpairfield.h
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/include/toonzqt/intpairfield.h
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
1
2019-10-07T17:12:30.000Z
2019-10-07T17:12:30.000Z
#ifndef INTPAIRFIELD_H #define INTPAIRFIELD_H #include "toonzqt/intfield.h" #include "tcommon.h" #undef DVAPI #undef DVVAR #ifdef TOONZQT_EXPORTS #define DVAPI DV_EXPORT_API #define DVVAR DV_EXPORT_VAR #else #define DVAPI DV_IMPORT_API #define DVVAR DV_IMPORT_VAR #endif // forward declaration class QSlider; class QLabel; //============================================================================= namespace DVGui { //============================================================================= /*! \brief The IntPairField class provides to view an object to manage a pair of int parameter. Inherits \b QWidget. The object is composed of an horizontal layout \b QHBoxLayout which contains two pair [label, text field] and a slider with two grab, one for each int value to manage. [label, text field] are a \b QLabel and a \b IntLineEdit. Objects are inserted in the following order: a label and respective text field, the slider and the other pair [lebel,text field]. Object size width is not fixed, while height is equal to DVGui::WidgetHeight, 20; labels width depend from its text lenght, text fields has fixed size, while slider width change in according with widget size. Objects contained in this widget are connected, so if you change one value the other automatically change, if it is necessary. You can set current value, getValues(), minimum and max value, getRange(), using setValues(), setRange(). To know when one of two int parameter value change class provides a signal, valuesChanged(); class emit signal when a grab slider position change or when editing text field, left or right is finished and current value is changed. Editing text field finished may occur if focus is lost or enter key is pressed. See SLOT: onLeftEditingFinished() and onRightEditingFinished(). \b Example: \code IntPairField* intPairFieldExample = new IntPairField(this); intPairFieldExample->setLeftText(tr("Left Value:")); intPairFieldExample->setRightText(tr("Rigth Value:")); intPairFieldExample->setRange(0,10); intPairFieldExample->setValues(std::make_pair(3,8)); \endcode \b Result: \image html DoublePairField.jpg */ class DVAPI IntPairField : public QWidget { Q_OBJECT QPixmap m_handleLeftPixmap, m_handleRightPixmap, m_handleLeftGrayPixmap, m_handleRightGrayPixmap; Q_PROPERTY(QPixmap HandleLeftPixmap READ getHandleLeftPixmap WRITE setHandleLeftPixmap); Q_PROPERTY(QPixmap HandleRightPixmap READ getHandleRightPixmap WRITE setHandleRightPixmap); Q_PROPERTY(QPixmap HandleLeftGrayPixmap READ getHandleLeftGrayPixmap WRITE setHandleLeftGrayPixmap); Q_PROPERTY(QPixmap HandleRightGrayPixmap READ getHandleRightGrayPixmap WRITE setHandleRightGrayPixmap); IntLineEdit *m_leftLineEdit; IntLineEdit *m_rightLineEdit; QColor m_lightLineColor; /*-- スライダ溝の明るい色(白) --*/ QColor m_darkLineColor; /*-- スライダ溝の暗い色(128,128,128) --*/ Q_PROPERTY(QColor LightLineColor READ getLightLineColor WRITE setLightLineColor); Q_PROPERTY(QColor DarkLineColor READ getDarkLineColor WRITE setDarkLineColor); QLabel *m_leftLabel, *m_rightLabel; std::pair<int, int> m_values; int m_minValue, m_maxValue; int m_grabOffset, m_grabIndex; int m_leftMargin, m_rightMargin; bool m_isMaxRangeLimited; public: IntPairField(QWidget *parent = 0, bool isMaxRangeLimited = true); ~IntPairField() {} /*! Set current values to \b values. */ void setValues(const std::pair<int, int> &values); /*! Return a pair containing current values. */ std::pair<int, int> getValues() const { return m_values; } /*! Set left label string to \b QString \b text. Recompute left margin adding label width. */ void setLeftText(const QString &text); /*! Set right label string to \b QString \b text. Recompute right margin adding label width. */ void setRightText(const QString &text); void setLabelsEnabled(bool enable); /*! Set range of \b IntPairField to \b minValue, \b maxValue. */ void setRange(int minValue, int maxValue); /*! Set \b minValue and \b maxValue to IntPairField range. */ void getRange(int &minValue, int &maxValue); QPixmap getHandleLeftPixmap() const { return m_handleLeftPixmap; } void setHandleLeftPixmap(const QPixmap &pixmap) { m_handleLeftPixmap = pixmap; } QPixmap getHandleRightPixmap() const { return m_handleRightPixmap; } void setHandleRightPixmap(const QPixmap &pixmap) { m_handleRightPixmap = pixmap; } QPixmap getHandleLeftGrayPixmap() const { return m_handleLeftGrayPixmap; } void setHandleLeftGrayPixmap(const QPixmap &pixmap) { m_handleLeftGrayPixmap = pixmap; } QPixmap getHandleRightGrayPixmap() const { return m_handleRightGrayPixmap; } void setHandleRightGrayPixmap(const QPixmap &pixmap) { m_handleRightGrayPixmap = pixmap; } void setLightLineColor(const QColor &color) { m_lightLineColor = color; } QColor getLightLineColor() const { return m_lightLineColor; } void setDarkLineColor(const QColor &color) { m_darkLineColor = color; } QColor getDarkLineColor() const { return m_darkLineColor; } protected: /*! Return value corresponding \b x position. */ double pos2value(int x) const; /*! Return x position corresponding \b value. */ int value2pos(double v) const; /*! Set current value to \b value. Set left or right value, or both, to value depending on current slider grab edited and \b value. */ void setValue(int v); void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); protected slots: /*! Set current left value to value in left text field; if necessary, if left value is greater than right, change also current right value. \n This protected slot is called when text editing is finished. \n Emit valuesChanged(). \n If current left value is equal to left text field value, return and do nothing. */ void onLeftEditingFinished(); /*! Set current right value to value in right text field; if necessary, if right value is lower than left, change also current left value. \n This protected slot is called when text editing is finished. \n Emit valuesChanged(). \n If current right value is equal to right text field value return and do nothing. */ void onRightEditingFinished(); signals: /*! This signal is emitted when change one of two IntField value; if one slider grab position change or if one text field editing is finished. */ void valuesChanged(bool isDragging); }; //----------------------------------------------------------------------------- } //namespace DVGui //----------------------------------------------------------------------------- #endif // INTPAIRFIELD_H
39.194118
104
0.731652
[ "object" ]
64344f8a2a3047c8322e0ce2fc9372565fac1b33
3,564
h
C
OsiriXAPI.framework/Versions/A/Headers/vtkAssignMimeType.h
nevitdilmen/Osirix-ColorMRI
47549f97dd09b414742e773f365a4e7143bf2067
[ "MIT" ]
20
2016-02-02T10:31:41.000Z
2021-11-08T08:35:25.000Z
OsiriXAPI.framework/Versions/A/Headers/vtkAssignMimeType.h
nevitdilmen/Osirix-ColorMRI
47549f97dd09b414742e773f365a4e7143bf2067
[ "MIT" ]
14
2018-01-03T16:49:04.000Z
2018-06-01T15:19:06.000Z
OsiriXAPI.framework/Versions/A/Headers/vtkAssignMimeType.h
nevitdilmen/Osirix-ColorMRI
47549f97dd09b414742e773f365a4e7143bf2067
[ "MIT" ]
9
2018-01-24T21:46:10.000Z
2022-03-08T09:42:42.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkAssignMimeType.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ // .NAME vtkAssignMimeType - Assigns MIME types to a collection of documents. // // .SECTION Description // Given a table containing document URIs and contents, tries to assign a MIME type // to each document. // // Inputs: // Input port 0: (required) A vtkTable containing document URIs and contents // (which could be binary). // // Outputs: // Output port 0: The same table with an additional "mime_type" column that contains the // MIME type identified for each document, or empty-string. // // Use SetInputArrayToProcess(0, ...) to specify the input table column that contains // URIs (must be a vtkStringArray). // // Use SetInputArrayToProcess(1, ...) to specify the input table column that contains // document contents (must be a vtkStringArray). // // .SECTION Caveats // The input document contents array must be a string array, even though the individual // document contents may be binary data. // // .SECTION Thanks // Developed by Timothy M. Shead (tshead@sandia.gov) at Sandia National Laboratories. #ifndef __vtkAssignMimeType_h #define __vtkAssignMimeType_h #include "vtkTableAlgorithm.h" class vtkMimeTypes; class VTK_TEXT_ANALYSIS_EXPORT vtkAssignMimeType : public vtkTableAlgorithm { public: static vtkAssignMimeType* New(); vtkTypeMacro(vtkAssignMimeType, vtkTableAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Specifies the name of the output MIME type array. Default: "mime_type". vtkSetStringMacro(OutputArray); vtkGetStringMacro(OutputArray); // Description: // Specifies a default MIME type that will be assigned to files whose MIME type // can't otherwise be identified. Set this to "text/plain" if you want to analyze // files that would otherwise be ignored (such as files without a known file // extension, files without any file extension, etc). Default: empty string. vtkSetStringMacro(DefaultMimeType); vtkGetStringMacro(DefaultMimeType); // Description: // Assign a custom vtkMimeTypes object to this filter. This makes it possible // to work with arbitrary Mime Type strategies. void SetMimeTypes(vtkMimeTypes *m); vtkGetObjectMacro(MimeTypes, vtkMimeTypes); //BTX protected: vtkAssignMimeType(); ~vtkAssignMimeType(); virtual int RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); private: vtkAssignMimeType(const vtkAssignMimeType &); // Not implemented. void operator=(const vtkAssignMimeType &); // Not implemented. char* OutputArray; char* DefaultMimeType; vtkMimeTypes* MimeTypes; //ETX }; #endif // __vtkAssignMimeType_h
34.601942
90
0.691077
[ "object" ]
64350ae66dfb9596a41aa2e55a77a74c876fd2cb
12,661
h
C
libs/visual_traffic_simulator/Graphical_Zone_Implementation.h
osu-sim/ANL_polaris
a7b96f908017d02af3a79a510c813f45c2373c84
[ "BSD-3-Clause" ]
null
null
null
libs/visual_traffic_simulator/Graphical_Zone_Implementation.h
osu-sim/ANL_polaris
a7b96f908017d02af3a79a510c813f45c2373c84
[ "BSD-3-Clause" ]
null
null
null
libs/visual_traffic_simulator/Graphical_Zone_Implementation.h
osu-sim/ANL_polaris
a7b96f908017d02af3a79a510c813f45c2373c84
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "Dependencies.h" #include "Traffic_Simulator\Zone_Implementation.h" namespace Zone_Components { namespace Types { enum COLUMN_COLOR { RED_COLUMN, GREEN_COLUMN, BLUE_COLUMN, GRAY_COLUMN }; #pragma pack(push,1) implementation struct Quad : public Polaris_Component<MasterType,INHERIT(Quad),NULLTYPE> { Quad() { color._a=200; color._b=0; color._r=0; color._g=0; } True_Color_RGBA<NULLTYPE> color; Point_3D<MasterType> a; Point_3D<MasterType> b; Point_3D<MasterType> c; Point_3D<MasterType> d; }; #pragma pack(pop) #pragma pack(push,1) implementation struct Column : public Polaris_Component<MasterType,INHERIT(Column),NULLTYPE> { Column(Point_3D<MasterType> center_point, int width, int height, COLUMN_COLOR primary_color) { quads=new Quad<MasterType>[5]; num_primitives=5; //if (primary_color == GREEN_COLUMN || primary_color == GRAY_COLUMN) //{ // quads[0].color._g = 255; // quads[1].color._g = 220; // quads[2].color._g = 180; // quads[3].color._g = 150; // quads[4].color._g = 255; //} //if (primary_color == RED_COLUMN || primary_color == GRAY_COLUMN) //{ // quads[0].color._r = 255; // quads[1].color._r = 220; // quads[2].color._r = 180; // quads[3].color._r = 150; // quads[4].color._r = 255; //} //if (primary_color == BLUE_COLUMN || primary_color == GRAY_COLUMN) //{ // quads[0].color._b = 255; // quads[1].color._b = 220; // quads[2].color._b = 180; // quads[3].color._b = 150; // quads[4].color._b = 255; //} if (primary_color == GREEN_COLUMN || primary_color == GRAY_COLUMN) { quads[0].color._g = 255; quads[1].color._g = 255; quads[2].color._g = 255; quads[3].color._g = 255; quads[4].color._g = 255; } if (primary_color == RED_COLUMN || primary_color == GRAY_COLUMN) { quads[0].color._r = 255; quads[1].color._r = 255; quads[2].color._r = 255; quads[3].color._r = 255; quads[4].color._r = 255; } if (primary_color == BLUE_COLUMN || primary_color == GRAY_COLUMN) { quads[0].color._b = 255; quads[1].color._b = 255; quads[2].color._b = 255; quads[3].color._b = 255; quads[4].color._b = 255; } quads[0].color._a = 220; quads[1].color._a = 220; quads[2].color._a = 220; quads[3].color._a = 220; quads[4].color._a = 220; // east side quads[0].a._x = center_point._x + width/4; quads[0].a._y = center_point._y - width/2; quads[0].a._z = 1; quads[0].b._x = center_point._x + width/4; quads[0].b._y = center_point._y + width/2; quads[0].b._z = 1; quads[0].c._x = center_point._x + width/4; quads[0].c._y = center_point._y + width/2; quads[0].c._z = height; quads[0].d._x = center_point._x + width/4; quads[0].d._y = center_point._y - width/2; quads[0].d._z = height; //west side quads[1].a._x = center_point._x - width/4; quads[1].a._y = center_point._y - width/2; quads[1].a._z = 1; quads[1].d._x = center_point._x - width/4; quads[1].d._y = center_point._y + width/2; quads[1].d._z = 1; quads[1].c._x = center_point._x - width/4; quads[1].c._y = center_point._y + width/2; quads[1].c._z = height; quads[1].b._x = center_point._x - width/4; quads[1].b._y = center_point._y - width/2; quads[1].b._z = height; //north side quads[2].a._x = center_point._x + width/4; quads[2].a._y = center_point._y + width/2; quads[2].a._z = 1; quads[2].b._x = center_point._x - width/4; quads[2].b._y = center_point._y + width/2; quads[2].b._z = 1; quads[2].c._x = center_point._x - width/4; quads[2].c._y = center_point._y + width/2; quads[2].c._z = height; quads[2].d._x = center_point._x + width/4; quads[2].d._y = center_point._y + width/2; quads[2].d._z = height; //south side quads[3].a._x = center_point._x + width/4; quads[3].a._y = center_point._y - width/2; quads[3].a._z = 1; quads[3].d._x = center_point._x - width/4; quads[3].d._y = center_point._y - width/2; quads[3].d._z = 1; quads[3].c._x = center_point._x - width/4; quads[3].c._y = center_point._y - width/2; quads[3].c._z = height; quads[3].b._x = center_point._x + width/4; quads[3].b._y = center_point._y - width/2; quads[3].b._z = height; //top side quads[4].a._x = center_point._x + width/4; quads[4].a._y = center_point._y - width/2; quads[4].a._z = height; quads[4].d._x = center_point._x - width/4; quads[4].d._y = center_point._y - width/2; quads[4].d._z = height; quads[4].c._x = center_point._x - width/4; quads[4].c._y = center_point._y + width/2; quads[4].c._z = height; quads[4].b._x = center_point._x + width/4; quads[4].b._y = center_point._y + width/2; quads[4].b._z = height; } template<typename TargetType> void Push_To_Layer(TargetType Layer_Reference) { Layer_Reference->Push_Element<Regular_Element>((void*)this); } void* ptr; int num_primitives; Quad<MasterType>* quads; }; #pragma pack(pop) } namespace Concepts { } namespace Implementations { implementation struct Graphical_Zone_Group_Implementation : public Polaris_Component<MasterType,INHERIT(Graphical_Zone_Group_Implementation),Data_Object> { template<typename CoordType, typename TargetType> void accept_zone_information(CoordType coordinates, void* ptr, typename TargetType productions, typename TargetType attractions) { int width = 300; int height_prod = productions; int height_att = attractions; Point_3D<MasterType> origin_col_center, destination_col_center; origin_col_center._x = coordinates._x - width*0.25; origin_col_center._y = coordinates._y ; destination_col_center._x = coordinates._x + width*0.25; destination_col_center._y = origin_col_center._y; Scale_Coordinates<MT>(origin_col_center); Scale_Coordinates<MT>(destination_col_center); // construct and push to productions column Types::Column<MasterType> origin_column = Types::Column<MasterType>(origin_col_center,width,height_prod, Types::GREEN_COLUMN); origin_column.ptr = ptr; origin_column.Push_To_Layer(_zone_centroids); // construct and push to attractions column Types::Column<MasterType> destination_column = Types::Column<MasterType>(destination_col_center,width,height_att, Types::BLUE_COLUMN); destination_column.ptr = ptr; destination_column.Push_To_Layer(_zone_centroids); } template<typename TargetType> void configure_zones_layer() { // configure vehicle layer cout << "configuring zone layer"; _zone_centroids=Allocate_New_Layer<MT>(string("Zones")); Antares_Layer_Configuration cfg; cfg.Configure_Static_Quads(True_Color_RGBA<NULLTYPE>(0,255,100,255),10); //cfg.attributes_schema.push_back("ID"); //cfg.attributes_schema.push_back("Productions"); //cfg.attributes_schema.push_back("Attractions"); //cfg.attributes_schema.push_back("Population"); //cfg.attributes_schema.push_back("Available"); cfg.dynamic_data = true; cfg.storage_period = 300; cfg.target_sub_iteration = Types::ZONE_UPDATE_SUBITERATION+1; cfg.storage_offset = 60/*iteration()*/; cfg.storage_size = 4; cfg.primitive_color = true; cfg.primitive_normal = true; cfg.grouped = true; cfg.selection_callback = (selection_callback_type)&Graphical_Zone_Implementation<MasterType>::on_select; //cfg.selection_callback = (selection_callback_type)&Graphical_Zone_Implementation<MasterType>::fetch_attributes; //cfg.submission_callback = (selection_callback_type)&Graphical_Zone_Implementation<MasterType>::submit_attributes; _zone_centroids->Initialize<NULLTYPE>(cfg); } m_prototype(Antares_Layer,typename MasterType::antares_layer_type,zone_centroids, NONE, NONE); }; implementation struct Graphical_Zone_Implementation : public Zone_Components::Implementations::Zone_Implementation<MasterType,INHERIT(Graphical_Zone_Implementation)> { typedef Zone_Components::Implementations::Zone_Implementation<MasterType,INHERIT(Graphical_Zone_Implementation)> BaseType; typedef Zone<typename MasterType::zone_type> this_itf; typedef Zone_Components::Prototypes::Zone<BaseType> base_itf; typedef Activity_Location_Components::Prototypes::Activity_Location<typename remove_pointer<typename BaseType::type_of(origin_activity_locations)::value_type>::type> activity_location_interface; typedef Random_Access_Sequence<typename BaseType::type_of(origin_activity_locations),activity_location_interface*> activity_locations_interface; static void Default_Zone_Conditional(ComponentType* _this,Event_Response& response) { this_itf* pthis = (this_itf*)_this; response.next._iteration=Simulation_Time.Future_Time<Simulation_Timestep_Increment,Simulation_Timestep_Increment>(pthis->update_increment<Simulation_Timestep_Increment>()); //response.next._iteration = iteration() + pthis->update_increment<Simulation_Timestep_Increment>(); response.next._sub_iteration=Types::ZONE_UPDATE_SUBITERATION; _this->Default_Zone_Event(); } void Default_Zone_Event() { this->Push_To_Zone_Display<NULLTYPE>(); this->reset_counters<NULLTYPE>(); } template<typename TargetType> void Initialize() { base_itf* base_this = (base_itf*)this; base_this->zone_is_available<bool>(true); this_itf* pthis = (this_itf*)this; pthis->update_increment<Time_Minutes>(5); ((ComponentType*)this)->Load_Event<ComponentType>(&Default_Zone_Conditional,60,Types::ZONE_UPDATE_SUBITERATION); } template<typename TargetType> void Push_To_Zone_Display() { //cout << endl << "at zone push_to_display"; base_itf* base_this = (base_itf*)this; Point_3D<MasterType> coordinate; coordinate._x=base_this->X<float>(); coordinate._y=base_this->Y<float>(); coordinate._z=0; //int height = base_this->origin_activity_locations<activity_locations_interface*>()->size(); int prod_height = base_this->production_count<int>(); int att_height = base_this->attraction_count<int>(); _production_count_buffer = prod_height; _attraction_count_buffer = att_height; int height_scale = 50; _graphical_zone_group->accept_zone_information<Point_3D<MasterType>, int>(coordinate, this, prod_height*height_scale, att_height*height_scale); } static void on_select(const std::list<void*>& removed,const std::list<void*>& added,const std::list<void*>& selected,std::vector<pair<string,string>>& bucket) { } static bool fetch_attributes(Graphical_Zone_Implementation* _this,std::vector<string>& bucket) { this_itf* this_ptr = (this_itf*)_this; stringstream s; s << this_ptr->uuid<int>(); bucket.push_back(s.str()); s.str(""); s << _this->_production_count_buffer; bucket.push_back(s.str()); s.str(""); s << _this->_attraction_count_buffer; bucket.push_back(s.str()); s.str(""); s << this_ptr->population<int>(); bucket.push_back(s.str()); s.str(""); s << boolalpha << this_ptr->zone_is_available<bool>(); bucket.push_back(s.str()); s.str(""); return true; } static bool submit_attributes(Graphical_Zone_Implementation* _this,std::vector<string>& bucket) { this_itf* this_ptr = (this_itf*)_this; std::vector<string>::iterator itr; if(bucket[4] == "True" ||bucket[4] == "true" || bucket[4] == "t" || bucket[4] == "T" ) { this_ptr->zone_is_available<bool>(true); return true; } else if (bucket[4] == "False" || bucket[4] == "false" || bucket[4] == "f" || bucket[4] == "F" ) { this_ptr->zone_is_available<bool>(false); return true; } else { return false; } } m_data(typename Basic_Units::Implementations::Time_Implementation<MasterType>,_Update_Increment, NONE, NONE); member_component_feature(update_increment, _Update_Increment, Value, Basic_Units::Prototypes::Time); static m_prototype(Graphical_Zone_Group,typename MasterType::graphical_zone_group_type,graphical_zone_group, NONE, NONE); m_data(int, production_count_buffer, NONE, NONE); m_data(int, attraction_count_buffer, NONE, NONE); }; template<typename MasterType,typename InheritanceList> Zone_Components::Prototypes::Graphical_Zone_Group<typename MasterType::graphical_zone_group_type>* Graphical_Zone_Implementation<MasterType,InheritanceList>::_graphical_zone_group; } }
34.687671
197
0.683437
[ "vector" ]
643674af16c0bc58e245ebd72cc242c3ca248fb1
126,498
c
C
osal/src/os/posix/osapi.c
SpaceySciences/spacey-cfs
dd4b318843328a7b298f80c68692923c74725ee9
[ "NASA-1.3" ]
1
2016-05-09T13:07:16.000Z
2016-05-09T13:07:16.000Z
osal/src/os/posix/osapi.c
SpaceySciences/spacey-cfs
dd4b318843328a7b298f80c68692923c74725ee9
[ "NASA-1.3" ]
null
null
null
osal/src/os/posix/osapi.c
SpaceySciences/spacey-cfs
dd4b318843328a7b298f80c68692923c74725ee9
[ "NASA-1.3" ]
null
null
null
/* ** File : osapi.c ** ** Copyright (c) 2004-2006, United States government as represented by the ** administrator of the National Aeronautics Space Administration. ** All rights reserved. This software was created at NASAs Goddard ** Space Flight Center pursuant to government contracts. ** ** This is governed by the NASA Open Source Agreement and may be used, ** distributed and modified only pursuant to the terms of that agreement. ** ** Author : Alan Cudmore ** ** Purpose: ** This file contains some of the OS APIs abstraction layer ** implementation for POSIX, specifically for Linux with the 2.6 kernel ( > 2.6.18 ) ** with the gnu c library. uClibc or other embedded C libraries may not work. ** ** ** $Date: 2014/04/23 13:11:08GMT-05:00 $ ** $Revision: 1.29 $ ** $Log: osapi.c $ ** Revision 1.29 2014/04/23 13:11:08GMT-05:00 acudmore ** In the posix message queue version of OS_QueueCreate, fixed the problem where the queue size was hardcoded ** Revision 1.28 2014/01/16 16:29:22GMT-05:00 acudmore ** Implemented safer mutex lock/unlock ** switched time functions to clock_gettime/clock_settime ** Revision 1.27 2013/12/11 16:46:07GMT-05:00 acudmore ** OS_QueueGet - check for buffer overflow condition in both versions of function ** Revision 1.26 2013/12/11 13:21:36GMT-05:00 acudmore ** Updated OS_QueueGet code to allow a message to be smaller than the buffer ** Revision 1.25 2013/08/09 14:42:03GMT-05:00 acudmore ** changed OS_TaskDelay to use nanosleep and handle interruptions ** Revision 1.24 2013/07/25 14:27:20GMT-05:00 acudmore ** Fixed reference to bin_sem_table in CountSem function ** Revision 1.23 2013/07/24 11:13:31GMT-05:00 acudmore ** Updated Milli2Ticks ** Revision 1.22 2013/07/23 13:42:03GMT-05:00 acudmore ** The pthread attributes were not being set correctly. ** In addition, the application must be run as root to set priority, stack size, and scheduling policy. ** Revision 1.21 2013/07/22 15:54:47GMT-05:00 acudmore ** conditionally compile debug printfs ** Revision 1.20 2012/12/19 14:39:56GMT-05:00 acudmore ** Updated use of size_copied in OS_QueueGet ** Revision 1.19 2012/12/19 13:45:21EST acudmore ** Updated QueuePut return codes ( included OS_ERROR ) ** Also, close socket before returning an error ** Revision 1.18 2012/12/06 14:53:02EST acudmore ** Updated comments ** Revision 1.17 2012/11/28 16:56:15EST acudmore ** Remove OS X and Cygwin Support ** Revision 1.16 2012/11/15 14:17:08EST acudmore ** Moved task table init statements inside mutex lock in OS_TaskCreate ** Revision 1.15 2012/11/09 17:11:30EST acudmore ** Overhaul of Binary, Counting sems ** Fixed task creation priority setup ** Revision 1.14 2012/10/03 11:35:04EDT acudmore ** Fixed semaphore define when initializing counting semaphore table in OS_API_Init ** Revision 1.13 2012/04/11 10:57:07EDT acudmore ** Added OS_printf_enable and OS_printf_disable ** Revision 1.12 2012/01/09 17:28:43EST acudmore ** Fixed a couple of OS X related compilation errors ** Revision 1.11 2011/12/05 15:26:29EST acudmore ** Added semaphore protection for counting semaphore give and take operations ** Revision 1.10 2011/06/27 15:50:18EDT acudmore ** Went over APIs and Documentation for return code consistency. ** Updated documentation, function comments, and return codes as needed. ** Revision 1.9 2011/04/05 12:53:49EDT acudmore ** Updated comments for timeout code. If a pend is interrupted by ** a system call, there is no need to recompute delay ** Revision 1.8 2011/03/30 11:43:47EDT acudmore ** Updated all timeout code to: ** - use the CompAbsDelayTime function ** - Check to see if the delay was interrupted by a system call ** - Not use a busy loop if the posix call is available ( linux ) ** Revision 1.7 2011/03/23 12:31:52EDT acudmore ** Updated pending calls to account for EINTR return code ( interrupted by signal ) ** Revision 1.6 2011/03/23 11:20:09EDT acudmore ** Added logic to posix message queue create and delete to make queue name unique for each process running the cfe ** Revision 1.5 2010/11/12 12:00:43EST acudmore ** replaced copyright character with (c) and added open source notice where needed. ** Revision 1.4 2010/11/10 15:33:47EST acudmore ** Fixed IntAttachHandler prototype ** Revision 1.3 2010/03/10 15:43:03EST acudmore ** Updated to work with cygwin 1.7.x ** Revision 1.2 2010/03/08 12:07:17EST acudmore ** fixed warnings by using a function pointer type ** Revision 1.1 2010/02/17 13:12:01EST acudmore ** Initial revision ** Member added to project c:/MKSDATA/MKS-REPOSITORY/MKS-OSAL-REPOSITORY/src/os/posix/project.pj ** Member added to project c:/MKSDATA/MKS-REPOSITORY/MKS-OSAL-REPOSITORY/src/os/linux/project.pj ** Revision 1.10 2008/02/14 10:12:24EST apcudmore ** initialized pthread_attr_t to fix problem with OS_TaskCreate in cygwin ** Revision 1.9 2008/02/04 10:59:00EST apcudmore ** Changed OS_QueueGet timeout to use select rather than a sleep loop. ** Revision 1.7 2008/01/31 10:37:05EST apcudmore ** Implement Task Delete hook API. */ /**************************************************************************************** INCLUDE FILES ****************************************************************************************/ #include <stdio.h> #include <sys/types.h> #include <ctype.h> #include <unistd.h> #include <semaphore.h> #include <time.h> #include <signal.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <sys/select.h> #include <sys/time.h> #include <fcntl.h> #include <errno.h> #include <limits.h> /* ** The __USE_UNIX98 is for advanced pthread features on linux */ #define __USE_UNIX98 #include <pthread.h> /* ** User defined include files */ #include "common_types.h" #include "osapi.h" /* ** This include must be put below the osapi.h ** include so it can pick up the define */ #ifndef OSAL_SOCKET_QUEUE #include <mqueue.h> #endif /* ** Defines */ #define OS_BASE_PORT 43000 #define UNINITIALIZED 0 #define MAX_PRIORITY 255 #ifndef PTHREAD_STACK_MIN #define PTHREAD_STACK_MIN 8092 #endif #undef OS_DEBUG_PRINTF /* ** Global data for the API */ /* ** Tables for the properties of objects */ /*tasks */ typedef struct { int free; pthread_t id; char name [OS_MAX_API_NAME]; int creator; uint32 stack_size; uint32 priority; void *delete_hook_pointer; }OS_task_record_t; #ifdef OSAL_SOCKET_QUEUE /* queues */ typedef struct { int free; int id; uint32 max_size; char name [OS_MAX_API_NAME]; int creator; }OS_queue_record_t; #else /* queues */ typedef struct { int free; mqd_t id; uint32 max_size; char name [OS_MAX_API_NAME]; int creator; }OS_queue_record_t; #endif /* Binary Semaphores */ typedef struct { int free; pthread_mutex_t id; pthread_cond_t cv; char name [OS_MAX_API_NAME]; int creator; int max_value; int current_value; }OS_bin_sem_record_t; /*Counting Semaphores */ typedef struct { int free; pthread_mutex_t id; pthread_cond_t cv; char name [OS_MAX_API_NAME]; int creator; int max_value; int current_value; }OS_count_sem_record_t; /* Mutexes */ typedef struct { int free; pthread_mutex_t id; char name [OS_MAX_API_NAME]; int creator; }OS_mut_sem_record_t; /* function pointer type */ typedef void (*FuncPtr_t)(void); /* Tables where the OS object information is stored */ OS_task_record_t OS_task_table [OS_MAX_TASKS]; OS_queue_record_t OS_queue_table [OS_MAX_QUEUES]; OS_bin_sem_record_t OS_bin_sem_table [OS_MAX_BIN_SEMAPHORES]; OS_count_sem_record_t OS_count_sem_table [OS_MAX_COUNT_SEMAPHORES]; OS_mut_sem_record_t OS_mut_sem_table [OS_MAX_MUTEXES]; pthread_key_t thread_key; pthread_mutex_t OS_task_table_mut; pthread_mutex_t OS_queue_table_mut; pthread_mutex_t OS_bin_sem_table_mut; pthread_mutex_t OS_mut_sem_table_mut; pthread_mutex_t OS_count_sem_table_mut; uint32 OS_printf_enabled = TRUE; /* ** Local Function Prototypes */ void OS_CompAbsDelayTime( uint32 milli_second , struct timespec * tm); void OS_ThreadKillHandler(int sig ); uint32 OS_FindCreator(void); int32 OS_PriorityRemap(uint32 InputPri); int OS_InterruptSafeLock(pthread_mutex_t *lock, sigset_t *set, sigset_t *previous); void OS_InterruptSafeUnlock(pthread_mutex_t *lock, sigset_t *previous); /*--------------------------------------------------------------------------------------- Name: OS_API_Init Purpose: Initialize the tables that the OS API uses to keep track of information about objects returns: OS_SUCCESS or OS_ERROR ---------------------------------------------------------------------------------------*/ int32 OS_API_Init(void) { int i; int ret; pthread_mutexattr_t mutex_attr ; int32 return_code = OS_SUCCESS; struct sched_param param; int sched_policy; /* Initialize Task Table */ for(i = 0; i < OS_MAX_TASKS; i++) { OS_task_table[i].free = TRUE; OS_task_table[i].creator = UNINITIALIZED; OS_task_table[i].delete_hook_pointer = NULL; strcpy(OS_task_table[i].name,""); } /* Initialize Message Queue Table */ for(i = 0; i < OS_MAX_QUEUES; i++) { OS_queue_table[i].free = TRUE; OS_queue_table[i].id = UNINITIALIZED; OS_queue_table[i].creator = UNINITIALIZED; strcpy(OS_queue_table[i].name,""); } /* Initialize Binary Semaphore Table */ for(i = 0; i < OS_MAX_BIN_SEMAPHORES; i++) { OS_bin_sem_table[i].free = TRUE; OS_bin_sem_table[i].creator = UNINITIALIZED; strcpy(OS_bin_sem_table[i].name,""); } /* Initialize Counting Semaphores */ for(i = 0; i < OS_MAX_COUNT_SEMAPHORES; i++) { OS_count_sem_table[i].free = TRUE; OS_count_sem_table[i].creator = UNINITIALIZED; strcpy(OS_count_sem_table[i].name,""); } /* Initialize Mutex Semaphore Table */ for(i = 0; i < OS_MAX_MUTEXES; i++) { OS_mut_sem_table[i].free = TRUE; OS_mut_sem_table[i].creator = UNINITIALIZED; strcpy(OS_mut_sem_table[i].name,""); } /* ** Initialize the module loader */ #ifdef OS_INCLUDE_MODULE_LOADER return_code = OS_ModuleTableInit(); if ( return_code == OS_ERROR ) { return(return_code); } #endif /* ** Initialize the Timer API */ return_code = OS_TimerAPIInit(); if ( return_code == OS_ERROR ) { return(return_code); } ret = pthread_key_create(&thread_key, NULL ); if ( ret != 0 ) { #ifdef OS_DEBUG_PRINTF printf("Error creating thread key\n"); #endif return_code = OS_ERROR; return(return_code); } /* ** initialize the pthread mutex attribute structure with default values */ return_code = pthread_mutexattr_init(&mutex_attr); if ( return_code != 0 ) { #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutexattr_init failed\n"); #endif return_code = OS_ERROR; return (return_code); } /* ** Allow the mutex to use priority inheritance */ return_code = pthread_mutexattr_setprotocol(&mutex_attr,PTHREAD_PRIO_INHERIT) ; if ( return_code != 0 ) { #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutexattr_setprotocol failed\n"); #endif return_code = OS_ERROR; return (return_code); } /* ** Set the mutex type to RECURSIVE so a thread can do nested locks */ return_code = pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE); if ( return_code != 0 ) { #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutexattr_settype failed\n"); #endif return_code = OS_ERROR; return (return_code); } /* ** create the mutexes that protect the OSAPI structures ** the function returns on error, since we dont want to go through ** the extra trouble of creating and deleting resoruces for nothing */ ret = pthread_mutex_init((pthread_mutex_t *) & OS_task_table_mut,&mutex_attr); if ( ret != 0 ) { return_code = OS_ERROR; return(return_code); } ret = pthread_mutex_init((pthread_mutex_t *) & OS_queue_table_mut,&mutex_attr); if ( ret != 0 ) { return_code = OS_ERROR; return(return_code); } ret = pthread_mutex_init((pthread_mutex_t *) & OS_bin_sem_table_mut,&mutex_attr); if ( ret != 0 ) { return_code = OS_ERROR; return(return_code); } ret = pthread_mutex_init((pthread_mutex_t *) & OS_count_sem_table_mut,&mutex_attr); if ( ret != 0 ) { return_code = OS_ERROR; return(return_code); } ret = pthread_mutex_init((pthread_mutex_t *) & OS_mut_sem_table_mut,&mutex_attr); if ( ret != 0 ) { return_code = OS_ERROR; return(return_code); } /* ** File system init */ return_code = OS_FS_Init(); /* ** Check to see if this application is running as root ** It must be root in order to set the scheduling policy, stacks, and priorities of ** the pthreads */ if (geteuid() != 0 ) { #ifdef OS_DEBUG_PRINTF printf("OS_API_Init: Note: Not running as root. Task scheduling policy, stack sizes, or priorities will not be set\n"); #endif } else { param.sched_priority = 50; sched_policy = SCHED_FIFO; return_code = pthread_setschedparam(pthread_self(), sched_policy, &param); #ifdef OS_DEBUG_PRINTF if (return_code != 0) { printf("OS_API_Init: Could not set scheduleparam in main thread\n"); } #endif } return(return_code); } /* ********************************************************************************** ** TASK API ********************************************************************************** */ /*--------------------------------------------------------------------------------------- Name: OS_TaskCreate Purpose: Creates a task and starts running it. returns: OS_INVALID_POINTER if any of the necessary pointers are NULL OS_ERR_NAME_TOO_LONG if the name of the task is too long to be copied OS_ERR_INVALID_PRIORITY if the priority is bad OS_ERR_NO_FREE_IDS if there can be no more tasks created OS_ERR_NAME_TAKEN if the name specified is already used by a task OS_ERROR if the operating system calls fail OS_SUCCESS if success NOTES: task_id is passed back to the user as the ID. stack_pointer is usually null. the flags parameter is unused. ---------------------------------------------------------------------------------------*/ int32 OS_TaskCreate (uint32 *task_id, const char *task_name, osal_task_entry function_pointer, const uint32 *stack_pointer, uint32 stack_size, uint32 priority, uint32 flags) { int return_code = 0; pthread_attr_t custom_attr ; struct sched_param priority_holder ; int possible_taskid; int i; uint32 local_stack_size; int ret; int os_priority; int inheritsched; sigset_t previous; sigset_t mask; /* Check for NULL pointers */ if( (task_name == NULL) || (function_pointer == NULL) || (task_id == NULL) ) { return OS_INVALID_POINTER; } /* we don't want to allow names too long*/ /* if truncated, two names might be the same */ if (strlen(task_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } /* Check for bad priority */ if (priority > MAX_PRIORITY) { return OS_ERR_INVALID_PRIORITY; } /* Change OSAL priority into a priority that will work for this OS */ os_priority = OS_PriorityRemap(priority); /* Check Parameters */ OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); for(possible_taskid = 0; possible_taskid < OS_MAX_TASKS; possible_taskid++) { if (OS_task_table[possible_taskid].free == TRUE) { break; } } /* Check to see if the id is out of bounds */ if( possible_taskid >= OS_MAX_TASKS || OS_task_table[possible_taskid].free != TRUE) { OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); return OS_ERR_NO_FREE_IDS; } /* Check to see if the name is already taken */ for (i = 0; i < OS_MAX_TASKS; i++) { if ((OS_task_table[i].free == FALSE) && ( strcmp((char*) task_name, OS_task_table[i].name) == 0)) { OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); return OS_ERR_NAME_TAKEN; } } /* ** Set the possible task Id to not free so that ** no other task can try to use it */ OS_task_table[possible_taskid].free = FALSE; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); if ( stack_size < PTHREAD_STACK_MIN ) { local_stack_size = PTHREAD_STACK_MIN; } else { local_stack_size = stack_size; } /* ** Initialize the pthread_attr structure. ** The structure is used to set the stack and priority */ memset(&custom_attr, 0, sizeof(custom_attr)); if(pthread_attr_init(&custom_attr)) { OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); OS_task_table[possible_taskid].free = TRUE; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("pthread_attr_init error in OS_TaskCreate, Task ID = %d\n",possible_taskid); perror("pthread_attr_init"); #endif return(OS_ERROR); } /* ** Test to see if the user is running as root. ** root is required to set the scheduling policy, stack, and priority */ if (geteuid() == 0 ) { /* ** Set the scheduling inherit attribute to EXPLICIT */ inheritsched = PTHREAD_EXPLICIT_SCHED; return_code = pthread_attr_setinheritsched(&custom_attr, inheritsched); if ( return_code < 0 ) { #ifdef OS_DEBUG_PRINTF printf("pthread_attr_setinheritsched error in OS_TaskCreate, Task ID = %d, errno = %s\n", possible_taskid,strerror(errno)); #endif return(OS_ERROR); } /* ** Set the Stack Size */ if (pthread_attr_setstacksize(&custom_attr, (size_t)local_stack_size )) { #ifdef OS_DEBUG_PRINTF printf("pthread_attr_setstacksize error in OS_TaskCreate, Task ID = %d\n",possible_taskid); #endif return(OS_ERROR); } /* ** Set the scheduling policy ** On Linux, the schedpolity must be SCHED_FIFO or SCHED_RR to set the priorty */ if (pthread_attr_setschedpolicy(&custom_attr, SCHED_FIFO)) { #ifdef OS_DEBUG_PRINTF printf("pthread_attr_setschedpolity error in OS_TaskCreate, Task ID = %d\n",possible_taskid); #endif return(OS_ERROR); } /* ** Set priority */ memset(&priority_holder, 0, sizeof(priority_holder)); priority_holder.sched_priority = os_priority; ret = pthread_attr_setschedparam(&custom_attr,&priority_holder); if(ret !=0) { #ifdef OS_DEBUG_PRINTF printf("pthread_attr_setschedparam error in OS_TaskCreate, Task ID = %d\n",possible_taskid); #endif return(OS_ERROR); } } /* End if user is root */ /* ** Create thread */ return_code = pthread_create(&(OS_task_table[possible_taskid].id), &custom_attr, function_pointer, (void *)0); if (return_code != 0) { OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); OS_task_table[possible_taskid].free = TRUE; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("pthread_create error in OS_TaskCreate, Task ID = %d\n",possible_taskid); #endif return(OS_ERROR); } /* ** Free the resources that are no longer needed */ return_code = pthread_detach(OS_task_table[possible_taskid].id); if (return_code !=0) { OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); OS_task_table[possible_taskid].free = TRUE; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("pthread_detach error in OS_TaskCreate, Task ID = %d\n",possible_taskid); #endif return(OS_ERROR); } return_code = pthread_attr_destroy(&custom_attr); if (return_code !=0) { OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); OS_task_table[possible_taskid].free = TRUE; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("pthread_attr_destroy error in OS_TaskCreate, Task ID = %d\n",possible_taskid); #endif return(OS_ERROR); } /* ** Assign the task ID */ *task_id = possible_taskid; /* ** Initialize the table entries */ OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); OS_task_table[possible_taskid].free = FALSE; strcpy(OS_task_table[*task_id].name, (char*) task_name); OS_task_table[possible_taskid].creator = OS_FindCreator(); OS_task_table[possible_taskid].stack_size = stack_size; /* Use the abstracted priority, not the OS one */ OS_task_table[possible_taskid].priority = priority; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); return OS_SUCCESS; }/* end OS_TaskCreate */ /*-------------------------------------------------------------------------------------- Name: OS_TaskDelete Purpose: Deletes the specified Task and removes it from the OS_task_table. returns: OS_ERR_INVALID_ID if the ID given to it is invalid OS_ERROR if the OS delete call fails OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_TaskDelete (uint32 task_id) { int ret; FuncPtr_t FunctionPointer; sigset_t previous; sigset_t mask; /* ** Check to see if the task_id given is valid */ if (task_id >= OS_MAX_TASKS || OS_task_table[task_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* ** Call the thread Delete hook if there is one. */ if ( OS_task_table[task_id].delete_hook_pointer != NULL) { FunctionPointer = (FuncPtr_t)(OS_task_table[task_id].delete_hook_pointer); (*FunctionPointer)(); } /* ** Try to delete the task */ ret = pthread_cancel(OS_task_table[task_id].id); if (ret != 0) { #ifdef OS_DEBUG_PRINTF printf("FAILED PTHREAD CANCEL %d, %d \n",ret, ESRCH); #endif return OS_ERROR; } /* ** Now that the task is deleted, remove its ** "presence" in OS_task_table */ OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); OS_task_table[task_id].free = TRUE; strcpy(OS_task_table[task_id].name, ""); OS_task_table[task_id].creator = UNINITIALIZED; OS_task_table[task_id].stack_size = UNINITIALIZED; OS_task_table[task_id].priority = UNINITIALIZED; OS_task_table[task_id].id = UNINITIALIZED; OS_task_table[task_id].delete_hook_pointer = NULL; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); return OS_SUCCESS; }/* end OS_TaskDelete */ /*-------------------------------------------------------------------------------------- Name: OS_TaskExit Purpose: Exits the calling task and removes it from the OS_task_table. returns: Nothing ---------------------------------------------------------------------------------------*/ void OS_TaskExit() { uint32 task_id; sigset_t previous; sigset_t mask; task_id = OS_TaskGetId(); OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); OS_task_table[task_id].free = TRUE; strcpy(OS_task_table[task_id].name, ""); OS_task_table[task_id].creator = UNINITIALIZED; OS_task_table[task_id].stack_size = UNINITIALIZED; OS_task_table[task_id].priority = UNINITIALIZED; OS_task_table[task_id].id = UNINITIALIZED; OS_task_table[task_id].delete_hook_pointer = NULL; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); pthread_exit(NULL); }/*end OS_TaskExit */ /*--------------------------------------------------------------------------------------- Name: OS_TaskDelay Purpose: Delay a task for specified amount of milliseconds returns: OS_ERROR if sleep fails or millisecond = 0 OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_TaskDelay(uint32 millisecond ) { struct timespec waittime; uint32 ms = millisecond; int sleepstat; waittime.tv_sec = ms / 1000; waittime.tv_nsec = (ms % 1000) * 1000000; /* ** Do not allow signals to interrupt nanosleep until the requested time */ do { sleepstat = nanosleep(&waittime, &waittime); } while( sleepstat == -1 && errno == EINTR ); if ( sleepstat == -1 ) { return(OS_ERROR); } else { return OS_SUCCESS; } }/* end OS_TaskDelay */ /*--------------------------------------------------------------------------------------- Name: OS_TaskSetPriority Purpose: Sets the given task to a new priority returns: OS_ERR_INVALID_ID if the ID passed to it is invalid OS_ERR_INVALID_PRIORITY if the priority is greater than the max allowed OS_ERROR if the OS call to change the priority fails OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_TaskSetPriority (uint32 task_id, uint32 new_priority) { int os_priority; int ret; if(task_id >= OS_MAX_TASKS || OS_task_table[task_id].free == TRUE) { return OS_ERR_INVALID_ID; } if (new_priority > MAX_PRIORITY) { return OS_ERR_INVALID_PRIORITY; } /* Change OSAL priority into a priority that will work for this OS */ os_priority = OS_PriorityRemap(new_priority); if (geteuid() == 0 ) { /* ** Set priority */ ret = pthread_setschedprio(OS_task_table[task_id].id, os_priority); if( ret != 0 ) { #ifdef OS_DEBUG_PRINTF printf("pthread_setschedprio err in OS_TaskSetPriority, Task ID = %lu, prio = %d, errno = %s\n", task_id,os_priority ,strerror(errno)); #endif return(OS_ERROR); } } /* Use the abstracted priority, not the OS one */ /* Change the priority in the table as well */ OS_task_table[task_id].priority = new_priority; return OS_SUCCESS; } /* end OS_TaskSetPriority */ /*--------------------------------------------------------------------------------------- Name: OS_TaskRegister Purpose: Registers the calling task id with the task by adding the var to the tcb It searches the OS_task_table to find the task_id corresponding to the tcb_id Returns: OS_ERR_INVALID_ID if there the specified ID could not be found OS_ERROR if the OS call fails OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_TaskRegister (void) { int i; int ret; uint32 task_id; pthread_t pthread_id; /* ** Get PTHREAD Id */ pthread_id = pthread_self(); /* ** Look our task ID in table */ for(i = 0; i < OS_MAX_TASKS; i++) { if(OS_task_table[i].id == pthread_id) { break; } } task_id = i; if(task_id == OS_MAX_TASKS) { return OS_ERR_INVALID_ID; } /* ** Add pthread variable */ ret = pthread_setspecific(thread_key, (void *)task_id); if ( ret != 0 ) { #ifdef OS_DEBUG_PRINTF printf("OS_TaskRegister Failed during pthread_setspecific function\n"); #endif return(OS_ERROR); } return OS_SUCCESS; }/* end OS_TaskRegister */ /*--------------------------------------------------------------------------------------- Name: OS_TaskGetId Purpose: This function returns the #defined task id of the calling task Notes: The OS_task_key is initialized by the task switch if AND ONLY IF the OS_task_key has been registered via OS_TaskRegister(..). If this is not called prior to this call, the value will be old and wrong. ---------------------------------------------------------------------------------------*/ uint32 OS_TaskGetId (void) { void* task_id; int task_id_int; uint32 task_key; task_key = 0; task_id = (void *)pthread_getspecific(thread_key); memcpy(& task_id_int,&task_id, sizeof(uint32)); task_key = task_id_int & 0xFFFF; return(task_key); }/* end OS_TaskGetId */ /*-------------------------------------------------------------------------------------- Name: OS_TaskGetIdByName Purpose: This function tries to find a task Id given the name of a task Returns: OS_INVALID_POINTER if the pointers passed in are NULL OS_ERR_NAME_TOO_LONG if th ename to found is too long to begin with OS_ERR_NAME_NOT_FOUND if the name wasn't found in the table OS_SUCCESS if SUCCESS ---------------------------------------------------------------------------------------*/ int32 OS_TaskGetIdByName (uint32 *task_id, const char *task_name) { uint32 i; if (task_id == NULL || task_name == NULL) { return OS_INVALID_POINTER; } /* ** we don't want to allow names too long because they won't be found at all */ if (strlen(task_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } for (i = 0; i < OS_MAX_TASKS; i++) { if((OS_task_table[i].free != TRUE) && (strcmp(OS_task_table[i].name,(char*) task_name) == 0 )) { *task_id = i; return OS_SUCCESS; } } /* The name was not found in the table, ** or it was, and the task_id isn't valid anymore */ return OS_ERR_NAME_NOT_FOUND; }/* end OS_TaskGetIdByName */ /*--------------------------------------------------------------------------------------- Name: OS_TaskGetInfo Purpose: This function will pass back a pointer to structure that contains all of the relevant info (creator, stack size, priority, name) about the specified task. Returns: OS_ERR_INVALID_ID if the ID passed to it is invalid OS_INVALID_POINTER if the task_prop pointer is NULL OS_SUCCESS if it copied all of the relevant info over ---------------------------------------------------------------------------------------*/ int32 OS_TaskGetInfo (uint32 task_id, OS_task_prop_t *task_prop) { sigset_t previous; sigset_t mask; /* ** Check to see that the id given is valid */ if (task_id >= OS_MAX_TASKS || OS_task_table[task_id].free == TRUE) { return OS_ERR_INVALID_ID; } if( task_prop == NULL) { return OS_INVALID_POINTER; } /* put the info into the stucture */ OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); task_prop -> creator = OS_task_table[task_id].creator; task_prop -> stack_size = OS_task_table[task_id].stack_size; task_prop -> priority = OS_task_table[task_id].priority; task_prop -> OStask_id = (uint32) OS_task_table[task_id].id; strcpy(task_prop-> name, OS_task_table[task_id].name); OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); return OS_SUCCESS; } /* end OS_TaskGetInfo */ /*-------------------------------------------------------------------------------------- Name: OS_TaskInstallDeleteHandler Purpose: Installs a handler for when the task is deleted. returns: status ---------------------------------------------------------------------------------------*/ int32 OS_TaskInstallDeleteHandler(void *function_pointer) { uint32 task_id; sigset_t previous; sigset_t mask; task_id = OS_TaskGetId(); if ( task_id >= OS_MAX_TASKS ) { return(OS_ERR_INVALID_ID); } OS_InterruptSafeLock(&OS_task_table_mut, &mask, &previous); if ( OS_task_table[task_id].free != FALSE ) { /* ** Somehow the calling task is not registered */ OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); return(OS_ERR_INVALID_ID); } /* ** Install the pointer */ OS_task_table[task_id].delete_hook_pointer = function_pointer; OS_InterruptSafeUnlock(&OS_task_table_mut, &previous); return(OS_SUCCESS); }/*end OS_TaskInstallDeleteHandler */ /**************************************************************************************** MESSAGE QUEUE API ****************************************************************************************/ #ifdef OSAL_SOCKET_QUEUE /*--------------------------------------------------------------------------------------- Name: OS_QueueCreate Purpose: Create a message queue which can be refered to by name or ID Returns: OS_INVALID_POINTER if a pointer passed in is NULL OS_ERR_NAME_TOO_LONG if the name passed in is too long OS_ERR_NO_FREE_IDS if there are already the max queues created OS_ERR_NAME_TAKEN if the name is already being used on another queue OS_ERROR if the OS create call fails OS_SUCCESS if success Notes: the flags parameter is unused. ---------------------------------------------------------------------------------------*/ int32 OS_QueueCreate (uint32 *queue_id, const char *queue_name, uint32 queue_depth, uint32 data_size, uint32 flags) { int tmpSkt; int returnStat; struct sockaddr_in servaddr; int i; uint32 possible_qid; sigset_t previous; sigset_t mask; if ( queue_id == NULL || queue_name == NULL) { return OS_INVALID_POINTER; } /* we don't want to allow names too long*/ /* if truncated, two names might be the same */ if (strlen(queue_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } /* Check Parameters */ OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); for(possible_qid = 0; possible_qid < OS_MAX_QUEUES; possible_qid++) { if (OS_queue_table[possible_qid].free == TRUE) break; } if( possible_qid >= OS_MAX_QUEUES || OS_queue_table[possible_qid].free != TRUE) { OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_ERR_NO_FREE_IDS; } /* Check to see if the name is already taken */ for (i = 0; i < OS_MAX_QUEUES; i++) { if ((OS_queue_table[i].free == FALSE) && strcmp ((char*) queue_name, OS_queue_table[i].name) == 0) { OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_ERR_NAME_TAKEN; } } /* Set the possible task Id to not free so that * no other task can try to use it */ OS_queue_table[possible_qid].free = FALSE; OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); tmpSkt = socket(AF_INET, SOCK_DGRAM, 0); if ( tmpSkt == -1 ) { OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); OS_queue_table[possible_qid].free = TRUE; OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Failed to create a socket on OS_QueueCreate. errno = %d\n",errno); #endif return OS_ERROR; } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(OS_BASE_PORT + possible_qid); servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* ** bind the input socket to a pipe ** port numbers are OS_BASE_PORT + queue_id */ returnStat = bind(tmpSkt,(struct sockaddr *)&servaddr, sizeof(servaddr)); if ( returnStat == -1 ) { OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); OS_queue_table[possible_qid].free = TRUE; OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("bind failed on OS_QueueCreate. errno = %d\n",errno); #endif return OS_ERROR; } /* ** store socket handle */ *queue_id = possible_qid; OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); OS_queue_table[*queue_id].id = tmpSkt; OS_queue_table[*queue_id].free = FALSE; OS_queue_table[*queue_id].max_size = data_size; strcpy( OS_queue_table[*queue_id].name, (char*) queue_name); OS_queue_table[*queue_id].creator = OS_FindCreator(); OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_SUCCESS; }/* end OS_QueueCreate */ /*-------------------------------------------------------------------------------------- Name: OS_QueueDelete Purpose: Deletes the specified message queue. Returns: OS_ERR_INVALID_ID if the id passed in does not exist OS_ERROR if the OS call to delete the queue fails OS_SUCCESS if success Notes: If There are messages on the queue, they will be lost and any subsequent calls to QueueGet or QueuePut to this queue will result in errors ---------------------------------------------------------------------------------------*/ int32 OS_QueueDelete (uint32 queue_id) { sigset_t previous; sigset_t mask; /* Check to see if the queue_id given is valid */ if (queue_id >= OS_MAX_QUEUES || OS_queue_table[queue_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Try to delete the queue */ if(close(OS_queue_table[queue_id].id) !=0) { return OS_ERROR; } /* * Now that the queue is deleted, remove its "presence" * in OS_message_q_table and OS_message_q_name_table */ OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); OS_queue_table[queue_id].free = TRUE; strcpy(OS_queue_table[queue_id].name, ""); OS_queue_table[queue_id].creator = UNINITIALIZED; OS_queue_table[queue_id].max_size = 0; OS_queue_table[queue_id].id = UNINITIALIZED; OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_SUCCESS; } /* end OS_QueueDelete */ /*--------------------------------------------------------------------------------------- Name: OS_QueueGet Purpose: Receive a message on a message queue. Will pend or timeout on the receive. Returns: OS_ERR_INVALID_ID if the given ID does not exist OS_INVALID_POINTER if a pointer passed in is NULL OS_QUEUE_EMPTY if the Queue has no messages on it to be recieved OS_QUEUE_TIMEOUT if the timeout was OS_PEND and the time expired OS_QUEUE_INVALID_SIZE if the size of the buffer passed in is not big enough for the maximum size message OS_ERROR if there was an error waiting for the timeout OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_QueueGet (uint32 queue_id, void *data, uint32 size, uint32 *size_copied, int32 timeout) { int sizeCopied; int flags; /* ** Check Parameters */ if(queue_id >= OS_MAX_QUEUES || OS_queue_table[queue_id].free == TRUE) { return OS_ERR_INVALID_ID; } else if( (data == NULL) || (size_copied == NULL) ) { return OS_INVALID_POINTER; } else if( size < OS_queue_table[queue_id].max_size ) { /* ** The buffer that the user is passing in is potentially too small ** RTEMS will just copy into a buffer that is too small */ *size_copied = 0; return(OS_QUEUE_INVALID_SIZE); } /* ** Read the socket for data */ if (timeout == OS_PEND) { fcntl(OS_queue_table[queue_id].id,F_SETFL,0); /* ** A signal can interrupt the recvfrom call, so the call has to be done with ** a loop */ do { sizeCopied = recvfrom(OS_queue_table[queue_id].id, data, size, 0, NULL, NULL); } while ( sizeCopied == -1 && errno == EINTR ); if ( sizeCopied == -1 ) { *size_copied = 0; return OS_ERROR; } else { *size_copied = sizeCopied; } } else if (timeout == OS_CHECK) { flags = fcntl(OS_queue_table[queue_id].id, F_GETFL, 0); fcntl(OS_queue_table[queue_id].id,F_SETFL,flags|O_NONBLOCK); sizeCopied = recvfrom(OS_queue_table[queue_id].id, data, size, 0, NULL, NULL); fcntl(OS_queue_table[queue_id].id,F_SETFL,flags); if (sizeCopied == -1 && errno == EWOULDBLOCK ) { *size_copied = 0; return(OS_QUEUE_EMPTY); } else if ( sizeCopied == -1 ) { *size_copied = 0; return(OS_ERROR); } else { *size_copied = sizeCopied; } } else /* timeout */ { int rv; int sock = OS_queue_table[queue_id].id; struct timeval tv_timeout; fd_set fdset; FD_ZERO( &fdset ); FD_SET( sock, &fdset ); /* ** Translate the timeout value from milliseconds into ** seconds and nanoseconds. */ tv_timeout.tv_usec = (timeout % 1000) * 1000; tv_timeout.tv_sec = timeout / 1000; /* ** Use select to wait for data to come in on the socket ** TODO: If the select call is interrupted, the timeout should be ** re-computed to avoid having to delay for the full time. ** */ do { FD_ZERO( &fdset ); FD_SET( sock, &fdset ); rv = select( sock+1, &fdset, NULL, NULL, &tv_timeout ); } while ( rv == -1 && errno == EINTR ); if( rv > 0 ) { /* got a packet within the timeout */ sizeCopied = recvfrom(OS_queue_table[queue_id].id, data, size, 0, NULL, NULL); if ( sizeCopied == -1 ) { *size_copied = 0; return(OS_ERROR); } else { *size_copied = sizeCopied; } } else if ( rv < 0 ) { /* ** Need to handle Select error codes here ** This might need a new error code: OS_QUEUE_TIMEOUT_ERROR */ #ifdef OS_DEBUG_PRINTF printf("Bad return value from select: %d, sock = %d\n", rv, sock); #endif *size_copied = 0; return OS_ERROR; } /* ** If rv == 0, then the select timed out with no data */ *size_copied = 0; return(OS_QUEUE_TIMEOUT); } /* END timeout */ return OS_SUCCESS; } /* end OS_QueueGet */ /*--------------------------------------------------------------------------------------- Name: OS_QueuePut Purpose: Put a message on a message queue. Returns: OS_ERR_INVALID_ID if the queue id passed in is not a valid queue OS_INVALID_POINTER if the data pointer is NULL OS_QUEUE_FULL if the queue cannot accept another message OS_ERROR if the OS call returns an error OS_SUCCESS if SUCCESS Notes: The flags parameter is not used. The message put is always configured to immediately return an error if the receiving message queue is full. ---------------------------------------------------------------------------------------*/ int32 OS_QueuePut (uint32 queue_id, void *data, uint32 size, uint32 flags) { struct sockaddr_in serva; static int socketFlags = 0; int bytesSent = 0; int tempSkt = 0; /* ** Check Parameters */ if(queue_id >= OS_MAX_QUEUES || OS_queue_table[queue_id].free == TRUE) { return OS_ERR_INVALID_ID; } if (data == NULL) { return OS_INVALID_POINTER; } /* ** specify the IP addres and port number of destination */ memset(&serva, 0, sizeof(serva)); serva.sin_family = AF_INET; serva.sin_port = htons(OS_BASE_PORT + queue_id); serva.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* ** open a temporary socket to transfer the packet to MR */ tempSkt = socket(AF_INET, SOCK_DGRAM, 0); /* ** send the packet to the message router task (MR) */ bytesSent = sendto(tempSkt,(char *)data, size, socketFlags, (struct sockaddr *)&serva, sizeof(serva)); if( bytesSent == -1 ) { close(tempSkt); return(OS_ERROR); } if( bytesSent != size ) { close(tempSkt); return(OS_QUEUE_FULL); } /* ** close socket */ close(tempSkt); return OS_SUCCESS; } /* end OS_QueuePut */ #else /* ---------------------- POSIX MESSAGE QUEUE IMPLEMENTATION ------------------------- */ /*--------------------------------------------------------------------------------------- Name: OS_QueueCreate Purpose: Create a message queue which can be refered to by name or ID Returns: OS_INVALID_POINTER if a pointer passed in is NULL OS_ERR_NAME_TOO_LONG if the name passed in is too long OS_ERR_NO_FREE_IDS if there are already the max queues created OS_ERR_NAME_TAKEN if the name is already being used on another queue OS_ERROR if the OS create call fails OS_SUCCESS if success Notes: the flags parameter is unused. ---------------------------------------------------------------------------------------*/ int32 OS_QueueCreate (uint32 *queue_id, const char *queue_name, uint32 queue_depth, uint32 data_size, uint32 flags) { int i; pid_t process_id; mqd_t queueDesc; struct mq_attr queueAttr; uint32 possible_qid; char name[OS_MAX_API_NAME * 2]; char process_id_string[OS_MAX_API_NAME+1]; sigset_t previous; sigset_t mask; if ( queue_id == NULL || queue_name == NULL) { return OS_INVALID_POINTER; } /* we don't want to allow names too long*/ /* if truncated, two names might be the same */ if (strlen(queue_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } /* Check Parameters */ OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); for(possible_qid = 0; possible_qid < OS_MAX_QUEUES; possible_qid++) { if (OS_queue_table[possible_qid].free == TRUE) break; } if( possible_qid >= OS_MAX_QUEUES || OS_queue_table[possible_qid].free != TRUE) { OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_ERR_NO_FREE_IDS; } /* Check to see if the name is already taken */ for (i = 0; i < OS_MAX_QUEUES; i++) { if ((OS_queue_table[i].free == FALSE) && strcmp ((char*) queue_name, OS_queue_table[i].name) == 0) { OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_ERR_NAME_TAKEN; } } /* Set the possible task Id to not free so that * no other task can try to use it */ OS_queue_table[possible_qid].free = FALSE; OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); /* set queue attributes */ queueAttr.mq_maxmsg = queue_depth; queueAttr.mq_msgsize = data_size; /* ** Construct the queue name: ** The name will consist of "/<process_id>.queue_name" */ /* pre-pend / to queue name */ strcpy(name, "/"); /* ** Get the process ID */ process_id = getpid(); sprintf(process_id_string, "%d", process_id); strcat(name, process_id_string); strcat(name,"."); /* ** Add the name that was passed in */ strcat(name, queue_name); /* ** create message queue */ queueDesc = mq_open(name, O_CREAT | O_RDWR, 0666, &queueAttr); if ( queueDesc == -1 ) { OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); OS_queue_table[possible_qid].free = TRUE; OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("OS_QueueCreate Error. errno = %d\n",errno); #endif if( errno ==EINVAL) { printf("Your queue depth may be too large for the\n"); printf("OS to handle. Please check the msg_max\n"); printf("parameter located in /proc/sys/fs/mqueue/msg_max\n"); printf("on your Linux file system and raise it if you\n"); printf(" need to or run as root\n"); } return OS_ERROR; } /* ** store queue_descriptor */ *queue_id = possible_qid; OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); OS_queue_table[*queue_id].id = queueDesc; OS_queue_table[*queue_id].free = FALSE; OS_queue_table[*queue_id].max_size = data_size; strcpy( OS_queue_table[*queue_id].name, (char*) queue_name); OS_queue_table[*queue_id].creator = OS_FindCreator(); OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_SUCCESS; }/* end OS_QueueCreate */ /*-------------------------------------------------------------------------------------- Name: OS_QueueDelete Purpose: Deletes the specified message queue. Returns: OS_ERR_INVALID_ID if the id passed in does not exist OS_ERROR if the OS call to delete the queue fails OS_SUCCESS if success Notes: If There are messages on the queue, they will be lost and any subsequent calls to QueueGet or QueuePut to this queue will result in errors ---------------------------------------------------------------------------------------*/ int32 OS_QueueDelete (uint32 queue_id) { pid_t process_id; char name[OS_MAX_API_NAME+1]; char process_id_string[OS_MAX_API_NAME+1]; sigset_t previous; sigset_t mask; /* Check to see if the queue_id given is valid */ if (queue_id >= OS_MAX_QUEUES || OS_queue_table[queue_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* ** Construct the queue name: ** The name will consist of "/<process_id>.queue_name" */ /* pre-pend / to queue name */ strcpy(name, "/"); /* ** Get the process ID */ process_id = getpid(); sprintf(process_id_string, "%d", process_id); strcat(name, process_id_string); strcat(name,"."); strcat(name, OS_queue_table[queue_id].name); /* Try to delete and unlink the queue */ if((mq_close(OS_queue_table[queue_id].id) == -1) || (mq_unlink(name) == -1)) { return OS_ERROR; } /* * Now that the queue is deleted, remove its "presence" * in OS_message_q_table and OS_message_q_name_table */ OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); OS_queue_table[queue_id].free = TRUE; strcpy(OS_queue_table[queue_id].name, ""); OS_queue_table[queue_id].creator = UNINITIALIZED; OS_queue_table[queue_id].max_size = 0; OS_queue_table[queue_id].id = UNINITIALIZED; OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_SUCCESS; } /* end OS_QueueDelete */ /*--------------------------------------------------------------------------------------- Name: OS_QueueGet Purpose: Receive a message on a message queue. Will pend or timeout on the receive. Returns: OS_ERR_INVALID_ID if the given ID does not exist OS_ERR_INVALID_POINTER if a pointer passed in is NULL OS_QUEUE_EMPTY if the Queue has no messages on it to be recieved OS_QUEUE_TIMEOUT if the timeout was OS_PEND and the time expired OS_QUEUE_INVALID_SIZE if the size of the buffer passed in is not big enough for the maximum size message OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_QueueGet (uint32 queue_id, void *data, uint32 size, uint32 *size_copied, int32 timeout) { struct mq_attr queueAttr; int sizeCopied = -1; struct timespec ts; /* ** Check Parameters */ if(queue_id >= OS_MAX_QUEUES || OS_queue_table[queue_id].free == TRUE) { return OS_ERR_INVALID_ID; } else if( (data == NULL) || (size_copied == NULL) ) { return OS_INVALID_POINTER; } else if( size < OS_queue_table[queue_id].max_size ) { /* ** The buffer that the user is passing in is potentially too small ** RTEMS will just copy into a buffer that is too small */ *size_copied = 0; return(OS_QUEUE_INVALID_SIZE); } /* ** Read the message queue for data */ if (timeout == OS_PEND) { /* ** A signal can interrupt the mq_receive call, so the call has to be done with ** a loop */ do { sizeCopied = mq_receive(OS_queue_table[queue_id].id, data, size, NULL); } while ((sizeCopied == -1) && (errno == EINTR)); if (sizeCopied == -1) { *size_copied = 0; return(OS_ERROR); } else { *size_copied = sizeCopied; } } else if (timeout == OS_CHECK) { /* get queue attributes */ if(mq_getattr(OS_queue_table[queue_id].id, &queueAttr)) { *size_copied = 0; return (OS_ERROR); } /* check how many messages in queue */ if(queueAttr.mq_curmsgs > 0) { do { sizeCopied = mq_receive(OS_queue_table[queue_id].id, data, size, NULL); } while ( sizeCopied == -1 && errno == EINTR ); if (sizeCopied == -1) { *size_copied = 0; return(OS_ERROR); } else { *size_copied = sizeCopied; } } else { *size_copied = 0; return (OS_QUEUE_EMPTY); } } else /* timeout */ { OS_CompAbsDelayTime( timeout , &ts) ; /* ** If the mq_timedreceive call is interrupted by a system call or signal, ** call it again. */ do { sizeCopied = mq_timedreceive(OS_queue_table[queue_id].id, data, size, NULL, &ts); } while ( sizeCopied == -1 && errno == EINTR ); if((sizeCopied == -1) && (errno == ETIMEDOUT)) { return(OS_QUEUE_TIMEOUT); } else if (sizeCopied == -1) { *size_copied = 0; return(OS_ERROR); } else { *size_copied = sizeCopied; } } /* END timeout */ return OS_SUCCESS; } /* end OS_QueueGet */ /*--------------------------------------------------------------------------------------- Name: OS_QueuePut Purpose: Put a message on a message queue. Returns: OS_ERR_INVALID_ID if the queue id passed in is not a valid queue OS_INVALID_POINTER if the data pointer is NULL OS_QUEUE_FULL if the queue cannot accept another message OS_ERROR if the OS call returns an error OS_SUCCESS if SUCCESS Notes: The flags parameter is not used. The message put is always configured to immediately return an error if the receiving message queue is full. ---------------------------------------------------------------------------------------*/ int32 OS_QueuePut (uint32 queue_id, void *data, uint32 size, uint32 flags) { struct mq_attr queueAttr; /* ** Check Parameters */ if(queue_id >= OS_MAX_QUEUES || OS_queue_table[queue_id].free == TRUE) { return OS_ERR_INVALID_ID; } if (data == NULL) { return OS_INVALID_POINTER; } /* get queue attributes */ if(mq_getattr(OS_queue_table[queue_id].id, &queueAttr)) { return (OS_ERROR); } /* check if queue is full */ if(queueAttr.mq_curmsgs >= queueAttr.mq_maxmsg) { return(OS_QUEUE_FULL); } /* send message */ if(mq_send(OS_queue_table[queue_id].id, data, size, 1) == -1) { return(OS_ERROR); } return OS_SUCCESS; } /* end OS_QueuePut */ /* --------------------- END POSIX MESSAGE QUEUE IMPLEMENTATION ---------------------- */ #endif /*-------------------------------------------------------------------------------------- Name: OS_QueueGetIdByName Purpose: This function tries to find a queue Id given the name of the queue. The id of the queue is passed back in queue_id Returns: OS_INVALID_POINTER if the name or id pointers are NULL OS_ERR_NAME_TOO_LONG the name passed in is too long OS_ERR_NAME_NOT_FOUND the name was not found in the table OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_QueueGetIdByName (uint32 *queue_id, const char *queue_name) { uint32 i; if(queue_id == NULL || queue_name == NULL) { return OS_INVALID_POINTER; } /* a name too long wouldn't have been allowed in the first place * so we definitely won't find a name too long*/ if (strlen(queue_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } for (i = 0; i < OS_MAX_QUEUES; i++) { if (OS_queue_table[i].free != TRUE && (strcmp(OS_queue_table[i].name, (char*) queue_name) == 0 )) { *queue_id = i; return OS_SUCCESS; } } /* The name was not found in the table, * or it was, and the queue_id isn't valid anymore */ return OS_ERR_NAME_NOT_FOUND; }/* end OS_QueueGetIdByName */ /*--------------------------------------------------------------------------------------- Name: OS_QueueGetInfo Purpose: This function will pass back a pointer to structure that contains all of the relevant info (name and creator) about the specified queue. Returns: OS_INVALID_POINTER if queue_prop is NULL OS_ERR_INVALID_ID if the ID given is not a valid queue OS_SUCCESS if the info was copied over correctly ---------------------------------------------------------------------------------------*/ int32 OS_QueueGetInfo (uint32 queue_id, OS_queue_prop_t *queue_prop) { sigset_t previous; sigset_t mask; /* Check to see that the id given is valid */ if (queue_prop == NULL) { return OS_INVALID_POINTER; } if (queue_id >= OS_MAX_QUEUES || OS_queue_table[queue_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* put the info into the stucture */ OS_InterruptSafeLock(&OS_queue_table_mut, &mask, &previous); queue_prop -> creator = OS_queue_table[queue_id].creator; strcpy(queue_prop -> name, OS_queue_table[queue_id].name); OS_InterruptSafeUnlock(&OS_queue_table_mut, &previous); return OS_SUCCESS; } /* end OS_QueueGetInfo */ /**************************************************************************************** SEMAPHORE API ****************************************************************************************/ /*--------------------------------------------------------------------------------------- Name: OS_BinSemCreate Purpose: Creates a binary semaphore with initial value specified by sem_initial_value and name specified by sem_name. sem_id will be returned to the caller Returns: OS_INVALID_POINTER if sen name or sem_id are NULL OS_ERR_NAME_TOO_LONG if the name given is too long OS_ERR_NO_FREE_IDS if all of the semaphore ids are taken OS_ERR_NAME_TAKEN if this is already the name of a binary semaphore OS_SEM_FAILURE if the OS call failed OS_SUCCESS if success Notes: options is an unused parameter ---------------------------------------------------------------------------------------*/ int32 OS_BinSemCreate (uint32 *sem_id, const char *sem_name, uint32 sem_initial_value, uint32 options) { uint32 possible_semid; uint32 i; int Status; pthread_mutexattr_t mutex_attr; sigset_t previous; sigset_t mask; /* ** Check Parameters */ if (sem_id == NULL || sem_name == NULL) { return OS_INVALID_POINTER; } /* ** Check for maximum name length */ if (strlen(sem_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } /* Lock table */ OS_InterruptSafeLock(&OS_bin_sem_table_mut, &mask, &previous); for (possible_semid = 0; possible_semid < OS_MAX_BIN_SEMAPHORES; possible_semid++) { if (OS_bin_sem_table[possible_semid].free == TRUE) break; } if((possible_semid >= OS_MAX_BIN_SEMAPHORES) || (OS_bin_sem_table[possible_semid].free != TRUE)) { OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); return OS_ERR_NO_FREE_IDS; } /* Check to see if the name is already taken */ for (i = 0; i < OS_MAX_BIN_SEMAPHORES; i++) { if ((OS_bin_sem_table[i].free == FALSE) && strcmp ((char*) sem_name, OS_bin_sem_table[i].name) == 0) { OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); return OS_ERR_NAME_TAKEN; } } /* ** Check to make sure the value is 0 or 1 */ if (sem_initial_value < 0) { sem_initial_value = 0; } else if ( sem_initial_value > 1 ) { sem_initial_value = 1; } /* ** Initialize the pthread mutex attribute structure with default values */ errno = 0; Status = pthread_mutexattr_init(&mutex_attr); if ( Status == 0 ) { /* ** Use priority inheritance */ Status = pthread_mutexattr_setprotocol(&mutex_attr,PTHREAD_PRIO_INHERIT); if ( Status == 0 ) { /* ** Initialize the mutex that is used with the condition variable */ Status = pthread_mutex_init(&(OS_bin_sem_table[possible_semid].id), &mutex_attr); if( Status == 0 ) { /* ** Initialize the condition variable */ Status = pthread_cond_init(&(OS_bin_sem_table[possible_semid].cv), NULL); if ( Status == 0 ) { /* ** fill out the proper OSAL table fields */ *sem_id = possible_semid; strcpy(OS_bin_sem_table[*sem_id].name , (char*) sem_name); OS_bin_sem_table[*sem_id].creator = OS_FindCreator(); OS_bin_sem_table[*sem_id].max_value = 1; OS_bin_sem_table[*sem_id].current_value = sem_initial_value; OS_bin_sem_table[*sem_id].free = FALSE; /* Unlock table */ OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); return OS_SUCCESS; } else { OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_cond_init failed\n"); #endif return (OS_SEM_FAILURE); } } else { OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutex_init failed\n"); #endif return (OS_SEM_FAILURE); } } else { OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutexattr_setprotocol failed\n"); #endif return (OS_SEM_FAILURE); } } else { OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutexattr_init failed\n"); #endif return (OS_SEM_FAILURE); } }/* end OS_BinSemCreate */ /*-------------------------------------------------------------------------------------- Name: OS_BinSemDelete Purpose: Deletes the specified Binary Semaphore. Returns: OS_ERR_INVALID_ID if the id passed in is not a valid binary semaphore OS_SEM_FAILURE the OS call failed OS_SUCCESS if success Notes: Since we can't delete a semaphore which is currently locked by some task (as it may ber crucial to completing the task), the semaphore must be full to allow deletion. ---------------------------------------------------------------------------------------*/ int32 OS_BinSemDelete (uint32 sem_id) { sigset_t previous; sigset_t mask; /* Check to see if this sem_id is valid */ if (sem_id >= OS_MAX_BIN_SEMAPHORES || OS_bin_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Lock table */ OS_InterruptSafeLock(&OS_bin_sem_table_mut, &mask, &previous); /* Remove the Id from the table, and its name, so that it cannot be found again */ pthread_mutex_destroy(&(OS_bin_sem_table[sem_id].id)); pthread_cond_destroy(&(OS_bin_sem_table[sem_id].cv)); OS_bin_sem_table[sem_id].free = TRUE; strcpy(OS_bin_sem_table[sem_id].name , ""); OS_bin_sem_table[sem_id].creator = UNINITIALIZED; OS_bin_sem_table[sem_id].max_value = 0; OS_bin_sem_table[sem_id].current_value = 0; /* Unlock table */ OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); return OS_SUCCESS; }/* end OS_BinSemDelete */ /*--------------------------------------------------------------------------------------- Name: OS_BinSemGive Purpose: The function unlocks the semaphore referenced by sem_id by performing a semaphore unlock operation on that semaphore.If the semaphore value resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become unlocked; the semaphore value is simply incremented for this semaphore. Returns: OS_SEM_FAILURE the semaphore was not previously initialized or is not in the array of semaphores defined by the system OS_ERR_INVALID_ID if the id passed in is not a binary semaphore OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_BinSemGive ( uint32 sem_id ) { int ret; sigset_t previous; sigset_t mask; /* Check Parameters */ if(sem_id >= OS_MAX_BIN_SEMAPHORES || OS_bin_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Lock the mutex ( not the table! ) */ ret = OS_InterruptSafeLock(&(OS_bin_sem_table[sem_id].id), &mask, &previous); if ( ret != 0 ) { return(OS_SEM_FAILURE); } /* ** If the sem value is not full ( 1 ) then increment it. */ if ( OS_bin_sem_table[sem_id].current_value < OS_bin_sem_table[sem_id].max_value ) { OS_bin_sem_table[sem_id].current_value ++; pthread_cond_signal(&(OS_bin_sem_table[sem_id].cv)); } OS_InterruptSafeUnlock(&(OS_bin_sem_table[sem_id].id), &previous); return (OS_SUCCESS); }/* end OS_BinSemGive */ /*--------------------------------------------------------------------------------------- Name: OS_BinSemFlush Purpose: The function unblocks all tasks pending on the specified semaphore. However, this function does not change the state of the semaphore. Returns: OS_SEM_FAILURE the semaphore was not previously initialized or is not in the array of semaphores defined by the system OS_ERR_INVALID_ID if the id passed in is not a binary semaphore OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_BinSemFlush (uint32 sem_id) { uint32 ret_val; int32 ret = 0; sigset_t previous; sigset_t mask; /* Check Parameters */ if(sem_id >= OS_MAX_BIN_SEMAPHORES || OS_bin_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Lock the mutex ( not the table! ) */ ret = OS_InterruptSafeLock(&(OS_bin_sem_table[sem_id].id), &mask, &previous); if ( ret != 0 ) { return(OS_SEM_FAILURE); } /* ** Release all threads waiting on the binary semaphore */ ret = pthread_cond_broadcast(&(OS_bin_sem_table[sem_id].cv)); if ( ret == 0 ) { ret_val = OS_SUCCESS ; OS_bin_sem_table[sem_id].current_value = OS_bin_sem_table[sem_id].max_value; } else { ret_val = OS_SEM_FAILURE; } OS_InterruptSafeUnlock(&(OS_bin_sem_table[sem_id].id), &previous); return(ret_val); }/* end OS_BinSemFlush */ /*--------------------------------------------------------------------------------------- Name: OS_BinSemTake Purpose: The locks the semaphore referenced by sem_id by performing a semaphore lock operation on that semaphore.If the semaphore value is currently zero, then the calling thread shall not return from the call until it either locks the semaphore or the call is interrupted by a signal. Return: OS_ERR_INVALID_ID the Id passed in is not a valid binary semaphore OS_SEM_FAILURE if the OS call failed OS_SUCCESS if success ----------------------------------------------------------------------------------------*/ int32 OS_BinSemTake ( uint32 sem_id ) { uint32 ret_val; int ret; sigset_t previous; sigset_t mask; /* Check parameters */ if(sem_id >= OS_MAX_BIN_SEMAPHORES || OS_bin_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Lock the mutex */ ret = OS_InterruptSafeLock(&(OS_bin_sem_table[sem_id].id), &mask, &previous); if ( ret != 0 ) { return(OS_SEM_FAILURE); } /* ** If the value is less than the max (1) ** wait until it is available ** If the value is max (1), then grab the resource without waiting */ if ( OS_bin_sem_table[sem_id].current_value < OS_bin_sem_table[sem_id].max_value ) { /* ** Wait on the condition variable. Calling this function unlocks the mutex and ** re-aquires the mutex when the function returns. This allows the function that ** calls the pthread_cond_signal or pthread_cond_broadcast to aquire the mutex */ ret = pthread_cond_wait(&(OS_bin_sem_table[sem_id].cv),&(OS_bin_sem_table[sem_id].id)); if ( ret == 0 ) { ret_val = OS_SUCCESS; /* ** Decrement the counter */ OS_bin_sem_table[sem_id].current_value --; } else { ret_val = OS_SEM_FAILURE; } } else { OS_bin_sem_table[sem_id].current_value --; ret_val = OS_SUCCESS; } /* Unlock the mutex */ OS_InterruptSafeUnlock(&(OS_bin_sem_table[sem_id].id), &previous); return (ret_val); }/* end OS_BinSemTake */ /*--------------------------------------------------------------------------------------- Name: OS_BinSemTimedWait Purpose: The function locks the semaphore referenced by sem_id . However, if the semaphore cannot be locked without waiting for another process or thread to unlock the semaphore , this wait shall be terminated when the specified timeout ,msecs, expires. Returns: OS_SEM_TIMEOUT if semaphore was not relinquished in time OS_SUCCESS if success OS_SEM_FAILURE the semaphore was not previously initialized or is not in the array of semaphores defined by the system OS_ERR_INVALID_ID if the ID passed in is not a valid semaphore ID ----------------------------------------------------------------------------------------*/ int32 OS_BinSemTimedWait ( uint32 sem_id, uint32 msecs ) { int ret; uint32 ret_val; struct timespec ts; sigset_t previous; sigset_t mask; if( (sem_id >= OS_MAX_BIN_SEMAPHORES) || (OS_bin_sem_table[sem_id].free == TRUE) ) { return OS_ERR_INVALID_ID; } /* ** Compute an absolute time for the delay */ OS_CompAbsDelayTime(msecs, &ts); /* Lock the mutex */ ret = OS_InterruptSafeLock(&(OS_bin_sem_table[sem_id].id), &mask, &previous); if ( ret != 0 ) { return(OS_SEM_FAILURE); } /* ** If the value is less than the max (1) ** wait until it is available ** If the value is max (1), then grab the resource */ if ( OS_bin_sem_table[sem_id].current_value < OS_bin_sem_table[sem_id].max_value ) { /* ** Wait on the condition variable. Calling this function unlocks the mutex and ** re-aquires the mutex when the function returns. This allows the function that ** calls the pthread_cond_signal or pthread_cond_broadcast to aquire the mutex */ ret = pthread_cond_timedwait(&(OS_bin_sem_table[sem_id].cv), &(OS_bin_sem_table[sem_id].id), &ts); if ( ret == 0 ) { ret_val = OS_SUCCESS; /* Decrement the counter */ OS_bin_sem_table[sem_id].current_value --; } else if ( ret == ETIMEDOUT ) { ret_val = OS_SEM_TIMEOUT; } else { ret_val = OS_SEM_FAILURE; } } else { OS_bin_sem_table[sem_id].current_value --; ret_val = OS_SUCCESS; } /* Unlock the mutex */ OS_InterruptSafeUnlock(&(OS_bin_sem_table[sem_id].id), &previous); return ret_val; } /*-------------------------------------------------------------------------------------- Name: OS_BinSemGetIdByName Purpose: This function tries to find a binary sem Id given the name of a bin_sem The id is returned through sem_id Returns: OS_INVALID_POINTER is semid or sem_name are NULL pointers OS_ERR_NAME_TOO_LONG if the name given is to long to have been stored OS_ERR_NAME_NOT_FOUND if the name was not found in the table OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_BinSemGetIdByName (uint32 *sem_id, const char *sem_name) { uint32 i; /* Check parameters */ if (sem_id == NULL || sem_name == NULL) { return OS_INVALID_POINTER; } /* ** a name too long wouldn't have been allowed in the first place ** so we definitely won't find a name too long */ if (strlen(sem_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } for (i = 0; i < OS_MAX_BIN_SEMAPHORES; i++) { if (OS_bin_sem_table[i].free != TRUE && (strcmp (OS_bin_sem_table[i].name , (char*) sem_name) == 0)) { *sem_id = i; return OS_SUCCESS; } } /* ** The name was not found in the table, ** or it was, and the sem_id isn't valid anymore */ return OS_ERR_NAME_NOT_FOUND; }/* end OS_BinSemGetIdByName */ /*--------------------------------------------------------------------------------------- Name: OS_BinSemGetInfo Purpose: This function will pass back a pointer to structure that contains all of the relevant info( name and creator) about the specified binary semaphore. Returns: OS_ERR_INVALID_ID if the id passed in is not a valid semaphore OS_INVALID_POINTER if the bin_prop pointer is null OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_BinSemGetInfo (uint32 sem_id, OS_bin_sem_prop_t *bin_prop) { sigset_t previous; sigset_t mask; /* Check parameters */ if (sem_id >= OS_MAX_BIN_SEMAPHORES || OS_bin_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } if (bin_prop == NULL) { return OS_INVALID_POINTER; } /* put the info into the stucture */ OS_InterruptSafeLock(&OS_bin_sem_table_mut, &mask, &previous); bin_prop ->creator = OS_bin_sem_table[sem_id].creator; bin_prop -> value = OS_bin_sem_table[sem_id].current_value ; strcpy(bin_prop-> name, OS_bin_sem_table[sem_id].name); OS_InterruptSafeUnlock(&OS_bin_sem_table_mut, &previous); return OS_SUCCESS; } /* end OS_BinSemGetInfo */ /*--------------------------------------------------------------------------------------- Name: OS_CountSemCreate Purpose: Creates a counting semaphore with initial value specified by sem_initial_value and name specified by sem_name. sem_id will be returned to the caller Returns: OS_INVALID_POINTER if sen name or sem_id are NULL OS_ERR_NAME_TOO_LONG if the name given is too long OS_ERR_NO_FREE_IDS if all of the semaphore ids are taken OS_ERR_NAME_TAKEN if this is already the name of a counting semaphore OS_SEM_FAILURE if the OS call failed OS_INVALID_SEM_VALUE if the semaphore value is too high OS_SUCCESS if success Notes: options is an unused parameter ---------------------------------------------------------------------------------------*/ int32 OS_CountSemCreate (uint32 *sem_id, const char *sem_name, uint32 sem_initial_value, uint32 options) { uint32 possible_semid; uint32 i; int Status; pthread_mutexattr_t mutex_attr; sigset_t previous; sigset_t mask; /* ** Check Parameters */ if (sem_id == NULL || sem_name == NULL) { return OS_INVALID_POINTER; } /* ** Check for maximum name length */ if (strlen(sem_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } /* ** Check to make sure the value is between 0 and SEM_VALUE_MAX */ if (sem_initial_value < 0) { sem_initial_value = 0; } if ( sem_initial_value > SEM_VALUE_MAX ) { return OS_INVALID_SEM_VALUE; } /* Lock table */ OS_InterruptSafeLock(&OS_count_sem_table_mut, &mask, &previous); for (possible_semid = 0; possible_semid < OS_MAX_COUNT_SEMAPHORES; possible_semid++) { if (OS_count_sem_table[possible_semid].free == TRUE) break; } if((possible_semid >= OS_MAX_COUNT_SEMAPHORES) || (OS_count_sem_table[possible_semid].free != TRUE)) { OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); return OS_ERR_NO_FREE_IDS; } /* Check to see if the name is already taken */ for (i = 0; i < OS_MAX_COUNT_SEMAPHORES; i++) { if ((OS_count_sem_table[i].free == FALSE) && strcmp ((char*) sem_name, OS_count_sem_table[i].name) == 0) { OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); return OS_ERR_NAME_TAKEN; } } /* ** Initialize the pthread mutex attribute structure with default values */ errno = 0; Status = pthread_mutexattr_init(&mutex_attr); if ( Status == 0 ) { /* ** Use priority inheritance */ Status = pthread_mutexattr_setprotocol(&mutex_attr,PTHREAD_PRIO_INHERIT); if ( Status == 0 ) { /* ** Initialize the mutex that is used with the condition variable */ Status = pthread_mutex_init(&(OS_count_sem_table[possible_semid].id), &mutex_attr); if( Status == 0 ) { /* ** Initialize the condition variable */ Status = pthread_cond_init(&(OS_count_sem_table[possible_semid].cv), NULL); if ( Status == 0 ) { /* ** fill out the proper OSAL table fields */ *sem_id = possible_semid; strcpy(OS_count_sem_table[*sem_id].name , (char*) sem_name); OS_count_sem_table[*sem_id].creator = OS_FindCreator(); OS_count_sem_table[*sem_id].max_value = SEM_VALUE_MAX; OS_count_sem_table[*sem_id].current_value = sem_initial_value; OS_count_sem_table[*sem_id].free = FALSE; /* Unlock table */ OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); return OS_SUCCESS; } else { OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_cond_init failed\n"); #endif return (OS_SEM_FAILURE); } } else { OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutex_init failed\n"); #endif return (OS_SEM_FAILURE); } } else { OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutexattr_setprotocol failed\n"); #endif return (OS_SEM_FAILURE); } } else { OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: pthread_mutexattr_init failed\n"); #endif return (OS_SEM_FAILURE); } }/* end OS_CountSemCreate */ /*-------------------------------------------------------------------------------------- Name: OS_CountSemDelete Purpose: Deletes the specified Countary Semaphore. Returns: OS_ERR_INVALID_ID if the id passed in is not a valid counting semaphore OS_SEM_FAILURE the OS call failed OS_SUCCESS if success Notes: Since we can't delete a semaphore which is currently locked by some task (as it may ber crucial to completing the task), the semaphore must be full to allow deletion. ---------------------------------------------------------------------------------------*/ int32 OS_CountSemDelete (uint32 sem_id) { sigset_t previous; sigset_t mask; /* Check to see if this sem_id is valid */ if (sem_id >= OS_MAX_COUNT_SEMAPHORES || OS_count_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Lock table */ OS_InterruptSafeLock(&OS_count_sem_table_mut, &mask, &previous); /* Remove the Id from the table, and its name, so that it cannot be found again */ pthread_mutex_destroy(&(OS_count_sem_table[sem_id].id)); pthread_cond_destroy(&(OS_count_sem_table[sem_id].cv)); OS_count_sem_table[sem_id].free = TRUE; strcpy(OS_count_sem_table[sem_id].name , ""); OS_count_sem_table[sem_id].creator = UNINITIALIZED; OS_count_sem_table[sem_id].max_value = 0; OS_count_sem_table[sem_id].current_value = 0; /* Unlock table */ OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); return OS_SUCCESS; }/* end OS_CountSemDelete */ /*--------------------------------------------------------------------------------------- Name: OS_CountSemGive Purpose: The function unlocks the semaphore referenced by sem_id by performing a semaphore unlock operation on that semaphore.If the semaphore value resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become unlocked; the semaphore value is simply incremented for this semaphore. Returns: OS_SEM_FAILURE the semaphore was not previously initialized or is not in the array of semaphores defined by the system OS_ERR_INVALID_ID if the id passed in is not a counting semaphore OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_CountSemGive ( uint32 sem_id ) { int ret; sigset_t previous; sigset_t mask; /* Check Parameters */ if(sem_id >= OS_MAX_COUNT_SEMAPHORES || OS_count_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Lock the mutex ( not the table! ) */ ret = OS_InterruptSafeLock(&(OS_count_sem_table[sem_id].id), &mask, &previous); if ( ret != 0 ) { return(OS_SEM_FAILURE); } /* ** If the sem value is less than or equal to 0, there are waiters. ** If the count is from 1 to max, there are no waiters */ if ( OS_count_sem_table[sem_id].current_value <= 0 ) { OS_count_sem_table[sem_id].current_value ++; pthread_cond_signal(&(OS_count_sem_table[sem_id].cv)); } else if ( OS_count_sem_table[sem_id].current_value < OS_count_sem_table[sem_id].max_value ) { OS_count_sem_table[sem_id].current_value ++; } OS_InterruptSafeUnlock(&(OS_count_sem_table[sem_id].id), &previous); return (OS_SUCCESS); }/* end OS_CountSemGive */ /*--------------------------------------------------------------------------------------- Name: OS_CountSemTake Purpose: The locks the semaphore referenced by sem_id by performing a semaphore lock operation on that semaphore.If the semaphore value is currently zero, then the calling thread shall not return from the call until it either locks the semaphore or the call is interrupted by a signal. Return: OS_ERR_INVALID_ID the Id passed in is not a valid counting semaphore OS_SEM_FAILURE if the OS call failed OS_SUCCESS if success ----------------------------------------------------------------------------------------*/ int32 OS_CountSemTake ( uint32 sem_id ) { uint32 ret_val; int ret; sigset_t previous; sigset_t mask; /* Check parameters */ if(sem_id >= OS_MAX_COUNT_SEMAPHORES || OS_count_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* Lock the mutex */ ret = OS_InterruptSafeLock(&(OS_count_sem_table[sem_id].id), &mask, &previous); if ( ret != 0 ) { return(OS_SEM_FAILURE); } /* ** If the value is <= 0, then wait until the semaphore is available ** If the value is > 1, then grab the resource without waiting */ if ( OS_count_sem_table[sem_id].current_value <= 0 ) { /* ** Wait on the condition variable. Calling this function unlocks the mutex and ** re-aquires the mutex when the function returns. This allows the function that ** calls the pthread_cond_signal or pthread_cond_broadcast to aquire the mutex */ ret = pthread_cond_wait(&(OS_count_sem_table[sem_id].cv),&(OS_count_sem_table[sem_id].id)); if ( ret == 0 ) { ret_val = OS_SUCCESS; /* ** Decrement the counter */ OS_count_sem_table[sem_id].current_value --; } else { ret_val = OS_SEM_FAILURE; } } else /* Grab the sem */ { OS_count_sem_table[sem_id].current_value --; ret_val = OS_SUCCESS; } /* Unlock the mutex */ OS_InterruptSafeUnlock(&(OS_count_sem_table[sem_id].id), &previous); return (ret_val); }/* end OS_CountSemTake */ /*--------------------------------------------------------------------------------------- Name: OS_CountSemTimedWait Purpose: The function locks the semaphore referenced by sem_id . However, if the semaphore cannot be locked without waiting for another process or thread to unlock the semaphore , this wait shall be terminated when the specified timeout ,msecs, expires. Returns: OS_SEM_TIMEOUT if semaphore was not relinquished in time OS_SUCCESS if success OS_SEM_FAILURE the semaphore was not previously initialized or is not in the array of semaphores defined by the system OS_ERR_INVALID_ID if the ID passed in is not a valid semaphore ID ----------------------------------------------------------------------------------------*/ int32 OS_CountSemTimedWait ( uint32 sem_id, uint32 msecs ) { int ret; uint32 ret_val; struct timespec ts; sigset_t previous; sigset_t mask; if( (sem_id >= OS_MAX_COUNT_SEMAPHORES) || (OS_count_sem_table[sem_id].free == TRUE) ) { return OS_ERR_INVALID_ID; } /* ** Compute an absolute time for the delay */ OS_CompAbsDelayTime(msecs, &ts); /* Lock the mutex */ ret = OS_InterruptSafeLock(&(OS_count_sem_table[sem_id].id), &mask, &previous); if ( ret != 0 ) { return(OS_SEM_FAILURE); } /* ** If the value is <= 0, then wait until the semaphore is available ** If the value is > 1, then grab the resource without waiting */ if ( OS_count_sem_table[sem_id].current_value <= 0 ) { /* ** Wait on the condition variable. Calling this function unlocks the mutex and ** re-aquires the mutex when the function returns. This allows the function that ** calls the pthread_cond_signal or pthread_cond_broadcast to aquire the mutex */ ret = pthread_cond_timedwait(&(OS_count_sem_table[sem_id].cv), &(OS_count_sem_table[sem_id].id), &ts); if ( ret == 0 ) { ret_val = OS_SUCCESS; /* Decrement the counter */ OS_count_sem_table[sem_id].current_value --; } else if ( ret == ETIMEDOUT ) { ret_val = OS_SEM_TIMEOUT; } else { ret_val = OS_SEM_FAILURE; } } else /* Grab the sem */ { OS_count_sem_table[sem_id].current_value --; ret_val = OS_SUCCESS; } /* Unlock the mutex */ OS_InterruptSafeUnlock(&(OS_count_sem_table[sem_id].id), &previous); return ret_val; } /*-------------------------------------------------------------------------------------- Name: OS_CountSemGetIdByName Purpose: This function tries to find a counting sem Id given the name of a count_sem The id is returned through sem_id Returns: OS_INVALID_POINTER is semid or sem_name are NULL pointers OS_ERR_NAME_TOO_LONG if the name given is to long to have been stored OS_ERR_NAME_NOT_FOUND if the name was not found in the table OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_CountSemGetIdByName (uint32 *sem_id, const char *sem_name) { uint32 i; if (sem_id == NULL || sem_name == NULL) { return OS_INVALID_POINTER; } /* ** a name too long wouldn't have been allowed in the first place ** so we definitely won't find a name too long */ if (strlen(sem_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } for (i = 0; i < OS_MAX_COUNT_SEMAPHORES; i++) { if (OS_count_sem_table[i].free != TRUE && (strcmp (OS_count_sem_table[i].name , (char*) sem_name) == 0)) { *sem_id = i; return OS_SUCCESS; } } /* ** The name was not found in the table, ** or it was, and the sem_id isn't valid anymore */ return OS_ERR_NAME_NOT_FOUND; }/* end OS_CountSemGetIdByName */ /*--------------------------------------------------------------------------------------- Name: OS_CountSemGetInfo Purpose: This function will pass back a pointer to structure that contains all of the relevant info( name and creator) about the specified counting semaphore. Returns: OS_ERR_INVALID_ID if the id passed in is not a valid semaphore OS_INVALID_POINTER if the count_prop pointer is null OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_CountSemGetInfo (uint32 sem_id, OS_count_sem_prop_t *count_prop) { sigset_t previous; sigset_t mask; /* ** Check to see that the id given is valid */ if (sem_id >= OS_MAX_COUNT_SEMAPHORES || OS_count_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } if (count_prop == NULL) { return OS_INVALID_POINTER; } /* ** Lock */ OS_InterruptSafeLock(&OS_count_sem_table_mut, &mask, &previous); /* put the info into the stucture */ count_prop -> value = OS_count_sem_table[sem_id].current_value; count_prop -> creator = OS_count_sem_table[sem_id].creator; strcpy(count_prop-> name, OS_count_sem_table[sem_id].name); /* ** Unlock */ OS_InterruptSafeUnlock(&OS_count_sem_table_mut, &previous); return OS_SUCCESS; } /* end OS_CountSemGetInfo */ /**************************************************************************************** MUTEX API ****************************************************************************************/ /*--------------------------------------------------------------------------------------- Name: OS_MutSemCreate Purpose: Creates a mutex semaphore initially full. Returns: OS_INVALID_POINTER if sem_id or sem_name are NULL OS_ERR_NAME_TOO_LONG if the sem_name is too long to be stored OS_ERR_NO_FREE_IDS if there are no more free mutex Ids OS_ERR_NAME_TAKEN if there is already a mutex with the same name OS_SEM_FAILURE if the OS call failed OS_SUCCESS if success Notes: the options parameter is not used in this implementation ---------------------------------------------------------------------------------------*/ int32 OS_MutSemCreate (uint32 *sem_id, const char *sem_name, uint32 options) { int return_code; pthread_mutexattr_t mutex_attr ; uint32 possible_semid; uint32 i; sigset_t previous; sigset_t mask; /* Check Parameters */ if (sem_id == NULL || sem_name == NULL) { return OS_INVALID_POINTER; } /* we don't want to allow names too long*/ /* if truncated, two names might be the same */ if (strlen(sem_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); for (possible_semid = 0; possible_semid < OS_MAX_MUTEXES; possible_semid++) { if (OS_mut_sem_table[possible_semid].free == TRUE) break; } if( (possible_semid == OS_MAX_MUTEXES) || (OS_mut_sem_table[possible_semid].free != TRUE) ) { OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); return OS_ERR_NO_FREE_IDS; } /* Check to see if the name is already taken */ for (i = 0; i < OS_MAX_MUTEXES; i++) { if ((OS_mut_sem_table[i].free == FALSE) && strcmp ((char*) sem_name, OS_mut_sem_table[i].name) == 0) { OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); return OS_ERR_NAME_TAKEN; } } /* Set the free flag to false to make sure no other task grabs it */ OS_mut_sem_table[possible_semid].free = FALSE; OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); /* ** initialize the attribute with default values */ return_code = pthread_mutexattr_init(&mutex_attr); if ( return_code != 0 ) { /* Since the call failed, set free back to true */ OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); OS_mut_sem_table[possible_semid].free = TRUE; OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: Mutex could not be created. pthread_mutexattr_init failed ID = %lu\n",possible_semid); #endif return OS_SEM_FAILURE; } /* ** Allow the mutex to use priority inheritance */ return_code = pthread_mutexattr_setprotocol(&mutex_attr,PTHREAD_PRIO_INHERIT) ; if ( return_code != 0 ) { /* Since the call failed, set free back to true */ OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); OS_mut_sem_table[possible_semid].free = TRUE; OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: Mutex could not be created. pthread_mutexattr_setprotocol failed ID = %lu\n",possible_semid); #endif return OS_SEM_FAILURE; } /* ** Set the mutex type to RECURSIVE so a thread can do nested locks */ return_code = pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE); if ( return_code != 0 ) { /* Since the call failed, set free back to true */ OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); OS_mut_sem_table[possible_semid].free = TRUE; OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: Mutex could not be created. pthread_mutexattr_settype failed ID = %lu\n",possible_semid); #endif return OS_SEM_FAILURE; } /* ** create the mutex ** upon successful initialization, the state of the mutex becomes initialized and unlocked */ return_code = pthread_mutex_init((pthread_mutex_t *) &OS_mut_sem_table[possible_semid].id,&mutex_attr); if ( return_code != 0 ) { /* Since the call failed, set free back to true */ OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); OS_mut_sem_table[possible_semid].free = TRUE; OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); #ifdef OS_DEBUG_PRINTF printf("Error: Mutex could not be created. ID = %lu\n",possible_semid); #endif return OS_SEM_FAILURE; } else { /* ** Mark mutex as initialized */ *sem_id = possible_semid; OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); strcpy(OS_mut_sem_table[*sem_id].name, (char*) sem_name); OS_mut_sem_table[*sem_id].free = FALSE; OS_mut_sem_table[*sem_id].creator = OS_FindCreator(); OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); return OS_SUCCESS; } }/* end OS_MutexSemCreate */ /*-------------------------------------------------------------------------------------- Name: OS_MutSemDelete Purpose: Deletes the specified Mutex Semaphore. Returns: OS_ERR_INVALID_ID if the id passed in is not a valid mutex OS_SEM_FAILURE if the OS call failed OS_SUCCESS if success Notes: The mutex must be full to take it, so we have to check for fullness ---------------------------------------------------------------------------------------*/ int32 OS_MutSemDelete (uint32 sem_id) { int status=-1; sigset_t previous; sigset_t mask; /* Check to see if this sem_id is valid */ if (sem_id >= OS_MAX_MUTEXES || OS_mut_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } status = pthread_mutex_destroy( &(OS_mut_sem_table[sem_id].id)); /* 0 = success */ if( status != 0) { return OS_SEM_FAILURE; } /* Delete its presence in the table */ OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); OS_mut_sem_table[sem_id].free = TRUE; strcpy(OS_mut_sem_table[sem_id].name , ""); OS_mut_sem_table[sem_id].creator = UNINITIALIZED; OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); return OS_SUCCESS; }/* end OS_MutSemDelete */ /*--------------------------------------------------------------------------------------- Name: OS_MutSemGive Purpose: The function releases the mutex object referenced by sem_id.The manner in which a mutex is released is dependent upon the mutex's type attribute. If there are threads blocked on the mutex object referenced by mutex when this function is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex. Returns: OS_SUCCESS if success OS_SEM_FAILURE if the semaphore was not previously initialized OS_ERR_INVALID_ID if the id passed in is not a valid mutex ---------------------------------------------------------------------------------------*/ int32 OS_MutSemGive ( uint32 sem_id ) { uint32 ret_val ; /* Check Parameters */ if(sem_id >= OS_MAX_MUTEXES || OS_mut_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* ** Unlock the mutex */ if(pthread_mutex_unlock(&(OS_mut_sem_table[sem_id].id))) { ret_val = OS_SEM_FAILURE ; } else { ret_val = OS_SUCCESS ; } return ret_val; } /* end OS_MutSemGive */ /*--------------------------------------------------------------------------------------- Name: OS_MutSemTake Purpose: The mutex object referenced by sem_id shall be locked by calling this function. If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner. Returns: OS_SUCCESS if success OS_SEM_FAILURE if the semaphore was not previously initialized or is not in the array of semaphores defined by the system OS_ERR_INVALID_ID the id passed in is not a valid mutex ---------------------------------------------------------------------------------------*/ int32 OS_MutSemTake ( uint32 sem_id ) { int status; /* ** Check Parameters */ if(sem_id >= OS_MAX_MUTEXES || OS_mut_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } /* ** Lock the mutex - unlike the sem calls, the pthread mutex call ** should not be interrupted by a signal */ status = pthread_mutex_lock(&(OS_mut_sem_table[sem_id].id)); if( status == EINVAL ) { return OS_SEM_FAILURE ; } else if ( status == EDEADLK ) { #ifdef OS_DEBUG_PRINTF printf("Task would deadlock--nested mutex call!\n"); #endif return OS_SUCCESS ; } else { return OS_SUCCESS; } } /*-------------------------------------------------------------------------------------- Name: OS_MutSemGetIdByName Purpose: This function tries to find a mutex sem Id given the name of a mut_sem The id is returned through sem_id Returns: OS_INVALID_POINTER is semid or sem_name are NULL pointers OS_ERR_NAME_TOO_LONG if the name given is to long to have been stored OS_ERR_NAME_NOT_FOUND if the name was not found in the table OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_MutSemGetIdByName (uint32 *sem_id, const char *sem_name) { uint32 i; if(sem_id == NULL || sem_name == NULL) { return OS_INVALID_POINTER; } /* ** Check parameters */ if (strlen(sem_name) >= OS_MAX_API_NAME) { return OS_ERR_NAME_TOO_LONG; } for (i = 0; i < OS_MAX_MUTEXES; i++) { if ((OS_mut_sem_table[i].free != TRUE) && (strcmp (OS_mut_sem_table[i].name, (char*) sem_name) == 0) ) { *sem_id = i; return OS_SUCCESS; } } /* ** The name was not found in the table, ** or it was, and the sem_id isn't valid anymore */ return OS_ERR_NAME_NOT_FOUND; }/* end OS_MutSemGetIdByName */ /*--------------------------------------------------------------------------------------- Name: OS_MutSemGetInfo Purpose: This function will pass back a pointer to structure that contains all of the relevant info( name and creator) about the specified mutex semaphore. Returns: OS_ERR_INVALID_ID if the id passed in is not a valid semaphore OS_INVALID_POINTER if the mut_prop pointer is null OS_SUCCESS if success ---------------------------------------------------------------------------------------*/ int32 OS_MutSemGetInfo (uint32 sem_id, OS_mut_sem_prop_t *mut_prop) { sigset_t previous; sigset_t mask; /* Check to see that the id given is valid */ if (sem_id >= OS_MAX_MUTEXES || OS_mut_sem_table[sem_id].free == TRUE) { return OS_ERR_INVALID_ID; } if (mut_prop == NULL) { return OS_INVALID_POINTER; } /* put the info into the stucture */ OS_InterruptSafeLock(&OS_mut_sem_table_mut, &mask, &previous); mut_prop -> creator = OS_mut_sem_table[sem_id].creator; strcpy(mut_prop-> name, OS_mut_sem_table[sem_id].name); OS_InterruptSafeUnlock(&OS_mut_sem_table_mut, &previous); return OS_SUCCESS; } /* end OS_BinSemGetInfo */ /**************************************************************************************** INT API ****************************************************************************************/ /*--------------------------------------------------------------------------------------- ** Name: OS_IntAttachHandler ** ** Purpose: ** The call associates a specified C routine to a specified interrupt ** number.Upon occurring of the InterruptNumber , the InerruptHandler ** routine will be called and passed the parameter. ** ** Assumptions and Notes: ** ** Parameters: ** InterruptNumber : The Interrupt Number that will cause the start of ** the ISR ** InerruptHandler : The ISR associatd with this interrupt ** parameter :The parameter that is passed to the ISR ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: ** OS_SUCCESS on success ** OS_INVALID_POINTER if the Interrupt handler pointer is NULL ---------------------------------------------------------------------------------------*/ int32 OS_IntAttachHandler (uint32 InterruptNumber, osal_task_entry InterruptHandler, int32 parameter) { if (InterruptHandler == NULL) { return OS_INVALID_POINTER; } return(OS_ERR_NOT_IMPLEMENTED); } /*--------------------------------------------------------------------------------------- ** Name: OS_IntUnlock ** Purpose: ** Enable the interrupts. ** ** Assumptions and Notes: ** ** Parameters: ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: ** OS_SUCCESS ---------------------------------------------------------------------------------------*/ int32 OS_IntUnlock (int32 IntLevel) { return(OS_ERR_NOT_IMPLEMENTED); } /*--------------------------------------------------------------------------------------- ** Name: OS_Intlock ** Purpose: ** Disable the interrupts. ** ** Assumptions and Notes: ** ** Parameters: ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: ** OS_SUCCESS ---------------------------------------------------------------------------------------*/ int32 OS_IntLock ( void ) { return(OS_ERR_NOT_IMPLEMENTED) ; } /*--------------------------------------------------------------------------------------- ** Name: OS_IntEnable ** Purpose: ** Enables interrupts through Level ** ** Assumptions and Notes: ** ** Parameters: ** Level - the interrupts to enable ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: ** OS_SUCCESS ---------------------------------------------------------------------------------------*/ int32 OS_IntEnable(int32 Level) { return(OS_ERR_NOT_IMPLEMENTED); } /*--------------------------------------------------------------------------------------- ** Name: OS_IntDisable ** Purpose: ** Disables interrupts through Level ** ** Assumptions and Notes: ** ** Parameters: ** Level - the interrupts to disable ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: ** OS_SUCCESS ---------------------------------------------------------------------------------------*/ int32 OS_IntDisable(int32 Level) { return(OS_ERR_NOT_IMPLEMENTED); } /*--------------------------------------------------------------------------------------- Name: OS_HeapGetInfo Purpose: Return current info on the heap Parameters: ---------------------------------------------------------------------------------------*/ int32 OS_HeapGetInfo (OS_heap_prop_t *heap_prop) { if (heap_prop == NULL) { return OS_INVALID_POINTER; } /* ** Not implemented yet */ return (OS_ERR_NOT_IMPLEMENTED); } /*--------------------------------------------------------------------------------------- ** Name: OS_Tick2Micros ** ** Purpose: ** This function returns the duration of a system tick in micro seconds. ** ** Assumptions and Notes: ** ** Parameters: None ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** ** Return Values: duration of a system tick in microseconds ---------------------------------------------------------------------------------------*/ int32 OS_Tick2Micros (void) { /* ** sysconf(_SC_CLK_TCK) returns ticks/second. */ return ((int32)(1000000) / sysconf(_SC_CLK_TCK)); } /*--------------------------------------------------------------------------------------- ** Name: OS_Milli2Ticks ** ** Purpose: ** This function accepts a time interval in milliseconds, as an input and ** returns the tick equivalent for this time period. The tick value is ** rounded up. ** ** Assumptions and Notes: ** ** Parameters: ** milli_seconds : the time interval ,in milli second , to be translated ** to ticks ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: the number of ticks rounded up. ---------------------------------------------------------------------------------------*/ int32 OS_Milli2Ticks(uint32 milli_seconds) { uint32 num_of_ticks; uint32 tick_duration_usec; tick_duration_usec = OS_Tick2Micros(); num_of_ticks = ((milli_seconds * 1000) + tick_duration_usec - 1)/tick_duration_usec; return(num_of_ticks); } /*--------------------------------------------------------------------------------------- * Name: OS_GetLocalTime * * Purpose: This functions get the local time of the machine its on * ------------------------------------------------------------------------------------*/ int32 OS_GetLocalTime(OS_time_t *time_struct) { int Status; int32 ReturnCode; struct timespec time; if (time_struct == NULL) { return OS_INVALID_POINTER; } Status = clock_gettime(CLOCK_REALTIME, &time); if (Status == 0) { time_struct -> seconds = time.tv_sec; time_struct -> microsecs = time.tv_nsec / 1000; ReturnCode = OS_SUCCESS; } else { printf("Error calling clock_gettime!\n"); ReturnCode = OS_ERROR; } return ReturnCode; }/* end OS_GetLocalTime */ /*--------------------------------------------------------------------------------------- * Name: OS_SetLocalTime * * Purpose: This functions set the local time of the machine its on * ------------------------------------------------------------------------------------*/ int32 OS_SetLocalTime(OS_time_t *time_struct) { int Status; int32 ReturnCode; struct timespec time; if (time_struct == NULL) { return OS_INVALID_POINTER; } time.tv_sec = time_struct -> seconds; time.tv_nsec = (time_struct -> microsecs * 1000); Status = clock_settime(CLOCK_REALTIME, &time); if (Status == 0) { ReturnCode = OS_SUCCESS; } else { ReturnCode = OS_ERROR; } return ReturnCode; } /*end OS_SetLocalTime */ /*--------------------------------------------------------------------------------------- ** Name: OS_SetMask ** Purpose: ** Set the masking register to mask and unmask interrupts ** ** Assumptions and Notes: ** ** Parameters: ** MaskSetting :the value to be written into the mask register ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: ** OS_SUCCESS ---------------------------------------------------------------------------------------*/ int32 OS_SetMask ( uint32 MaskSetting ) { return(OS_SUCCESS) ; } /*-------------------------------------------------------------------------------------- ** Name: OS_GetMask ** Purpose: ** Read and report the setting of the cpu mask register. ** ** Assumptions and Notes: ** ** Parameters: ** MaskSettingPtr : pointer to a location where the function store the ** reading of the cpu mask register. ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: ** OS_SUCCESS ---------------------------------------------------------------------------------------*/ int32 OS_GetMask ( uint32 * MaskSettingPtr ) { return(OS_SUCCESS) ; } /*-------------------------------------------------------------------------------------- * uint32 FindCreator * purpose: Finds the creator of the calling thread ---------------------------------------------------------------------------------------*/ uint32 OS_FindCreator(void) { pthread_t pthread_id; uint32 i; pthread_id = pthread_self(); /* ** Get PTHREAD Id */ for (i = 0; i < OS_MAX_TASKS; i++) { if (pthread_equal(pthread_id, OS_task_table[i].id) != 0 ) { break; } } return i; } /*--------------------------------------------------------------------------------------- ** Name: OS_CompAbsDelayTime ** ** Purpose: ** This function accept time interval, msecs, as an input and ** computes the absolute time at which this time interval will expire. ** The absolute time is programmed into a struct. ** ** Assumptions and Notes: ** ** Parameters: ** ** Global Inputs: None ** ** Global Outputs: None ** ** ** Return Values: OS_SUCCESS, ---------------------------------------------------------------------------------------*/ void OS_CompAbsDelayTime( uint32 msecs, struct timespec * tm) { clock_gettime( CLOCK_REALTIME, tm ); /* add the delay to the current time */ tm->tv_sec += (time_t) (msecs / 1000) ; /* convert residue ( msecs ) to nanoseconds */ tm->tv_nsec += (msecs % 1000) * 1000000L ; if(tm->tv_nsec >= 1000000000L ) { tm->tv_nsec -= 1000000000L ; tm->tv_sec ++ ; } } /* --------------------------------------------------------------------------- * Name: OS_printf * * Purpose: This function abstracts out the printf type statements. This is * useful for using OS- specific thats that will allow non-polled * print statements for the real time systems. ---------------------------------------------------------------------------*/ void OS_printf( const char *String, ...) { va_list ptr; char msg_buffer [OS_BUFFER_SIZE]; if ( OS_printf_enabled == TRUE ) { va_start(ptr,String); vsnprintf(&msg_buffer[0], (size_t)OS_BUFFER_SIZE, String, ptr); va_end(ptr); msg_buffer[OS_BUFFER_SIZE -1] = '\0'; printf("%s", &msg_buffer[0]); } }/* end OS_printf*/ /* --------------------------------------------------------------------------- * Name: OS_printf_disable * * Purpose: This function disables the output to the UART from OS_printf. * ---------------------------------------------------------------------------*/ void OS_printf_disable(void) { OS_printf_enabled = FALSE; }/* end OS_printf_disable*/ /* --------------------------------------------------------------------------- * Name: OS_printf_enable * * Purpose: This function enables the output to the UART through OS_printf. * ---------------------------------------------------------------------------*/ void OS_printf_enable(void) { OS_printf_enabled = TRUE; }/* end OS_printf_enable*/ /*--------------------------------------------------------------------------------------- * Name: OS_GetErrorName() ---------------------------------------------------------------------------------------*/ int32 OS_GetErrorName(int32 error_num, os_err_name_t * err_name) { os_err_name_t local_name; uint32 return_code = OS_SUCCESS; if ( err_name == NULL ) { return(OS_INVALID_POINTER); } switch (error_num) { case OS_SUCCESS: strcpy(local_name,"OS_SUCCESS"); break; case OS_ERROR: strcpy(local_name,"OS_ERROR"); break; case OS_INVALID_POINTER: strcpy(local_name,"OS_INVALID_POINTER"); break; case OS_ERROR_ADDRESS_MISALIGNED: strcpy(local_name,"OS_ADDRESS_MISALIGNED"); break; case OS_ERROR_TIMEOUT: strcpy(local_name,"OS_ERROR_TIMEOUT"); break; case OS_INVALID_INT_NUM: strcpy(local_name,"OS_INVALID_INT_NUM"); break; case OS_SEM_FAILURE: strcpy(local_name,"OS_SEM_FAILURE"); break; case OS_SEM_TIMEOUT: strcpy(local_name,"OS_SEM_TIMEOUT"); break; case OS_QUEUE_EMPTY: strcpy(local_name,"OS_QUEUE_EMPTY"); break; case OS_QUEUE_FULL: strcpy(local_name,"OS_QUEUE_FULL"); break; case OS_QUEUE_TIMEOUT: strcpy(local_name,"OS_QUEUE_TIMEOUT"); break; case OS_QUEUE_INVALID_SIZE: strcpy(local_name,"OS_QUEUE_INVALID_SIZE"); break; case OS_QUEUE_ID_ERROR: strcpy(local_name,"OS_QUEUE_ID_ERROR"); break; case OS_ERR_NAME_TOO_LONG: strcpy(local_name,"OS_ERR_NAME_TOO_LONG"); break; case OS_ERR_NO_FREE_IDS: strcpy(local_name,"OS_ERR_NO_FREE_IDS"); break; case OS_ERR_NAME_TAKEN: strcpy(local_name,"OS_ERR_NAME_TAKEN"); break; case OS_ERR_INVALID_ID: strcpy(local_name,"OS_ERR_INVALID_ID"); break; case OS_ERR_NAME_NOT_FOUND: strcpy(local_name,"OS_ERR_NAME_NOT_FOUND"); break; case OS_ERR_SEM_NOT_FULL: strcpy(local_name,"OS_ERR_SEM_NOT_FULL"); break; case OS_ERR_INVALID_PRIORITY: strcpy(local_name,"OS_ERR_INVALID_PRIORITY"); break; default: strcpy(local_name,"ERROR_UNKNOWN"); return_code = OS_ERROR; } strcpy((char*) err_name, local_name); return return_code; } /*---------------------------------------------------------------------------- * Name: OS_PriorityRemap * * Purpose: Remaps the OSAL priority into one that is viable for this OS ----------------------------------------------------------------------------*/ int32 OS_PriorityRemap(uint32 InputPri) { int OutputPri; int pmax = sched_get_priority_max( SCHED_FIFO ); int pmin = sched_get_priority_min( SCHED_FIFO ); int prange = abs((pmax - pmin) +1); int numbins, offset; int IsMinNegative = 0; int MinNegOffset = 0; int IsMaxNegative = 0; int MaxNegOffset = 0; int InputRev; /* If an end point is negative, adjust the range upward so that there is no negative */ if (pmin < 0) { IsMinNegative = 1; MinNegOffset = -pmin; pmin += MinNegOffset; pmax += MinNegOffset; } if (pmax < 0) { IsMaxNegative = 1; MaxNegOffset = -pmax; pmin += MaxNegOffset; pmax += MaxNegOffset; } /* calculate the number of 'bins' to map the OSAL priorities into. * Since the Underlying OS will have AT MOST as many priority levels as * the OSAL (256 values), then we will be pigeon-holing a larger range * (OSAL priorities) into a small range (OS priorities), or the ranges are * equal, which is OK too. */ numbins = MAX_PRIORITY/prange; /* If we are more than half way to making a new bin, add another one */ if (MAX_PRIORITY % prange > prange/2) { numbins++; } /* Since the OSAL priorities have 0 as the highest and 255 as the lowest, * we need to reverse this so that the numerically higher number is a higher priority * to work with the OS's */ InputRev = MAX_PRIORITY - InputPri; /* calculate the offset from the min value */ offset = InputRev / numbins ; OutputPri = pmin + offset ; /* take care of extraneous cases at ends, if they occur. */ if (OutputPri > pmax) { OutputPri = pmax; } if ( OutputPri < pmin) { OutputPri = pmin; } /* if an end point was negative, shift it back */ if (IsMinNegative == 1) { OutputPri -= MinNegOffset; } if (IsMaxNegative == 1) { OutputPri -= MaxNegOffset; } return OutputPri; }/*end OS_PriortyRemap*/ /* --------------------------------------------------------------------------- * Name: OS_ThreadKillHandler * * Purpose: This function allows for a task to be deleted when OS_TaskDelete * is called ----------------------------------------------------------------------------*/ void OS_ThreadKillHandler(int sig) { pthread_exit(NULL); }/*end OS_ThreadKillHandler */ /* ** ** Name: OS_FPUExcSetMask ** ** Purpose: This function sets the FPU exception mask ** ** Notes: The exception environment is local to each task Therefore this must be ** called for each task that that wants to do floating point and catch exceptions. */ int32 OS_FPUExcSetMask(uint32 mask) { /* ** Not implemented in linux. */ return(OS_SUCCESS); } /* ** ** Name: OS_FPUExcGetMask ** ** Purpose: This function gets the FPU exception mask ** ** Notes: The exception environment is local to each task Therefore this must be ** called for each task that that wants to do floating point and catch exceptions. */ int32 OS_FPUExcGetMask(uint32 *mask) { /* ** Not implemented in linux. */ return(OS_SUCCESS); } /* ** ** Name: OS_InterruptSafeLock ** ** Purpose: This function masks signals and locks a mutex for mutual exclusion ** */ int OS_InterruptSafeLock(pthread_mutex_t *lock, sigset_t *set, sigset_t *previous) { /* Block all signals */ sigfillset(set); if (pthread_sigmask(SIG_SETMASK, set, previous) == 0) { /* Acquire the lock */ return pthread_mutex_lock(lock); } else { return EINVAL; } } /* ** ** Name: OS_InterruptSafeUnlock ** ** Purpose: This function unlocks the mutex and restores the signal mask ** */ void OS_InterruptSafeUnlock(pthread_mutex_t *lock, sigset_t *previous) { /* Release the lock */ pthread_mutex_unlock(lock); /* Restore previous signals */ pthread_sigmask(SIG_SETMASK, previous, NULL); }
30.710852
128
0.562254
[ "object" ]
6437618caba47cdb7a6c4e14dfb3f3a3be16f080
7,489
h
C
Modules/Core/Metadata/include/otbImageMetadataInterfaceBase.h
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
Modules/Core/Metadata/include/otbImageMetadataInterfaceBase.h
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
Modules/Core/Metadata/include/otbImageMetadataInterfaceBase.h
xcorail/OTB
092a93654c3b5d009e420f450fe9b675f737cdca
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbImageMetadataInterfaceBase_h #define otbImageMetadataInterfaceBase_h #include <string> #include "otbImageKeywordlist.h" #include "itkMetaDataDictionary.h" #include "otbMetaDataKey.h" #include "itkImageBase.h" #include "OTBMetadataExport.h" namespace otb { /** \class ImageMetadataInterfaceBase * * \brief Base class for captor metadata reading. * * * \ingroup OTBMetadata */ class OTBMetadata_EXPORT ImageMetadataInterfaceBase : public itk::Object { public: typedef ImageMetadataInterfaceBase Self; typedef itk::Object Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro(ImageMetadataInterfaceBase, itk::Object); typedef itk::ImageBase<2> ImageType; typedef itk::MetaDataDictionary MetaDataDictionaryType; typedef MetaDataKey::VectorType VectorType; typedef MetaDataKey::VariableLengthVectorType VariableLengthVectorType; typedef ImageKeywordlist ImageKeywordlistType; typedef unsigned int UnsignedIntType; typedef std::vector<std::string> StringVectorType; typedef std::vector<unsigned int> UIntVectorType; /** Set the image used to get the metadata */ void SetImage (ImageType* image) { this->SetMetaDataDictionary(image->GetMetaDataDictionary()); } /** Set the MetadataDictionary */ void SetMetaDataDictionary(const MetaDataDictionaryType& dict) { m_MetaDataDictionary = dict; } /** Get the MetadataDictionary */ const MetaDataDictionaryType& GetMetaDataDictionary() const { return m_MetaDataDictionary; } /** Get the projection coordinate system of the image. */ std::string GetProjectionRef() const; /** Get the GCP projection coordinates of the image. */ std::string GetGCPProjection() const; // otbMetadataGetMacro(GCPProjection, std::string); UnsignedIntType GetGCPCount() const; // otbMetadataGetMacro(GCPCount, unsigned int); OTB_GCP& GetGCPs(unsigned int GCPnum); //otbMetadataGetGCPnumMacro(GCPs, OTB_GCP&, GCPnum, unsigned int); std::string GetGCPId(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPId, std::string, GCPnum, unsigned int); std::string GetGCPInfo(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPInfo, std::string, GCPnum, unsigned int); double GetGCPRow(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPRow, double, GCPnum, unsigned int); double GetGCPCol(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPCol, double, GCPnum, unsigned int); double GetGCPX(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPX, double, GCPnum, unsigned int); double GetGCPY(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPY, double, GCPnum, unsigned int); double GetGCPZ(unsigned int GCPnum) const; // otbMetadataGetGCPnumMacro(GCPZ, double, GCPnum, unsigned int); /** * Get The no data flags if existing * return False otherwise */ bool GetNoDataFlags(std::vector<bool> & flags, std::vector<double> & values) const; /** Get the six coefficients of affine geoTtransform. */ VectorType GetGeoTransform() const; // otbMetadataGetMacro(GeoTransform, VectorType); /** Get image corners. */ VectorType GetUpperLeftCorner() const; // otbMetadataGetMacro(UpperLeftCorner, VectorType); VectorType GetUpperRightCorner() const; // otbMetadataGetMacro(UpperRightCorner, VectorType); VectorType GetLowerLeftCorner() const; // otbMetadataGetMacro(LowerLeftCorner, VectorType); VectorType GetLowerRightCorner() const; // otbMetadataGetMacro(LowerRightCorner, VectorType); /** Get the ImageKeywordlist */ ImageKeywordlistType GetImageKeywordlist(); const ImageKeywordlistType GetImageKeywordlist() const; /** This method is less performant and has extra copy. Please use bool GetSensorID(std::string& ) **/ std::string const GetSensorID() const; /** Get the sensor ID from the ossim metadata */ bool GetSensorID(std::string & sensorId) const; //otbMetadataGetMacro(SensorID, std::string); /** Get the number of bands from the ossim metadata */ UnsignedIntType GetNumberOfBands() const; //otbMetadataGetMacro(NumberOfBands, unsigned int); /** Get the band name from the ossim metadata */ StringVectorType GetBandName() const; //otbMetadataGetMacro(BandName, std::vector<std::string>); /** Get the x pixel spacing*/ double GetXPixelSpacing() const; //otbMetadataGetMacro(XPixelSpacing, double); /** Get the y pixel spacing*/ double GetYPixelSpacing() const; //otbMetadataGetMacro(YPixelSpacing, double); /** Get the imaging acquisition day from the ossim metadata */ virtual int GetDay() const = 0; // otbMetadataGetMacro(Day, int); /** Get the imaging acquisition month from the ossim metadata */ virtual int GetMonth() const = 0; //otbMetadataGetMacro(Month, int); /** Get the imaging acquisition year from the ossim metadata */ virtual int GetYear() const = 0; //otbMetadataGetMacro(Year, int); /** Get the imaging acquisition hour from the ossim metadata */ virtual int GetHour() const = 0; //otbMetadataGetMacro(Hour, int); /** Get the imaging acquisition minute from the ossim metadata */ virtual int GetMinute() const = 0; //otbMetadataGetMacro(Minute, int); /** Get the imaging production day from the ossim metadata */ virtual int GetProductionDay() const = 0; //otbMetadataGetMacro(ProductionDay, int); /** Get the imaging production month from the ossim metadata */ virtual int GetProductionMonth() const = 0; //otbMetadataGetMacro(ProductionMonth, int); /** Get the imaging production year from the ossim metadata */ virtual int GetProductionYear() const = 0; //otbMetadataGetMacro(ProductionYear, int); /** Convert the band names provided by ossim to the official band names */ virtual StringVectorType GetEnhancedBandNames () const = 0; /** Get the 3 spectral band numbers corresponding to the default display for visualization, * in the order R, G, B */ virtual UIntVectorType GetDefaultDisplay() const = 0; virtual bool CanRead() const = 0; static void PrintMetadata(std::ostream& os, itk::Indent indent, const MetaDataDictionaryType& dict); protected: ImageMetadataInterfaceBase(); ~ImageMetadataInterfaceBase() override {} void PrintSelf(std::ostream& os, itk::Indent indent) const override; MetaDataDictionaryType m_MetaDataDictionary; private: ImageMetadataInterfaceBase(const Self &) = delete; void operator =(const Self&) = delete; OTB_GCP m_GCP; }; } // end namespace otb #endif
32.141631
102
0.730405
[ "object", "vector" ]
643b413d9f0f395fca978a56641cbe582beee773
49,821
c
C
kernel/drivers/staging/pohmelfs/inode.c
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
10
2015-02-28T21:05:37.000Z
2021-09-16T04:57:27.000Z
kernel/drivers/staging/pohmelfs/inode.c
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
1
2021-02-24T05:16:58.000Z
2021-02-24T05:16:58.000Z
kernel/drivers/staging/pohmelfs/inode.c
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
5
2018-11-19T16:42:53.000Z
2021-12-07T12:39:23.000Z
/* * 2007+ Copyright (c) Evgeniy Polyakov <zbr@ioremap.net> * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/module.h> #include <linux/backing-dev.h> #include <linux/crypto.h> #include <linux/fs.h> #include <linux/jhash.h> #include <linux/hash.h> #include <linux/ktime.h> #include <linux/mm.h> #include <linux/mount.h> #include <linux/pagemap.h> #include <linux/pagevec.h> #include <linux/parser.h> #include <linux/swap.h> #include <linux/slab.h> #include <linux/statfs.h> #include <linux/writeback.h> #include "netfs.h" #define POHMELFS_MAGIC_NUM 0x504f482e static struct kmem_cache *pohmelfs_inode_cache; static atomic_t psb_bdi_num = ATOMIC_INIT(0); /* * Removes inode from all trees, drops local name cache and removes all queued * requests for object removal. */ void pohmelfs_inode_del_inode(struct pohmelfs_sb *psb, struct pohmelfs_inode *pi) { mutex_lock(&pi->offset_lock); pohmelfs_free_names(pi); mutex_unlock(&pi->offset_lock); dprintk("%s: deleted stuff in ino: %llu.\n", __func__, pi->ino); } /* * Sync inode to server. * Returns zero in success and negative error value otherwise. * It will gather path to root directory into structures containing * creation mode, permissions and names, so that the whole path * to given inode could be created using only single network command. */ int pohmelfs_write_inode_create(struct inode *inode, struct netfs_trans *trans) { struct pohmelfs_inode *pi = POHMELFS_I(inode); int err = -ENOMEM, size; struct netfs_cmd *cmd; void *data; int cur_len = netfs_trans_cur_len(trans); if (unlikely(cur_len < 0)) return -ETOOSMALL; cmd = netfs_trans_current(trans); cur_len -= sizeof(struct netfs_cmd); data = (void *)(cmd + 1); err = pohmelfs_construct_path_string(pi, data, cur_len); if (err < 0) goto err_out_exit; size = err; cmd->start = i_size_read(inode); cmd->cmd = NETFS_CREATE; cmd->size = size; cmd->id = pi->ino; cmd->ext = inode->i_mode; netfs_convert_cmd(cmd); netfs_trans_update(cmd, trans, size); return 0; err_out_exit: printk("%s: completed ino: %llu, err: %d.\n", __func__, pi->ino, err); return err; } static int pohmelfs_write_trans_complete(struct page **pages, unsigned int page_num, void *private, int err) { unsigned i; dprintk("%s: pages: %lu-%lu, page_num: %u, err: %d.\n", __func__, pages[0]->index, pages[page_num-1]->index, page_num, err); for (i = 0; i < page_num; i++) { struct page *page = pages[i]; if (!page) continue; end_page_writeback(page); if (err < 0) { SetPageError(page); set_page_dirty(page); } unlock_page(page); page_cache_release(page); /* dprintk("%s: %3u/%u: page: %p.\n", __func__, i, page_num, page); */ } return err; } static int pohmelfs_inode_has_dirty_pages(struct address_space *mapping, pgoff_t index) { int ret; struct page *page; rcu_read_lock(); ret = radix_tree_gang_lookup_tag(&mapping->page_tree, (void **)&page, index, 1, PAGECACHE_TAG_DIRTY); rcu_read_unlock(); return ret; } static int pohmelfs_writepages(struct address_space *mapping, struct writeback_control *wbc) { struct inode *inode = mapping->host; struct pohmelfs_inode *pi = POHMELFS_I(inode); struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); int err = 0; int done = 0; int nr_pages; pgoff_t index; pgoff_t end; /* Inclusive */ int scanned = 0; int range_whole = 0; if (wbc->range_cyclic) { index = mapping->writeback_index; /* Start from prev offset */ end = -1; } else { index = wbc->range_start >> PAGE_CACHE_SHIFT; end = wbc->range_end >> PAGE_CACHE_SHIFT; if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) range_whole = 1; scanned = 1; } retry: while (!done && (index <= end)) { unsigned int i = min(end - index, (pgoff_t)psb->trans_max_pages); int path_len; struct netfs_trans *trans; err = pohmelfs_inode_has_dirty_pages(mapping, index); if (!err) break; err = pohmelfs_path_length(pi); if (err < 0) break; path_len = err; if (path_len <= 2) { err = -ENOENT; break; } trans = netfs_trans_alloc(psb, path_len, 0, i); if (!trans) { err = -ENOMEM; break; } trans->complete = &pohmelfs_write_trans_complete; trans->page_num = nr_pages = find_get_pages_tag(mapping, &index, PAGECACHE_TAG_DIRTY, trans->page_num, trans->pages); dprintk("%s: t: %p, nr_pages: %u, end: %lu, index: %lu, max: %u.\n", __func__, trans, nr_pages, end, index, trans->page_num); if (!nr_pages) goto err_out_reset; err = pohmelfs_write_inode_create(inode, trans); if (err) goto err_out_reset; err = 0; scanned = 1; for (i = 0; i < trans->page_num; i++) { struct page *page = trans->pages[i]; lock_page(page); if (unlikely(page->mapping != mapping)) goto out_continue; if (!wbc->range_cyclic && page->index > end) { done = 1; goto out_continue; } if (wbc->sync_mode != WB_SYNC_NONE) wait_on_page_writeback(page); if (PageWriteback(page) || !clear_page_dirty_for_io(page)) { dprintk("%s: not clear for io page: %p, writeback: %d.\n", __func__, page, PageWriteback(page)); goto out_continue; } set_page_writeback(page); trans->attached_size += page_private(page); trans->attached_pages++; #if 0 dprintk("%s: %u/%u added trans: %p, gen: %u, page: %p, [High: %d], size: %lu, idx: %lu.\n", __func__, i, trans->page_num, trans, trans->gen, page, !!PageHighMem(page), page_private(page), page->index); #endif wbc->nr_to_write--; if (wbc->nr_to_write <= 0) done = 1; continue; out_continue: unlock_page(page); trans->pages[i] = NULL; } err = netfs_trans_finish(trans, psb); if (err) break; continue; err_out_reset: trans->result = err; netfs_trans_reset(trans); netfs_trans_put(trans); break; } if (!scanned && !done) { /* * We hit the last page and there is more work to be done: wrap * back to the start of the file */ scanned = 1; index = 0; goto retry; } if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) mapping->writeback_index = index; return err; } /* * Inode writeback creation completion callback. * Only invoked for just created inodes, which do not have pages attached, * like dirs and empty files. */ static int pohmelfs_write_inode_complete(struct page **pages, unsigned int page_num, void *private, int err) { struct inode *inode = private; struct pohmelfs_inode *pi = POHMELFS_I(inode); if (inode) { if (err) { mark_inode_dirty(inode); clear_bit(NETFS_INODE_REMOTE_SYNCED, &pi->state); } else { set_bit(NETFS_INODE_REMOTE_SYNCED, &pi->state); } pohmelfs_put_inode(pi); } return err; } int pohmelfs_write_create_inode(struct pohmelfs_inode *pi) { struct netfs_trans *t; struct inode *inode = &pi->vfs_inode; struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); int err; if (test_bit(NETFS_INODE_REMOTE_SYNCED, &pi->state)) return 0; dprintk("%s: started ino: %llu.\n", __func__, pi->ino); err = pohmelfs_path_length(pi); if (err < 0) goto err_out_exit; t = netfs_trans_alloc(psb, err + 1, 0, 0); if (!t) { err = -ENOMEM; goto err_out_exit; } t->complete = pohmelfs_write_inode_complete; t->private = igrab(inode); if (!t->private) { err = -ENOENT; goto err_out_put; } err = pohmelfs_write_inode_create(inode, t); if (err) goto err_out_put; netfs_trans_finish(t, POHMELFS_SB(inode->i_sb)); return 0; err_out_put: t->result = err; netfs_trans_put(t); err_out_exit: return err; } /* * Sync all not-yet-created children in given directory to the server. */ static int pohmelfs_write_inode_create_children(struct inode *inode) { struct pohmelfs_inode *parent = POHMELFS_I(inode); struct super_block *sb = inode->i_sb; struct pohmelfs_name *n; while (!list_empty(&parent->sync_create_list)) { n = NULL; mutex_lock(&parent->offset_lock); if (!list_empty(&parent->sync_create_list)) { n = list_first_entry(&parent->sync_create_list, struct pohmelfs_name, sync_create_entry); list_del_init(&n->sync_create_entry); } mutex_unlock(&parent->offset_lock); if (!n) break; inode = ilookup(sb, n->ino); dprintk("%s: parent: %llu, ino: %llu, inode: %p.\n", __func__, parent->ino, n->ino, inode); if (inode && (inode->i_state & I_DIRTY)) { struct pohmelfs_inode *pi = POHMELFS_I(inode); pohmelfs_write_create_inode(pi); /* pohmelfs_meta_command(pi, NETFS_INODE_INFO, 0, NULL, NULL, 0); */ iput(inode); } } return 0; } /* * Removes given child from given inode on server. */ int pohmelfs_remove_child(struct pohmelfs_inode *pi, struct pohmelfs_name *n) { return pohmelfs_meta_command_data(pi, pi->ino, NETFS_REMOVE, NULL, 0, NULL, NULL, 0); } /* * Writeback for given inode. */ static int pohmelfs_write_inode(struct inode *inode, struct writeback_control *wbc) { struct pohmelfs_inode *pi = POHMELFS_I(inode); pohmelfs_write_create_inode(pi); pohmelfs_write_inode_create_children(inode); return 0; } /* * It is not exported, sorry... */ static inline wait_queue_head_t *page_waitqueue(struct page *page) { const struct zone *zone = page_zone(page); return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)]; } static int pohmelfs_wait_on_page_locked(struct page *page) { struct pohmelfs_sb *psb = POHMELFS_SB(page->mapping->host->i_sb); long ret = psb->wait_on_page_timeout; DEFINE_WAIT_BIT(wait, &page->flags, PG_locked); int err = 0; if (!PageLocked(page)) return 0; for (;;) { prepare_to_wait(page_waitqueue(page), &wait.wait, TASK_INTERRUPTIBLE); dprintk("%s: page: %p, locked: %d, uptodate: %d, error: %d, flags: %lx.\n", __func__, page, PageLocked(page), PageUptodate(page), PageError(page), page->flags); if (!PageLocked(page)) break; if (!signal_pending(current)) { ret = schedule_timeout(ret); if (!ret) break; continue; } ret = -ERESTARTSYS; break; } finish_wait(page_waitqueue(page), &wait.wait); if (!ret) err = -ETIMEDOUT; if (!err) SetPageUptodate(page); if (err) printk("%s: page: %p, uptodate: %d, locked: %d, err: %d.\n", __func__, page, PageUptodate(page), PageLocked(page), err); return err; } static int pohmelfs_read_page_complete(struct page **pages, unsigned int page_num, void *private, int err) { struct page *page = private; if (PageChecked(page)) return err; if (err < 0) { dprintk("%s: page: %p, err: %d.\n", __func__, page, err); SetPageError(page); } unlock_page(page); return err; } /* * Read a page from remote server. * Function will wait until page is unlocked. */ static int pohmelfs_readpage(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); struct pohmelfs_inode *pi = POHMELFS_I(inode); struct netfs_trans *t; struct netfs_cmd *cmd; int err, path_len; void *data; u64 isize; err = pohmelfs_data_lock(pi, page->index << PAGE_CACHE_SHIFT, PAGE_SIZE, POHMELFS_READ_LOCK); if (err) goto err_out_exit; isize = i_size_read(inode); if (isize <= page->index << PAGE_CACHE_SHIFT) { SetPageUptodate(page); unlock_page(page); return 0; } path_len = pohmelfs_path_length(pi); if (path_len < 0) { err = path_len; goto err_out_exit; } t = netfs_trans_alloc(psb, path_len, NETFS_TRANS_SINGLE_DST, 0); if (!t) { err = -ENOMEM; goto err_out_exit; } t->complete = pohmelfs_read_page_complete; t->private = page; cmd = netfs_trans_current(t); data = (void *)(cmd + 1); err = pohmelfs_construct_path_string(pi, data, path_len); if (err < 0) goto err_out_free; path_len = err; cmd->id = pi->ino; cmd->start = page->index; cmd->start <<= PAGE_CACHE_SHIFT; cmd->size = PAGE_CACHE_SIZE + path_len; cmd->cmd = NETFS_READ_PAGE; cmd->ext = path_len; dprintk("%s: path: '%s', page: %p, ino: %llu, start: %llu, size: %lu.\n", __func__, (char *)data, page, pi->ino, cmd->start, PAGE_CACHE_SIZE); netfs_convert_cmd(cmd); netfs_trans_update(cmd, t, path_len); err = netfs_trans_finish(t, psb); if (err) goto err_out_return; return pohmelfs_wait_on_page_locked(page); err_out_free: t->result = err; netfs_trans_put(t); err_out_exit: SetPageError(page); if (PageLocked(page)) unlock_page(page); err_out_return: printk("%s: page: %p, start: %lu, size: %lu, err: %d.\n", __func__, page, page->index << PAGE_CACHE_SHIFT, PAGE_CACHE_SIZE, err); return err; } /* * Write begin/end magic. * Allocates a page and writes inode if it was not synced to server before. */ static int pohmelfs_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { struct inode *inode = mapping->host; struct page *page; pgoff_t index; unsigned start, end; int err; *pagep = NULL; index = pos >> PAGE_CACHE_SHIFT; start = pos & (PAGE_CACHE_SIZE - 1); end = start + len; page = grab_cache_page(mapping, index); #if 0 dprintk("%s: page: %p pos: %llu, len: %u, index: %lu, start: %u, end: %u, uptodate: %d.\n", __func__, page, pos, len, index, start, end, PageUptodate(page)); #endif if (!page) { err = -ENOMEM; goto err_out_exit; } while (!PageUptodate(page)) { if (start && test_bit(NETFS_INODE_REMOTE_SYNCED, &POHMELFS_I(inode)->state)) { err = pohmelfs_readpage(file, page); if (err) goto err_out_exit; lock_page(page); continue; } if (len != PAGE_CACHE_SIZE) { void *kaddr = kmap_atomic(page, KM_USER0); memset(kaddr + start, 0, PAGE_CACHE_SIZE - start); flush_dcache_page(page); kunmap_atomic(kaddr, KM_USER0); } SetPageUptodate(page); } set_page_private(page, end); *pagep = page; return 0; err_out_exit: page_cache_release(page); *pagep = NULL; return err; } static int pohmelfs_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { struct inode *inode = mapping->host; if (copied != len) { unsigned from = pos & (PAGE_CACHE_SIZE - 1); void *kaddr = kmap_atomic(page, KM_USER0); memset(kaddr + from + copied, 0, len - copied); flush_dcache_page(page); kunmap_atomic(kaddr, KM_USER0); } SetPageUptodate(page); set_page_dirty(page); #if 0 dprintk("%s: page: %p [U: %d, D: %d, L: %d], pos: %llu, len: %u, copied: %u.\n", __func__, page, PageUptodate(page), PageDirty(page), PageLocked(page), pos, len, copied); #endif flush_dcache_page(page); unlock_page(page); page_cache_release(page); if (pos + copied > inode->i_size) { struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); psb->avail_size -= pos + copied - inode->i_size; i_size_write(inode, pos + copied); } return copied; } static int pohmelfs_readpages_trans_complete(struct page **__pages, unsigned int page_num, void *private, int err) { struct pohmelfs_inode *pi = private; unsigned int i, num; struct page **pages, *page = (struct page *)__pages; loff_t index = page->index; pages = kzalloc(sizeof(void *) * page_num, GFP_NOIO); if (!pages) return -ENOMEM; num = find_get_pages_contig(pi->vfs_inode.i_mapping, index, page_num, pages); if (num <= 0) { err = num; goto err_out_free; } for (i = 0; i < num; ++i) { page = pages[i]; if (err) printk("%s: %u/%u: page: %p, index: %lu, uptodate: %d, locked: %d, err: %d.\n", __func__, i, num, page, page->index, PageUptodate(page), PageLocked(page), err); if (!PageChecked(page)) { if (err < 0) SetPageError(page); unlock_page(page); } page_cache_release(page); page_cache_release(page); } err_out_free: kfree(pages); return err; } static int pohmelfs_send_readpages(struct pohmelfs_inode *pi, struct page *first, unsigned int num) { struct netfs_trans *t; struct netfs_cmd *cmd; struct pohmelfs_sb *psb = POHMELFS_SB(pi->vfs_inode.i_sb); int err, path_len; void *data; err = pohmelfs_data_lock(pi, first->index << PAGE_CACHE_SHIFT, num * PAGE_SIZE, POHMELFS_READ_LOCK); if (err) goto err_out_exit; path_len = pohmelfs_path_length(pi); if (path_len < 0) { err = path_len; goto err_out_exit; } t = netfs_trans_alloc(psb, path_len, NETFS_TRANS_SINGLE_DST, 0); if (!t) { err = -ENOMEM; goto err_out_exit; } cmd = netfs_trans_current(t); data = (void *)(cmd + 1); t->complete = pohmelfs_readpages_trans_complete; t->private = pi; t->page_num = num; t->pages = (struct page **)first; err = pohmelfs_construct_path_string(pi, data, path_len); if (err < 0) goto err_out_put; path_len = err; cmd->cmd = NETFS_READ_PAGES; cmd->start = first->index; cmd->start <<= PAGE_CACHE_SHIFT; cmd->size = (num << 8 | PAGE_CACHE_SHIFT); cmd->id = pi->ino; cmd->ext = path_len; dprintk("%s: t: %p, gen: %u, path: '%s', path_len: %u, " "start: %lu, num: %u.\n", __func__, t, t->gen, (char *)data, path_len, first->index, num); netfs_convert_cmd(cmd); netfs_trans_update(cmd, t, path_len); return netfs_trans_finish(t, psb); err_out_put: netfs_trans_free(t); err_out_exit: pohmelfs_readpages_trans_complete((struct page **)first, num, pi, err); return err; } #define list_to_page(head) (list_entry((head)->prev, struct page, lru)) static int pohmelfs_readpages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { unsigned int page_idx, num = 0; struct page *page = NULL, *first = NULL; for (page_idx = 0; page_idx < nr_pages; page_idx++) { page = list_to_page(pages); prefetchw(&page->flags); list_del(&page->lru); if (!add_to_page_cache_lru(page, mapping, page->index, GFP_KERNEL)) { if (!num) { num = 1; first = page; continue; } dprintk("%s: added to lru page: %p, page_index: %lu, first_index: %lu.\n", __func__, page, page->index, first->index); if (unlikely(first->index + num != page->index) || (num > 500)) { pohmelfs_send_readpages(POHMELFS_I(mapping->host), first, num); first = page; num = 0; } num++; } } pohmelfs_send_readpages(POHMELFS_I(mapping->host), first, num); /* * This will be sync read, so when last page is processed, * all previous are alerady unlocked and ready to be used. */ return 0; } /* * Small addres space operations for POHMELFS. */ const struct address_space_operations pohmelfs_aops = { .readpage = pohmelfs_readpage, .readpages = pohmelfs_readpages, .writepages = pohmelfs_writepages, .write_begin = pohmelfs_write_begin, .write_end = pohmelfs_write_end, .set_page_dirty = __set_page_dirty_nobuffers, }; /* * ->detroy_inode() callback. Deletes inode from the caches * and frees private data. */ static void pohmelfs_destroy_inode(struct inode *inode) { struct super_block *sb = inode->i_sb; struct pohmelfs_sb *psb = POHMELFS_SB(sb); struct pohmelfs_inode *pi = POHMELFS_I(inode); /* pohmelfs_data_unlock(pi, 0, inode->i_size, POHMELFS_READ_LOCK); */ pohmelfs_inode_del_inode(psb, pi); dprintk("%s: pi: %p, inode: %p, ino: %llu.\n", __func__, pi, &pi->vfs_inode, pi->ino); kmem_cache_free(pohmelfs_inode_cache, pi); atomic_long_dec(&psb->total_inodes); } /* * ->alloc_inode() callback. Allocates inode and initilizes private data. */ static struct inode *pohmelfs_alloc_inode(struct super_block *sb) { struct pohmelfs_inode *pi; pi = kmem_cache_alloc(pohmelfs_inode_cache, GFP_NOIO); if (!pi) return NULL; pi->hash_root = RB_ROOT; mutex_init(&pi->offset_lock); INIT_LIST_HEAD(&pi->sync_create_list); INIT_LIST_HEAD(&pi->inode_entry); pi->lock_type = 0; pi->state = 0; pi->total_len = 0; pi->drop_count = 0; dprintk("%s: pi: %p, inode: %p.\n", __func__, pi, &pi->vfs_inode); atomic_long_inc(&POHMELFS_SB(sb)->total_inodes); return &pi->vfs_inode; } /* * We want fsync() to work on POHMELFS. */ static int pohmelfs_fsync(struct file *file, int datasync) { struct inode *inode = file->f_mapping->host; struct writeback_control wbc = { .sync_mode = WB_SYNC_ALL, .nr_to_write = 0, /* sys_fsync did this */ }; return sync_inode(inode, &wbc); } ssize_t pohmelfs_write(struct file *file, const char __user *buf, size_t len, loff_t *ppos) { struct address_space *mapping = file->f_mapping; struct inode *inode = mapping->host; struct pohmelfs_inode *pi = POHMELFS_I(inode); struct iovec iov = { .iov_base = (void __user *)buf, .iov_len = len }; struct kiocb kiocb; ssize_t ret; loff_t pos = *ppos; init_sync_kiocb(&kiocb, file); kiocb.ki_pos = pos; kiocb.ki_left = len; dprintk("%s: len: %zu, pos: %llu.\n", __func__, len, pos); mutex_lock(&inode->i_mutex); ret = pohmelfs_data_lock(pi, pos, len, POHMELFS_WRITE_LOCK); if (ret) goto err_out_unlock; ret = __generic_file_aio_write(&kiocb, &iov, 1, &kiocb.ki_pos); *ppos = kiocb.ki_pos; mutex_unlock(&inode->i_mutex); WARN_ON(ret < 0); if (ret > 0) { ssize_t err; err = generic_write_sync(file, pos, ret); if (err < 0) ret = err; WARN_ON(ret < 0); } return ret; err_out_unlock: mutex_unlock(&inode->i_mutex); return ret; } static const struct file_operations pohmelfs_file_ops = { .open = generic_file_open, .fsync = pohmelfs_fsync, .llseek = generic_file_llseek, .read = do_sync_read, .aio_read = generic_file_aio_read, .mmap = generic_file_mmap, .splice_read = generic_file_splice_read, .splice_write = generic_file_splice_write, .write = pohmelfs_write, .aio_write = generic_file_aio_write, }; const struct inode_operations pohmelfs_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, }; int pohmelfs_setattr_raw(struct inode *inode, struct iattr *attr) { int err; err = inode_change_ok(inode, attr); if (err) { dprintk("%s: ino: %llu, inode changes are not allowed.\n", __func__, POHMELFS_I(inode)->ino); goto err_out_exit; } err = inode_setattr(inode, attr); if (err) { dprintk("%s: ino: %llu, failed to set the attributes.\n", __func__, POHMELFS_I(inode)->ino); goto err_out_exit; } dprintk("%s: ino: %llu, mode: %o -> %o, uid: %u -> %u, gid: %u -> %u, size: %llu -> %llu.\n", __func__, POHMELFS_I(inode)->ino, inode->i_mode, attr->ia_mode, inode->i_uid, attr->ia_uid, inode->i_gid, attr->ia_gid, inode->i_size, attr->ia_size); return 0; err_out_exit: return err; } int pohmelfs_setattr(struct dentry *dentry, struct iattr *attr) { struct inode *inode = dentry->d_inode; struct pohmelfs_inode *pi = POHMELFS_I(inode); int err; err = pohmelfs_data_lock(pi, 0, ~0, POHMELFS_WRITE_LOCK); if (err) goto err_out_exit; err = security_inode_setattr(dentry, attr); if (err) goto err_out_exit; err = pohmelfs_setattr_raw(inode, attr); if (err) goto err_out_exit; return 0; err_out_exit: return err; } static int pohmelfs_send_xattr_req(struct pohmelfs_inode *pi, u64 id, u64 start, const char *name, const void *value, size_t attrsize, int command) { struct pohmelfs_sb *psb = POHMELFS_SB(pi->vfs_inode.i_sb); int err, path_len, namelen = strlen(name) + 1; /* 0-byte */ struct netfs_trans *t; struct netfs_cmd *cmd; void *data; dprintk("%s: id: %llu, start: %llu, name: '%s', attrsize: %zu, cmd: %d.\n", __func__, id, start, name, attrsize, command); path_len = pohmelfs_path_length(pi); if (path_len < 0) { err = path_len; goto err_out_exit; } t = netfs_trans_alloc(psb, namelen + path_len + attrsize, 0, 0); if (!t) { err = -ENOMEM; goto err_out_exit; } cmd = netfs_trans_current(t); data = cmd + 1; path_len = pohmelfs_construct_path_string(pi, data, path_len); if (path_len < 0) { err = path_len; goto err_out_put; } data += path_len; /* * 'name' is a NUL-terminated string already and * 'namelen' includes 0-byte. */ memcpy(data, name, namelen); data += namelen; memcpy(data, value, attrsize); cmd->cmd = command; cmd->id = id; cmd->start = start; cmd->size = attrsize + namelen + path_len; cmd->ext = path_len; cmd->csize = 0; cmd->cpad = 0; netfs_convert_cmd(cmd); netfs_trans_update(cmd, t, namelen + path_len + attrsize); return netfs_trans_finish(t, psb); err_out_put: t->result = err; netfs_trans_put(t); err_out_exit: return err; } static int pohmelfs_setxattr(struct dentry *dentry, const char *name, const void *value, size_t attrsize, int flags) { struct inode *inode = dentry->d_inode; struct pohmelfs_inode *pi = POHMELFS_I(inode); struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); if (!(psb->state_flags & POHMELFS_FLAGS_XATTR)) return -EOPNOTSUPP; return pohmelfs_send_xattr_req(pi, flags, attrsize, name, value, attrsize, NETFS_XATTR_SET); } static ssize_t pohmelfs_getxattr(struct dentry *dentry, const char *name, void *value, size_t attrsize) { struct inode *inode = dentry->d_inode; struct pohmelfs_inode *pi = POHMELFS_I(inode); struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); struct pohmelfs_mcache *m; int err; long timeout = psb->mcache_timeout; if (!(psb->state_flags & POHMELFS_FLAGS_XATTR)) return -EOPNOTSUPP; m = pohmelfs_mcache_alloc(psb, 0, attrsize, value); if (IS_ERR(m)) return PTR_ERR(m); dprintk("%s: ino: %llu, name: '%s', size: %zu.\n", __func__, pi->ino, name, attrsize); err = pohmelfs_send_xattr_req(pi, m->gen, attrsize, name, value, 0, NETFS_XATTR_GET); if (err) goto err_out_put; do { err = wait_for_completion_timeout(&m->complete, timeout); if (err) { err = m->err; break; } /* * This loop is a bit ugly, since it waits until reference counter * hits 1 and then put object here. Main goal is to prevent race with * network thread, when it can start processing given request, i.e. * increase its reference counter but yet not complete it, while * we will exit from ->getxattr() with timeout, and although request * will not be freed (its reference counter was increased by network * thread), data pointer provided by user may be released, so we will * overwrite already freed area in network thread. * * Now after timeout we remove request from the cache, so it can not be * found by network thread, and wait for its reference counter to hit 1, * i.e. if network thread already started to process this request, we wait * it to finish, and then free object locally. If reference counter is * already 1, i.e. request is not used by anyone else, we can free it without * problem. */ err = -ETIMEDOUT; timeout = HZ; pohmelfs_mcache_remove_locked(psb, m); } while (atomic_read(&m->refcnt) != 1); pohmelfs_mcache_put(psb, m); dprintk("%s: ino: %llu, err: %d.\n", __func__, pi->ino, err); return err; err_out_put: pohmelfs_mcache_put(psb, m); return err; } static int pohmelfs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode = dentry->d_inode; #if 0 struct pohmelfs_inode *pi = POHMELFS_I(inode); int err; err = pohmelfs_data_lock(pi, 0, ~0, POHMELFS_READ_LOCK); if (err) return err; dprintk("%s: ino: %llu, mode: %o, uid: %u, gid: %u, size: %llu.\n", __func__, pi->ino, inode->i_mode, inode->i_uid, inode->i_gid, inode->i_size); #endif generic_fillattr(inode, stat); return 0; } const struct inode_operations pohmelfs_file_inode_operations = { .setattr = pohmelfs_setattr, .getattr = pohmelfs_getattr, .setxattr = pohmelfs_setxattr, .getxattr = pohmelfs_getxattr, }; /* * Fill inode data: mode, size, operation callbacks and so on... */ void pohmelfs_fill_inode(struct inode *inode, struct netfs_inode_info *info) { inode->i_mode = info->mode; inode->i_nlink = info->nlink; inode->i_uid = info->uid; inode->i_gid = info->gid; inode->i_blocks = info->blocks; inode->i_rdev = info->rdev; inode->i_size = info->size; inode->i_version = info->version; inode->i_blkbits = ffs(info->blocksize); dprintk("%s: inode: %p, num: %lu/%llu inode is regular: %d, dir: %d, link: %d, mode: %o, size: %llu.\n", __func__, inode, inode->i_ino, info->ino, S_ISREG(inode->i_mode), S_ISDIR(inode->i_mode), S_ISLNK(inode->i_mode), inode->i_mode, inode->i_size); inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC; /* * i_mapping is a pointer to i_data during inode initialization. */ inode->i_data.a_ops = &pohmelfs_aops; if (S_ISREG(inode->i_mode)) { inode->i_fop = &pohmelfs_file_ops; inode->i_op = &pohmelfs_file_inode_operations; } else if (S_ISDIR(inode->i_mode)) { inode->i_fop = &pohmelfs_dir_fops; inode->i_op = &pohmelfs_dir_inode_ops; } else if (S_ISLNK(inode->i_mode)) { inode->i_op = &pohmelfs_symlink_inode_operations; inode->i_fop = &pohmelfs_file_ops; } else { inode->i_fop = &generic_ro_fops; } } static void pohmelfs_drop_inode(struct inode *inode) { struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); struct pohmelfs_inode *pi = POHMELFS_I(inode); spin_lock(&psb->ino_lock); list_del_init(&pi->inode_entry); spin_unlock(&psb->ino_lock); generic_drop_inode(inode); } static struct pohmelfs_inode *pohmelfs_get_inode_from_list(struct pohmelfs_sb *psb, struct list_head *head, unsigned int *count) { struct pohmelfs_inode *pi = NULL; spin_lock(&psb->ino_lock); if (!list_empty(head)) { pi = list_entry(head->next, struct pohmelfs_inode, inode_entry); list_del_init(&pi->inode_entry); *count = pi->drop_count; pi->drop_count = 0; } spin_unlock(&psb->ino_lock); return pi; } static void pohmelfs_flush_transactions(struct pohmelfs_sb *psb) { struct pohmelfs_config *c; mutex_lock(&psb->state_lock); list_for_each_entry(c, &psb->state_list, config_entry) { pohmelfs_state_flush_transactions(&c->state); } mutex_unlock(&psb->state_lock); } /* * ->put_super() callback. Invoked before superblock is destroyed, * so it has to clean all private data. */ static void pohmelfs_put_super(struct super_block *sb) { struct pohmelfs_sb *psb = POHMELFS_SB(sb); struct pohmelfs_inode *pi; unsigned int count; unsigned int in_drop_list = 0; struct inode *inode, *tmp; dprintk("%s.\n", __func__); /* * Kill pending transactions, which could affect inodes in-flight. */ pohmelfs_flush_transactions(psb); while ((pi = pohmelfs_get_inode_from_list(psb, &psb->drop_list, &count))) { inode = &pi->vfs_inode; dprintk("%s: ino: %llu, pi: %p, inode: %p, count: %u.\n", __func__, pi->ino, pi, inode, count); if (atomic_read(&inode->i_count) != count) { printk("%s: ino: %llu, pi: %p, inode: %p, count: %u, i_count: %d.\n", __func__, pi->ino, pi, inode, count, atomic_read(&inode->i_count)); count = atomic_read(&inode->i_count); in_drop_list++; } while (count--) iput(&pi->vfs_inode); } list_for_each_entry_safe(inode, tmp, &sb->s_inodes, i_sb_list) { pi = POHMELFS_I(inode); dprintk("%s: ino: %llu, pi: %p, inode: %p, i_count: %u.\n", __func__, pi->ino, pi, inode, atomic_read(&inode->i_count)); /* * These are special inodes, they were created during * directory reading or lookup, and were not bound to dentry, * so they live here with reference counter being 1 and prevent * umount from succeed since it believes that they are busy. */ count = atomic_read(&inode->i_count); if (count) { list_del_init(&inode->i_sb_list); while (count--) iput(&pi->vfs_inode); } } psb->trans_scan_timeout = psb->drop_scan_timeout = 0; cancel_rearming_delayed_work(&psb->dwork); cancel_rearming_delayed_work(&psb->drop_dwork); flush_scheduled_work(); dprintk("%s: stopped workqueues.\n", __func__); pohmelfs_crypto_exit(psb); pohmelfs_state_exit(psb); bdi_destroy(&psb->bdi); kfree(psb); sb->s_fs_info = NULL; } static int pohmelfs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct super_block *sb = dentry->d_sb; struct pohmelfs_sb *psb = POHMELFS_SB(sb); /* * There are no filesystem size limits yet. */ memset(buf, 0, sizeof(struct kstatfs)); buf->f_type = POHMELFS_MAGIC_NUM; /* 'POH.' */ buf->f_bsize = sb->s_blocksize; buf->f_files = psb->ino; buf->f_namelen = 255; buf->f_files = atomic_long_read(&psb->total_inodes); buf->f_bfree = buf->f_bavail = psb->avail_size >> PAGE_SHIFT; buf->f_blocks = psb->total_size >> PAGE_SHIFT; dprintk("%s: total: %llu, avail: %llu, inodes: %llu, bsize: %lu.\n", __func__, psb->total_size, psb->avail_size, buf->f_files, sb->s_blocksize); return 0; } static int pohmelfs_show_options(struct seq_file *seq, struct vfsmount *vfs) { struct pohmelfs_sb *psb = POHMELFS_SB(vfs->mnt_sb); seq_printf(seq, ",idx=%u", psb->idx); seq_printf(seq, ",trans_scan_timeout=%u", jiffies_to_msecs(psb->trans_scan_timeout)); seq_printf(seq, ",drop_scan_timeout=%u", jiffies_to_msecs(psb->drop_scan_timeout)); seq_printf(seq, ",wait_on_page_timeout=%u", jiffies_to_msecs(psb->wait_on_page_timeout)); seq_printf(seq, ",trans_retries=%u", psb->trans_retries); seq_printf(seq, ",crypto_thread_num=%u", psb->crypto_thread_num); seq_printf(seq, ",trans_max_pages=%u", psb->trans_max_pages); seq_printf(seq, ",mcache_timeout=%u", jiffies_to_msecs(psb->mcache_timeout)); if (psb->crypto_fail_unsupported) seq_printf(seq, ",crypto_fail_unsupported"); return 0; } enum { pohmelfs_opt_idx, pohmelfs_opt_crypto_thread_num, pohmelfs_opt_trans_max_pages, pohmelfs_opt_crypto_fail_unsupported, /* Remountable options */ pohmelfs_opt_trans_scan_timeout, pohmelfs_opt_drop_scan_timeout, pohmelfs_opt_wait_on_page_timeout, pohmelfs_opt_trans_retries, pohmelfs_opt_mcache_timeout, }; static struct match_token pohmelfs_tokens[] = { {pohmelfs_opt_idx, "idx=%u"}, {pohmelfs_opt_crypto_thread_num, "crypto_thread_num=%u"}, {pohmelfs_opt_trans_max_pages, "trans_max_pages=%u"}, {pohmelfs_opt_crypto_fail_unsupported, "crypto_fail_unsupported"}, {pohmelfs_opt_trans_scan_timeout, "trans_scan_timeout=%u"}, {pohmelfs_opt_drop_scan_timeout, "drop_scan_timeout=%u"}, {pohmelfs_opt_wait_on_page_timeout, "wait_on_page_timeout=%u"}, {pohmelfs_opt_trans_retries, "trans_retries=%u"}, {pohmelfs_opt_mcache_timeout, "mcache_timeout=%u"}, }; static int pohmelfs_parse_options(char *options, struct pohmelfs_sb *psb, int remount) { char *p; substring_t args[MAX_OPT_ARGS]; int option, err; if (!options) return 0; while ((p = strsep(&options, ",")) != NULL) { int token; if (!*p) continue; token = match_token(p, pohmelfs_tokens, args); err = match_int(&args[0], &option); if (err) return err; if (remount && token <= pohmelfs_opt_crypto_fail_unsupported) continue; switch (token) { case pohmelfs_opt_idx: psb->idx = option; break; case pohmelfs_opt_trans_scan_timeout: psb->trans_scan_timeout = msecs_to_jiffies(option); break; case pohmelfs_opt_drop_scan_timeout: psb->drop_scan_timeout = msecs_to_jiffies(option); break; case pohmelfs_opt_wait_on_page_timeout: psb->wait_on_page_timeout = msecs_to_jiffies(option); break; case pohmelfs_opt_mcache_timeout: psb->mcache_timeout = msecs_to_jiffies(option); break; case pohmelfs_opt_trans_retries: psb->trans_retries = option; break; case pohmelfs_opt_crypto_thread_num: psb->crypto_thread_num = option; break; case pohmelfs_opt_trans_max_pages: psb->trans_max_pages = option; break; case pohmelfs_opt_crypto_fail_unsupported: psb->crypto_fail_unsupported = 1; break; default: return -EINVAL; } } return 0; } static int pohmelfs_remount(struct super_block *sb, int *flags, char *data) { int err; struct pohmelfs_sb *psb = POHMELFS_SB(sb); unsigned long old_sb_flags = sb->s_flags; err = pohmelfs_parse_options(data, psb, 1); if (err) goto err_out_restore; if (!(*flags & MS_RDONLY)) sb->s_flags &= ~MS_RDONLY; return 0; err_out_restore: sb->s_flags = old_sb_flags; return err; } static void pohmelfs_flush_inode(struct pohmelfs_inode *pi, unsigned int count) { struct inode *inode = &pi->vfs_inode; dprintk("%s: %p: ino: %llu, owned: %d.\n", __func__, inode, pi->ino, test_bit(NETFS_INODE_OWNED, &pi->state)); mutex_lock(&inode->i_mutex); if (test_and_clear_bit(NETFS_INODE_OWNED, &pi->state)) { filemap_fdatawrite(inode->i_mapping); inode->i_sb->s_op->write_inode(inode, 0); } #ifdef POHMELFS_TRUNCATE_ON_INODE_FLUSH truncate_inode_pages(inode->i_mapping, 0); #endif pohmelfs_data_unlock(pi, 0, ~0, POHMELFS_WRITE_LOCK); mutex_unlock(&inode->i_mutex); } static void pohmelfs_put_inode_count(struct pohmelfs_inode *pi, unsigned int count) { dprintk("%s: ino: %llu, pi: %p, inode: %p, count: %u.\n", __func__, pi->ino, pi, &pi->vfs_inode, count); if (test_and_clear_bit(NETFS_INODE_NEED_FLUSH, &pi->state)) pohmelfs_flush_inode(pi, count); while (count--) iput(&pi->vfs_inode); } static void pohmelfs_drop_scan(struct work_struct *work) { struct pohmelfs_sb *psb = container_of(work, struct pohmelfs_sb, drop_dwork.work); struct pohmelfs_inode *pi; unsigned int count = 0; while ((pi = pohmelfs_get_inode_from_list(psb, &psb->drop_list, &count))) pohmelfs_put_inode_count(pi, count); pohmelfs_check_states(psb); if (psb->drop_scan_timeout) schedule_delayed_work(&psb->drop_dwork, psb->drop_scan_timeout); } /* * Run through all transactions starting from the oldest, * drop transaction from current state and try to send it * to all remote nodes, which are currently installed. */ static void pohmelfs_trans_scan_state(struct netfs_state *st) { struct rb_node *rb_node; struct netfs_trans_dst *dst; struct pohmelfs_sb *psb = st->psb; unsigned int timeout = psb->trans_scan_timeout; struct netfs_trans *t; int err; mutex_lock(&st->trans_lock); for (rb_node = rb_first(&st->trans_root); rb_node; ) { dst = rb_entry(rb_node, struct netfs_trans_dst, state_entry); t = dst->trans; if (timeout && time_after(dst->send_time + timeout, jiffies) && dst->retries == 0) break; dprintk("%s: t: %p, gen: %u, st: %p, retries: %u, max: %u.\n", __func__, t, t->gen, st, dst->retries, psb->trans_retries); netfs_trans_get(t); rb_node = rb_next(rb_node); err = -ETIMEDOUT; if (timeout && (++dst->retries < psb->trans_retries)) err = netfs_trans_resend(t, psb); if (err || (t->flags & NETFS_TRANS_SINGLE_DST)) { if (netfs_trans_remove_nolock(dst, st)) netfs_trans_drop_dst_nostate(dst); } t->result = err; netfs_trans_put(t); } mutex_unlock(&st->trans_lock); } /* * Walk through all installed network states and resend all * transactions, which are old enough. */ static void pohmelfs_trans_scan(struct work_struct *work) { struct pohmelfs_sb *psb = container_of(work, struct pohmelfs_sb, dwork.work); struct netfs_state *st; struct pohmelfs_config *c; mutex_lock(&psb->state_lock); list_for_each_entry(c, &psb->state_list, config_entry) { st = &c->state; pohmelfs_trans_scan_state(st); } mutex_unlock(&psb->state_lock); /* * If no timeout specified then system is in the middle of umount process, * so no need to reschedule scanning process again. */ if (psb->trans_scan_timeout) schedule_delayed_work(&psb->dwork, psb->trans_scan_timeout); } int pohmelfs_meta_command_data(struct pohmelfs_inode *pi, u64 id, unsigned int cmd_op, char *addon, unsigned int flags, netfs_trans_complete_t complete, void *priv, u64 start) { struct inode *inode = &pi->vfs_inode; struct pohmelfs_sb *psb = POHMELFS_SB(inode->i_sb); int err = 0, sz; struct netfs_trans *t; int path_len, addon_len = 0; void *data; struct netfs_inode_info *info; struct netfs_cmd *cmd; dprintk("%s: ino: %llu, cmd: %u, addon: %p.\n", __func__, pi->ino, cmd_op, addon); path_len = pohmelfs_path_length(pi); if (path_len < 0) { err = path_len; goto err_out_exit; } if (addon) addon_len = strlen(addon) + 1; /* 0-byte */ sz = addon_len; if (cmd_op == NETFS_INODE_INFO) sz += sizeof(struct netfs_inode_info); t = netfs_trans_alloc(psb, sz + path_len, flags, 0); if (!t) { err = -ENOMEM; goto err_out_exit; } t->complete = complete; t->private = priv; cmd = netfs_trans_current(t); data = (void *)(cmd + 1); if (cmd_op == NETFS_INODE_INFO) { info = (struct netfs_inode_info *)(cmd + 1); data = (void *)(info + 1); /* * We are under i_mutex, can read and change whatever we want... */ info->mode = inode->i_mode; info->nlink = inode->i_nlink; info->uid = inode->i_uid; info->gid = inode->i_gid; info->blocks = inode->i_blocks; info->rdev = inode->i_rdev; info->size = inode->i_size; info->version = inode->i_version; netfs_convert_inode_info(info); } path_len = pohmelfs_construct_path_string(pi, data, path_len); if (path_len < 0) goto err_out_free; dprintk("%s: path_len: %d.\n", __func__, path_len); if (addon) { path_len--; /* Do not place null-byte before the addon */ path_len += sprintf(data + path_len, "/%s", addon) + 1; /* 0 - byte */ } sz += path_len; cmd->cmd = cmd_op; cmd->ext = path_len; cmd->size = sz; cmd->id = id; cmd->start = start; netfs_convert_cmd(cmd); netfs_trans_update(cmd, t, sz); /* * Note, that it is possible to leak error here: transaction callback will not * be invoked for allocation path failure. */ return netfs_trans_finish(t, psb); err_out_free: netfs_trans_free(t); err_out_exit: if (complete) complete(NULL, 0, priv, err); return err; } int pohmelfs_meta_command(struct pohmelfs_inode *pi, unsigned int cmd_op, unsigned int flags, netfs_trans_complete_t complete, void *priv, u64 start) { return pohmelfs_meta_command_data(pi, pi->ino, cmd_op, NULL, flags, complete, priv, start); } /* * Send request and wait for POHMELFS root capabilities response, * which will update server's informaion about size of the export, * permissions, number of objects, available size and so on. */ static int pohmelfs_root_handshake(struct pohmelfs_sb *psb) { struct netfs_trans *t; struct netfs_cmd *cmd; int err = -ENOMEM; t = netfs_trans_alloc(psb, 0, 0, 0); if (!t) goto err_out_exit; cmd = netfs_trans_current(t); cmd->cmd = NETFS_CAPABILITIES; cmd->id = POHMELFS_ROOT_CAPABILITIES; cmd->size = 0; cmd->start = 0; cmd->ext = 0; cmd->csize = 0; netfs_convert_cmd(cmd); netfs_trans_update(cmd, t, 0); err = netfs_trans_finish(t, psb); if (err) goto err_out_exit; psb->flags = ~0; err = wait_event_interruptible_timeout(psb->wait, (psb->flags != ~0), psb->wait_on_page_timeout); if (!err) err = -ETIMEDOUT; else if (err > 0) err = -psb->flags; if (err) goto err_out_exit; return 0; err_out_exit: return err; } static int pohmelfs_show_stats(struct seq_file *m, struct vfsmount *mnt) { struct netfs_state *st; struct pohmelfs_ctl *ctl; struct pohmelfs_sb *psb = POHMELFS_SB(mnt->mnt_sb); struct pohmelfs_config *c; mutex_lock(&psb->state_lock); seq_printf(m, "\nidx addr(:port) socket_type protocol active priority permissions\n"); list_for_each_entry(c, &psb->state_list, config_entry) { st = &c->state; ctl = &st->ctl; seq_printf(m, "%u ", ctl->idx); if (ctl->addr.sa_family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in *)&st->ctl.addr; seq_printf(m, "%pI4:%u", &sin->sin_addr.s_addr, ntohs(sin->sin_port)); } else if (ctl->addr.sa_family == AF_INET6) { struct sockaddr_in6 *sin = (struct sockaddr_in6 *)&st->ctl.addr; seq_printf(m, "%pi6:%u", &sin->sin6_addr, ntohs(sin->sin6_port)); } else { unsigned int i; for (i = 0; i < ctl->addrlen; ++i) seq_printf(m, "%02x.", ctl->addr.addr[i]); } seq_printf(m, " %u %u %d %u %x\n", ctl->type, ctl->proto, st->socket != NULL, ctl->prio, ctl->perm); } mutex_unlock(&psb->state_lock); return 0; } static const struct super_operations pohmelfs_sb_ops = { .alloc_inode = pohmelfs_alloc_inode, .destroy_inode = pohmelfs_destroy_inode, .drop_inode = pohmelfs_drop_inode, .write_inode = pohmelfs_write_inode, .put_super = pohmelfs_put_super, .remount_fs = pohmelfs_remount, .statfs = pohmelfs_statfs, .show_options = pohmelfs_show_options, .show_stats = pohmelfs_show_stats, }; /* * Allocate private superblock and create root dir. */ static int pohmelfs_fill_super(struct super_block *sb, void *data, int silent) { struct pohmelfs_sb *psb; int err = -ENOMEM; struct inode *root; struct pohmelfs_inode *npi; struct qstr str; psb = kzalloc(sizeof(struct pohmelfs_sb), GFP_KERNEL); if (!psb) goto err_out_exit; err = bdi_init(&psb->bdi); if (err) goto err_out_free_sb; err = bdi_register(&psb->bdi, NULL, "pfs-%d", atomic_inc_return(&psb_bdi_num)); if (err) { bdi_destroy(&psb->bdi); goto err_out_free_sb; } sb->s_fs_info = psb; sb->s_op = &pohmelfs_sb_ops; sb->s_magic = POHMELFS_MAGIC_NUM; sb->s_maxbytes = MAX_LFS_FILESIZE; sb->s_blocksize = PAGE_SIZE; sb->s_bdi = &psb->bdi; psb->sb = sb; psb->ino = 2; psb->idx = 0; psb->active_state = NULL; psb->trans_retries = 5; psb->trans_data_size = PAGE_SIZE; psb->drop_scan_timeout = msecs_to_jiffies(1000); psb->trans_scan_timeout = msecs_to_jiffies(5000); psb->wait_on_page_timeout = msecs_to_jiffies(5000); init_waitqueue_head(&psb->wait); spin_lock_init(&psb->ino_lock); INIT_LIST_HEAD(&psb->drop_list); mutex_init(&psb->mcache_lock); psb->mcache_root = RB_ROOT; psb->mcache_timeout = msecs_to_jiffies(5000); atomic_long_set(&psb->mcache_gen, 0); psb->trans_max_pages = 100; psb->crypto_align_size = 16; psb->crypto_attached_size = 0; psb->hash_strlen = 0; psb->cipher_strlen = 0; psb->perform_crypto = 0; psb->crypto_thread_num = 2; psb->crypto_fail_unsupported = 0; mutex_init(&psb->crypto_thread_lock); INIT_LIST_HEAD(&psb->crypto_ready_list); INIT_LIST_HEAD(&psb->crypto_active_list); atomic_set(&psb->trans_gen, 1); atomic_long_set(&psb->total_inodes, 0); mutex_init(&psb->state_lock); INIT_LIST_HEAD(&psb->state_list); err = pohmelfs_parse_options((char *) data, psb, 0); if (err) goto err_out_free_bdi; err = pohmelfs_copy_crypto(psb); if (err) goto err_out_free_bdi; err = pohmelfs_state_init(psb); if (err) goto err_out_free_strings; err = pohmelfs_crypto_init(psb); if (err) goto err_out_state_exit; err = pohmelfs_root_handshake(psb); if (err) goto err_out_crypto_exit; str.name = "/"; str.hash = jhash("/", 1, 0); str.len = 1; npi = pohmelfs_create_entry_local(psb, NULL, &str, 0, 0755|S_IFDIR); if (IS_ERR(npi)) { err = PTR_ERR(npi); goto err_out_crypto_exit; } set_bit(NETFS_INODE_REMOTE_SYNCED, &npi->state); clear_bit(NETFS_INODE_OWNED, &npi->state); root = &npi->vfs_inode; sb->s_root = d_alloc_root(root); if (!sb->s_root) goto err_out_put_root; INIT_DELAYED_WORK(&psb->drop_dwork, pohmelfs_drop_scan); schedule_delayed_work(&psb->drop_dwork, psb->drop_scan_timeout); INIT_DELAYED_WORK(&psb->dwork, pohmelfs_trans_scan); schedule_delayed_work(&psb->dwork, psb->trans_scan_timeout); return 0; err_out_put_root: iput(root); err_out_crypto_exit: pohmelfs_crypto_exit(psb); err_out_state_exit: pohmelfs_state_exit(psb); err_out_free_strings: kfree(psb->cipher_string); kfree(psb->hash_string); err_out_free_bdi: bdi_destroy(&psb->bdi); err_out_free_sb: kfree(psb); err_out_exit: dprintk("%s: err: %d.\n", __func__, err); return err; } /* * Some VFS magic here... */ static int pohmelfs_get_sb(struct file_system_type *fs_type, int flags, const char *dev_name, void *data, struct vfsmount *mnt) { return get_sb_nodev(fs_type, flags, data, pohmelfs_fill_super, mnt); } /* * We need this to sync all inodes earlier, since when writeback * is invoked from the umount/mntput path dcache is already shrunk, * see generic_shutdown_super(), and no inodes can access the path. */ static void pohmelfs_kill_super(struct super_block *sb) { sync_inodes_sb(sb); kill_anon_super(sb); } static struct file_system_type pohmel_fs_type = { .owner = THIS_MODULE, .name = "pohmel", .get_sb = pohmelfs_get_sb, .kill_sb = pohmelfs_kill_super, }; /* * Cache and module initializations and freeing routings. */ static void pohmelfs_init_once(void *data) { struct pohmelfs_inode *pi = data; inode_init_once(&pi->vfs_inode); } static int __init pohmelfs_init_inodecache(void) { pohmelfs_inode_cache = kmem_cache_create("pohmelfs_inode_cache", sizeof(struct pohmelfs_inode), 0, (SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD), pohmelfs_init_once); if (!pohmelfs_inode_cache) return -ENOMEM; return 0; } static void pohmelfs_destroy_inodecache(void) { kmem_cache_destroy(pohmelfs_inode_cache); } static int __init init_pohmel_fs(void) { int err; err = pohmelfs_config_init(); if (err) goto err_out_exit; err = pohmelfs_init_inodecache(); if (err) goto err_out_config_exit; err = pohmelfs_mcache_init(); if (err) goto err_out_destroy; err = netfs_trans_init(); if (err) goto err_out_mcache_exit; err = register_filesystem(&pohmel_fs_type); if (err) goto err_out_trans; return 0; err_out_trans: netfs_trans_exit(); err_out_mcache_exit: pohmelfs_mcache_exit(); err_out_destroy: pohmelfs_destroy_inodecache(); err_out_config_exit: pohmelfs_config_exit(); err_out_exit: return err; } static void __exit exit_pohmel_fs(void) { unregister_filesystem(&pohmel_fs_type); pohmelfs_destroy_inodecache(); pohmelfs_mcache_exit(); pohmelfs_config_exit(); netfs_trans_exit(); } module_init(init_pohmel_fs); module_exit(exit_pohmel_fs); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Evgeniy Polyakov <zbr@ioremap.net>"); MODULE_DESCRIPTION("Pohmel filesystem");
24.386197
105
0.700729
[ "object" ]
643f6f10c1d6fc698bd869825e4c0f3d4f65d8ae
26,389
c
C
gsl-2.6/linalg/rqr.c
ielomariala/Hex-Game
2c2e7c85f8414cb0e654cb82e9686cce5e75c63a
[ "MIT" ]
1
2021-06-14T11:51:37.000Z
2021-06-14T11:51:37.000Z
gsl-2.6/linalg/rqr.c
ielomariala/Hex-Game
2c2e7c85f8414cb0e654cb82e9686cce5e75c63a
[ "MIT" ]
6
2019-12-16T17:41:24.000Z
2019-12-22T00:00:16.000Z
test/lib/gsl-2.6/linalg/rqr.c
karanbirsandhu/nu-sense
83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b
[ "MIT" ]
2
2021-01-20T16:22:57.000Z
2021-02-14T12:31:02.000Z
/* linalg/rqr.c * * Copyright (C) 2019 Patrick Alken, Julien Langou * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> /* * this module contains routines for the QR factorization of a matrix * using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with * additional modifications courtesy of Julien Langou. */ static int unpack_Q1(gsl_matrix * Q); static int unpack_Q2(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q); static int aux_ULT(const gsl_matrix * L, gsl_matrix * U); static int aux_mLU(gsl_matrix * A); static int aux_ApUBT(const gsl_matrix * U, const gsl_matrix * B, gsl_matrix * A); /* gsl_linalg_QR_decomp_r() QR decomposition using Level 3 BLAS recursive algorithm of: Elmroth, E. and Gustavson, F.G., 2000. Applying recursion to serial and parallel QR factorization leads to better performance. IBM Journal of Research and Development, 44(4), pp.605-624. Inputs: A - matrix to be factored, M-by-N with M >= N T - N-by-N upper triangular factor of block reflector Return: success/error Notes: 1) on output, upper triangle of A contains R; elements below the diagonal are columns of V. The matrix Q is Q = I - V T V^T where T is upper triangular. Note that diag(T) = tau 2) implementation provided by Julien Langou */ int gsl_linalg_QR_decomp_r (gsl_matrix * A, gsl_matrix * T) { const size_t M = A->size1; const size_t N = A->size2; if (M < N) { GSL_ERROR ("M must be >= N", GSL_EBADLEN); } else if (T->size1 != T->size2) { GSL_ERROR ("T matrix must be square", GSL_ENOTSQR); } else if (T->size1 != N) { GSL_ERROR ("T matrix does not match dimensions of A", GSL_EBADLEN); } else if (N == 1) { /* base case, compute householder transform for single column matrix */ double * T00 = gsl_matrix_ptr(T, 0, 0); gsl_vector_view v = gsl_matrix_column(A, 0); *T00 = gsl_linalg_householder_transform(&v.vector); return GSL_SUCCESS; } else { /* * partition matrices: * * N1 N2 N1 N2 * N1 [ A11 A12 ] and N1 [ T11 T12 ] * M2 [ A21 A22 ] N2 [ 0 T22 ] */ int status; const size_t N1 = N / 2; const size_t N2 = N - N1; const size_t M2 = M - N1; gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1); gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2); gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, M2, N1); gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, M2, N2); gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1); gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2); gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2); gsl_matrix_view m; /* * Eq. 2: recursively factor * * [ A11 ] = Q1 [ R11 ] * [ A21 ] [ 0 ] * N1 * Note: Q1 = I - V1 T11 V1^T, where V1 = [ V11 ] N1 * [ V21 ] M2 */ m = gsl_matrix_submatrix(A, 0, 0, M, N1); status = gsl_linalg_QR_decomp_r(&m.matrix, &T11.matrix); if (status) return status; /* * Eq. 3: * * [ R12 ] := Q1^T [ A12 ] = [ A12 ] - [ V11 W ] * [ A22 ] [ A22 ] [ A22 ] [ V21 W ] * * where W = T11^T (V11^T A12 + V21^T A22), and using T12 as temporary storage */ gsl_matrix_memcpy(&T12.matrix, &A12.matrix); /* W := A12 */ gsl_blas_dtrmm(CblasLeft, CblasLower, CblasTrans, CblasUnit, 1.0, &A11.matrix, &T12.matrix); /* W := V11^T * A12 */ gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A21.matrix, &A22.matrix, 1.0, &T12.matrix); /* W := W + V21^T * A22 */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T * W */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A21.matrix, &T12.matrix, 1.0, &A22.matrix); /* A22 = A22 - V21 * W */ gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &A11.matrix, &T12.matrix); /* tmp = V11 * W */ gsl_matrix_sub(&A12.matrix, &T12.matrix); /* R12 := A12 - V11 * W */ /* * Eq. 4: recursively factor * * A22 = Q2~ R22 * * N1 M2 * Note: Q2 = [ I 0 ] N1 * [ 0 Q2~ ] M2 */ status = gsl_linalg_QR_decomp_r(&A22.matrix, &T22.matrix); if (status) return status; /* * Eq. 13: update T12 := -T11 * V1^T * V2 * T22 * * where: * * N1 N2 * V1 = [ V11 ] N1 V2 = [ 0 ] N1 * [ V21 ] N2 [ V22 ] N2 * [ V31 ] M-N [ V32 ] M-N * * Note: V1^T V2 = V21^T V22 + V31^T V32 * Also, V11, V22 are unit lower triangular */ m = gsl_matrix_submatrix(&A21.matrix, 0, 0, N2, N1); /* V21 */ gsl_matrix_transpose_memcpy(&T12.matrix, &m.matrix); /* T12 := V21^T */ m = gsl_matrix_submatrix(A, N1, N1, N2, N2); /* V22 */ gsl_blas_dtrmm(CblasRight, CblasLower, CblasNoTrans, CblasUnit, 1.0, &m.matrix, &T12.matrix); /* T12 := V21^T * V22 */ if (M > N) { gsl_matrix_view V31 = gsl_matrix_submatrix(A, N, 0, M - N, N1); gsl_matrix_view V32 = gsl_matrix_submatrix(A, N, N1, M - N, N2); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &V31.matrix, &V32.matrix, 1.0, &T12.matrix); /* T12 := T12 + V31^T * V32 */ } gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */ gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */ return GSL_SUCCESS; } } /* Solves the square system A x = b for x using the QR factorisation, * * R x = Q^T b * * where Q = I - V T V^T */ int gsl_linalg_QR_solve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x) { const size_t N = QR->size2; if (QR->size1 != N) { GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR); } else if (T->size1 != QR->size1 || T->size2 != QR->size2) { GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN); } else if (N != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (N != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { size_t i; /* compute Q^T b = [I - V T^T V^T] b */ /* x := V^T b */ gsl_vector_memcpy(x, b); gsl_blas_dtrmv(CblasLower, CblasTrans, CblasUnit, QR, x); /* x = T^T * x */ gsl_blas_dtrmv(CblasUpper, CblasTrans, CblasNonUnit, T, x); /* x = V * x */ gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasUnit, QR, x); /* x = b - V * x */ for (i = 0; i < N; ++i) { double * xi = gsl_vector_ptr(x, i); double bi = gsl_vector_get(b, i); *xi = bi - (*xi); } /* Solve R x = Q^T b, storing x in-place */ gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x); return GSL_SUCCESS; } } /* Find the least squares solution to the overdetermined system * * A x = b * * for M >= N using the QR factorization A = Q R. * * Inputs: QR - [R; V] matrix, M-by-N * T - upper triangular block reflector, N-by-N * b - right hand side, size M * x - (output) solution, size M * x(1:N) = least squares solution vector * x(N+1:M) = vector whose norm equals ||b - Ax|| * work - workspace, size N */ int gsl_linalg_QR_lssolve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x, gsl_vector * work) { const size_t M = QR->size1; const size_t N = QR->size2; if (M < N) { GSL_ERROR ("QR matrix must have M >= N", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN); } else if (M != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (M != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else if (N != work->size) { GSL_ERROR ("matrix size must match work size", GSL_EBADLEN); } else { gsl_matrix_const_view R = gsl_matrix_const_submatrix (QR, 0, 0, N, N); gsl_vector_view x1 = gsl_vector_subvector(x, 0, N); /* compute x = Q^T b */ gsl_vector_memcpy(x, b); gsl_linalg_QR_QTvec_r (QR, T, x, work); /* Solve R x = Q^T b */ gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, &R.matrix, &x1.vector); return GSL_SUCCESS; } } /* gsl_linalg_QR_unpack_r() Unpack matrices Q and R Inputs: QR - packed QR format, M-by-N T - block reflector matrix, N-by-N Q - (output) Q matrix, M-by-M R - (output) R matrix, N-by-N Return: success/error Notes: 1) Implementation provided by Julien Langou */ int gsl_linalg_QR_unpack_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q, gsl_matrix * R) { const size_t M = QR->size1; const size_t N = QR->size2; if (M < N) { GSL_ERROR ("M must be >= N", GSL_EBADLEN); } else if (Q->size1 != M || Q->size2 != M) { GSL_ERROR ("Q matrix must be M-by-M", GSL_EBADLEN); } else if (R->size1 != N || R->size2 != N) { GSL_ERROR ("R matrix must be N-by-N", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN); } else { gsl_matrix_const_view RV = gsl_matrix_const_submatrix(QR, 0, 0, N, N); gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, M, N); gsl_matrix_view m; /* * set Q1 = [ T ] * [ V ] */ m = gsl_matrix_submatrix(Q, 0, 0, N, N); gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &m.matrix, T); gsl_matrix_tricpy(CblasLower, CblasUnit, &m.matrix, &RV.matrix); if (M > N) { gsl_matrix_const_view tmp = gsl_matrix_const_submatrix(QR, N, 0, M - N, N); m = gsl_matrix_submatrix(Q, N, 0, M - N, N); gsl_matrix_memcpy(&m.matrix, &tmp.matrix); } unpack_Q1(&Q1.matrix); if (M > N) { gsl_matrix_view Q2 = gsl_matrix_submatrix(Q, 0, N, M, M - N); unpack_Q2(QR, T, &Q2.matrix); } /* copy R */ gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, &RV.matrix); return GSL_SUCCESS; } } /* gsl_linalg_QR_QTvec_r() Apply M-by-M Q^T to the M-by-1 vector b Inputs: QR - [R; V] matrix encoded by gsl_linalg_QR_decomp_r T - block reflector matrix b - M-by-1 vector replaced by Q^T b on output work - workspace, length N Notes: 1) Q^T b = (I - V T^T V^T) b = b - V T^T [ V1^T V2^T ] [ b1 ] [ b2 ] = b - V T^T [ V1^T b1 + V2^T b2 ] = [ b1 ] - [ V1 w ] [ b2 ] [ V2 w ] where w = T^T ( V1^T b1 + V2^T b2 ) */ int gsl_linalg_QR_QTvec_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_vector * b, gsl_vector * work) { const size_t M = QR->size1; const size_t N = QR->size2; if (M < N) { GSL_ERROR ("M must be >= N", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN); } else if (b->size != M) { GSL_ERROR ("b vector must have length M", GSL_EBADLEN); } else if (work->size != N) { GSL_ERROR ("workspace must be length N", GSL_EBADLEN); } else { gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N); gsl_vector_view b1 = gsl_vector_subvector(b, 0, N); gsl_vector_view b2; /* work := V1^T b1 */ gsl_vector_memcpy(work, &b1.vector); gsl_blas_dtrmv(CblasLower, CblasTrans, CblasUnit, &V1.matrix, work); if (M > N) { gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N); /* work = work + V2^T b2 */ b2 = gsl_vector_subvector(b, N, M - N); gsl_blas_dgemv(CblasTrans, 1.0, &V2.matrix, &b2.vector, 1.0, work); } /* work = T^T * work */ gsl_blas_dtrmv(CblasUpper, CblasTrans, CblasNonUnit, T, work); if (M > N) { /* b2 = b2 - V2 * work */ gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N); gsl_blas_dgemv(CblasNoTrans, -1.0, &V2.matrix, work, 1.0, &b2.vector); } /* b1 = b1 - V1 * work */ gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasUnit, &V1.matrix, work); gsl_vector_sub(&b1.vector, work); return GSL_SUCCESS; } } /* gsl_linalg_QR_QTmat_r() Apply M-by-M Q^T to the M-by-K matrix B Inputs: QR - [R; V] matrix encoded by gsl_linalg_QR_decomp_r T - block reflector matrix B - M-by-K matrix replaced by Q^T B on output work - N-by-K workspace Notes: 1) Provided by Julien Langou */ int gsl_linalg_QR_QTmat_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * B, gsl_matrix * work) { const size_t M = QR->size1; const size_t N = QR->size2; const size_t K = B->size2; if (M < N) { GSL_ERROR ("M must be >= N", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN); } else if (B->size1 != M) { GSL_ERROR ("B matrix must have M rows", GSL_EBADLEN); } else if (work->size1 != N || work->size2 != K) { GSL_ERROR ("workspace must be N-by-K", GSL_EBADLEN); } else { gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N); gsl_matrix_view B1 = gsl_matrix_submatrix(B, 0, 0, N, K); gsl_matrix_view B2; /* work := V1^T B1 */ gsl_matrix_memcpy(work, &B1.matrix); gsl_blas_dtrmm(CblasLeft, CblasLower, CblasTrans, CblasUnit, 1.0, &V1.matrix, work); if (M > N) { gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N); /* work = work + V2^T B2 */ B2 = gsl_matrix_submatrix(B, N, 0, M - N, K); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &V2.matrix, &B2.matrix, 1.0, work); } /* work = T^T * work */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, T, work); if (M > N) { /* B2 = B2 - V2 * work */ gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &V2.matrix, work, 1.0, &B2.matrix); } /* B1 = B1 - V1 * work */ gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &V1.matrix, work); gsl_matrix_sub(&B1.matrix, work); return GSL_SUCCESS; } } /* unpack_Q1() Compute Q_1 Inputs: Q - on input, contains T in upper triangle and V in lower trapezoid on output, contains Q_1 M-by-N Return: success/error Notes: 1) N Q1 = [ Q1 Q2 ] [ I_n ] = (I - V T V^T) [ I; 0 ] = [ I - V1 T V1^T ] N [ 0 ] [ - V2 T V1^T ] M - N */ static int unpack_Q1(gsl_matrix * Q) { int status; const size_t M = Q->size1; const size_t N = Q->size2; gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, N, N); gsl_vector_view diag = gsl_matrix_diagonal(&Q1.matrix); /* Q1 := T V1^T */ status = aux_ULT(&Q1.matrix, &Q1.matrix); if (status) return status; if (M > N) { /* compute Q2 := - V2 T V1^T */ gsl_matrix_view V2 = gsl_matrix_submatrix(Q, N, 0, M - N, N); gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &Q1.matrix, &V2.matrix); } /* Q1 := - V1 T V1^T */ status = aux_mLU(&Q1.matrix); if (status) return status; /* Q1 := I - V1 T V1^T */ gsl_vector_add_constant(&diag.vector, 1.0); return GSL_SUCCESS; } /* unpack_Q2() Compute Q_2 Inputs: QR - [R; V] from QR_decomp_r, M-by-N T - upper triangular T factor, N-by-N Q - (output) Q_2 factor, M-by-(M-N) Return: success/error Notes: N M-N 1) Since Q = I - V T V^T = M [ Q1 Q2 ], we have M-N Q2 = Q [ 0 ] N [ I_{M-N} ] M-N So, Q2 = Q [ 0; I ] = (I - V T V^T) [ 0; I ] = [ - V1 T V2^T ] [ I - V2 T V2^T ] */ static int unpack_Q2(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q) { const size_t M = QR->size1; const size_t N = QR->size2; if (M <= N) { GSL_ERROR ("M must be > N", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN); } else if (Q->size1 != M || Q->size2 != (M - N)) { GSL_ERROR ("Q matrix must be M-by-(M-N)", GSL_EBADLEN); } else { gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N); gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N); gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, N, M - N); gsl_matrix_view Q2 = gsl_matrix_submatrix(Q, N, 0, M - N, M - N); gsl_vector_view diag = gsl_matrix_diagonal(&Q2.matrix); /* Q1 := V2^T */ gsl_matrix_transpose_memcpy(&Q1.matrix, &V2.matrix); /* Q1 := - T V2^T */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, T, &Q1.matrix); /* Q2 := - V2 T V2^T */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &V2.matrix, &Q1.matrix, 0.0, &Q2.matrix); /* Q2 := I - V2 T V2^T */ gsl_vector_add_constant(&diag.vector, 1.0); /* Q1 := - V1 T V2^T */ gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &V1.matrix, &Q1.matrix); return GSL_SUCCESS; } } /* U := U L^T for triangular matrices L and U; L is unit lower triangular */ static int aux_ULT(const gsl_matrix * L, gsl_matrix * U) { const size_t N = L->size1; if (N != L->size2) { GSL_ERROR ("L matrix must be square", GSL_ENOTSQR); } else if (U->size1 != N || U->size2 != N) { GSL_ERROR ("U matrix must be same size as L", GSL_EBADLEN); } else if (N == 1) { /* nothing to do */ return GSL_SUCCESS; } else { int status; const size_t N1 = N / 2; const size_t N2 = N - N1; gsl_matrix_const_view L11 = gsl_matrix_const_submatrix(L, 0, 0, N1, N1); gsl_matrix_const_view L21 = gsl_matrix_const_submatrix(L, N1, 0, N2, N1); gsl_matrix_const_view L22 = gsl_matrix_const_submatrix(L, N1, N1, N2, N2); gsl_matrix_view U11 = gsl_matrix_submatrix(U, 0, 0, N1, N1); gsl_matrix_view U12 = gsl_matrix_submatrix(U, 0, N1, N1, N2); gsl_matrix_view U22 = gsl_matrix_submatrix(U, N1, N1, N2, N2); /* U12 = U12 * L22^T */ gsl_blas_dtrmm(CblasRight, CblasLower, CblasTrans, CblasUnit, 1.0, &L22.matrix, &U12.matrix); /* U12 = U12 + U11 * L21^T */ status = aux_ApUBT(&U11.matrix, &L21.matrix, &U12.matrix); if (status) return status; status = aux_ULT(&L11.matrix, &U11.matrix); if (status) return status; status = aux_ULT(&L22.matrix, &U22.matrix); if (status) return status; return GSL_SUCCESS; } } /* store -L*U in A */ static int aux_mLU(gsl_matrix * A) { const size_t N = A->size1; if (N != A->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N == 1) { double *A00 = gsl_matrix_ptr(A, 0, 0); *A00 = -(*A00); return GSL_SUCCESS; } else { int status; const size_t N1 = N / 2; const size_t N2 = N - N1; gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1); gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2); gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, N2, N1); gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, N2, N2); /* A22 = - L22 U22 */ status = aux_mLU(&A22.matrix); if (status) return status; /* A22 = A22 - L21 U12 */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A21.matrix, &A12.matrix, 1.0, &A22.matrix); /* A12 - -L11 U12 */ gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, -1.0, &A11.matrix, &A12.matrix); /* A21 = -L21 U11 */ gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &A11.matrix, &A21.matrix); /* A11 = - L11 U11 */ status = aux_mLU(&A11.matrix); if (status) return status; return GSL_SUCCESS; } } /* A := A + U B^T where U is upper triangular */ static int aux_ApUBT(const gsl_matrix * U, const gsl_matrix * B, gsl_matrix * A) { const size_t M = A->size1; const size_t N = A->size2; if (U->size1 != M || U->size2 != M) { GSL_ERROR ("U matrix has wrong dimensions", GSL_EBADLEN); } else if (B->size1 != N || B->size2 != M) { GSL_ERROR ("B matrix has wrong dimensions", GSL_EBADLEN); } else if (M == 1 && N == 1) { double *aptr = gsl_matrix_ptr(A, 0, 0); const double *uptr = gsl_matrix_const_ptr(U, 0, 0); const double *bptr = gsl_matrix_const_ptr(B, 0, 0); *aptr += (*uptr) * (*bptr); return GSL_SUCCESS; } else if (M == 1) { double U00 = gsl_matrix_get(U, 0, 0); gsl_vector_view v = gsl_matrix_row(A, 0); gsl_vector_const_view w = gsl_matrix_const_column(B, 0); gsl_blas_daxpy(U00, &w.vector, &v.vector); return GSL_SUCCESS; } else if (N == 1) { /* * partition: * * M1 M2 * B = 1 [ B11 B12 ] * * 1 M1 M2 1 * M1 [ A11 ] + [ U11 U12 ] [ B11^T ] M1 * M2 [ A21 ] [ 0 U22 ] [ B12^T ] M2 */ int status; const size_t M1 = M / 2; const size_t M2 = M - M1; gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, M1, 1); gsl_matrix_view A21 = gsl_matrix_submatrix(A, M1, 0, M2, 1); gsl_vector_view a1 = gsl_matrix_subcolumn(A, 0, 0, M1); gsl_matrix_const_view U11 = gsl_matrix_const_submatrix(U, 0, 0, M1, M1); gsl_matrix_const_view U12 = gsl_matrix_const_submatrix(U, 0, M1, M1, M2); gsl_matrix_const_view U22 = gsl_matrix_const_submatrix(U, M1, M1, M2, M2); gsl_matrix_const_view B11 = gsl_matrix_const_submatrix(B, 0, 0, 1, M1); gsl_matrix_const_view B12 = gsl_matrix_const_submatrix(B, 0, M1, 1, M2); gsl_vector_const_view b2 = gsl_matrix_const_subrow(B, 0, M1, M2); /* A(1:M1,1) += U12 * B12^T */ gsl_blas_dgemv(CblasNoTrans, 1.0, &U12.matrix, &b2.vector, 1.0, &a1.vector); /* A11 := A11 + U11 B11^T */ status = aux_ApUBT(&U11.matrix, &B11.matrix, &A11.matrix); if (status) return status; /* A21 := A21 + U22 B12^T */ status = aux_ApUBT(&U22.matrix, &B12.matrix, &A21.matrix); if (status) return status; return GSL_SUCCESS; } else { int status; const size_t M1 = M / 2; const size_t M2 = M - M1; const size_t N1 = N / 2; const size_t N2 = N - N1; gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, M1, N1); gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, M1, N2); gsl_matrix_view A21 = gsl_matrix_submatrix(A, M1, 0, M2, N1); gsl_matrix_view A22 = gsl_matrix_submatrix(A, M1, N1, M2, N2); gsl_matrix_const_view U11 = gsl_matrix_const_submatrix(U, 0, 0, M1, M1); gsl_matrix_const_view U12 = gsl_matrix_const_submatrix(U, 0, M1, M1, M2); gsl_matrix_const_view U22 = gsl_matrix_const_submatrix(U, M1, M1, M2, M2); gsl_matrix_const_view B11 = gsl_matrix_const_submatrix(B, 0, 0, N1, M1); gsl_matrix_const_view B12 = gsl_matrix_const_submatrix(B, 0, M1, N1, M2); gsl_matrix_const_view B21 = gsl_matrix_const_submatrix(B, N1, 0, N2, M1); gsl_matrix_const_view B22 = gsl_matrix_const_submatrix(B, N1, M1, N2, M2); /* A11 := A11 + U11 B11^T */ status = aux_ApUBT(&U11.matrix, &B11.matrix, &A11.matrix); if (status) return status; /* A11 := A11 + U12 B12^T */ gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &U12.matrix, &B12.matrix, 1.0, &A11.matrix); /* A12 := A12 + U11 B21^T */ status = aux_ApUBT(&U11.matrix, &B21.matrix, &A12.matrix); if (status) return status; /* A12 := A12 + U12 B22^T */ gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &U12.matrix, &B22.matrix, 1.0, &A12.matrix); /* A21 := A21 + U22 B12^T */ status = aux_ApUBT(&U22.matrix, &B12.matrix, &A21.matrix); if (status) return status; /* A22 := A22 + U22 B22^T */ status = aux_ApUBT(&U22.matrix, &B22.matrix, &A22.matrix); if (status) return status; return GSL_SUCCESS; } }
30.021615
135
0.56732
[ "vector", "transform" ]
6440f6fc75f706feb895c02968f3dde252aee8a7
1,519
h
C
client/include/Sphere.h
cainzhou96/Gaia
a2f942d47d1d7d7b706fbd182469acc41eb535ca
[ "MIT" ]
null
null
null
client/include/Sphere.h
cainzhou96/Gaia
a2f942d47d1d7d7b706fbd182469acc41eb535ca
[ "MIT" ]
33
2020-04-03T05:55:38.000Z
2020-06-07T00:58:23.000Z
client/include/Sphere.h
cainzhou96/Gaia
a2f942d47d1d7d7b706fbd182469acc41eb535ca
[ "MIT" ]
4
2020-04-02T18:32:18.000Z
2022-02-06T21:36:41.000Z
// // Sphere.h // Gaia // // Created by Wenlin Mao on 4/18/20. // Copyright © 2020 SphereEnix. All rights reserved. // #ifndef Sphere_h #define Sphere_h #include "util.h" #include "Primitive.h" using namespace std; class Sphere : public Primitive { public: Sphere(); Sphere(float m, float r, const std::vector<std::string>& faces); Sphere(float mass, const glm::vec3& pos, const glm::vec3& vel, float r, const std::vector<std::string>& faces); ~Sphere(); glm::vec3 computeNormal(); glm::vec3 computeSurfaceV(); virtual void move (const glm::vec3& pos); virtual void move (const glm::mat4& transform); glm::vec3 getCenter() { return position; } float getRadius() { return radius; } void setRadius(float r); void draw(const glm::mat4& view, const glm::mat4& projection, GLuint shader); void reset(); void prepareDraw(); void createVerts(); void createIndices(); glm::vec3 checkCollision(glm::vec3 a, glm::vec3 b, glm::vec3 c, glm::vec3 n); glm::vec3 force = glm::vec3(0); glm::vec3 moveForce = glm::vec3(0); glm::vec3 moveMomentum = glm::vec3(0); private: float radius; int numLon; int numLat; unsigned int cubemapTexture; GLuint VAO; GLuint VBO_positions, VBO_normals, EBO; vector<glm::vec3> positions; vector<glm::vec3> normals; vector<unsigned int> indices; const float PI = glm::pi<float>(); }; #endif /* Sphere_h */
23.369231
81
0.621461
[ "vector", "transform" ]
6443cefe4f6cf48a1eb53b2b33ed4b1dda32a001
1,747
h
C
archsim/inc/util/LivePerformanceMeter.h
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
10
2020-07-14T22:09:30.000Z
2022-01-11T09:57:52.000Z
archsim/inc/util/LivePerformanceMeter.h
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
6
2020-07-09T12:01:57.000Z
2021-04-27T10:23:58.000Z
archsim/inc/util/LivePerformanceMeter.h
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
10
2020-07-29T17:05:26.000Z
2021-12-04T14:57:15.000Z
/* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */ /* * File: LivePerformanceMeter.h * Author: s0457958 * * Created on 20 August 2014, 10:21 */ #ifndef LIVEPERFORMANCEMETER_H #define LIVEPERFORMANCEMETER_H #include "define.h" #include "concurrent/Thread.h" #include <string> #include <vector> namespace gensim { class Processor; } namespace archsim { namespace util { class Counter64; class PerformanceSource { public: PerformanceSource(std::string name); virtual ~PerformanceSource(); virtual uint64_t GetValue() = 0; inline uint64_t GetDelta() { uint64_t delta = GetValue() - last; last = GetValue(); return delta; } inline std::string GetName() const { return name; } private: std::string name; uint64_t last; }; class CounterPerformanceSource : public PerformanceSource { public: CounterPerformanceSource(std::string name, const Counter64& counter); uint64_t GetValue() override; private: const Counter64& counter; }; class InstructionCountPerformanceSource : public PerformanceSource { public: InstructionCountPerformanceSource(gensim::Processor& cpu); uint64_t GetValue() override; private: gensim::Processor& cpu; }; class LivePerformanceMeter : public archsim::concurrent::Thread { public: LivePerformanceMeter(gensim::Processor& cpu, std::vector<PerformanceSource *> sources, std::string filename, uint32_t period = 1e6); void run(); void stop(); private: gensim::Processor& cpu; std::vector<PerformanceSource *> sources; std::string filename; uint32_t period; volatile bool terminate; }; } } #endif /* LIVEPERFORMANCEMETER_H */
17.826531
135
0.70063
[ "vector" ]
644492540b2a0b271d3112dc7cb9b71b7fa224c5
12,283
h
C
RemoteActionMapping/RamHelper.h
rajnishdey/rdkservices
9bc1be2caeea971f5e1cfb017b7328d0938ccaed
[ "BSD-2-Clause" ]
null
null
null
RemoteActionMapping/RamHelper.h
rajnishdey/rdkservices
9bc1be2caeea971f5e1cfb017b7328d0938ccaed
[ "BSD-2-Clause" ]
null
null
null
RemoteActionMapping/RamHelper.h
rajnishdey/rdkservices
9bc1be2caeea971f5e1cfb017b7328d0938ccaed
[ "BSD-2-Clause" ]
null
null
null
/** * If not stated otherwise in this file or this component's LICENSE * file the following copyright and licenses apply: * * Copyright 2019 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #pragma once #include "Module.h" //IARM includes #include "libIBus.h" #include "ctrlm_ipc.h" #include "ctrlm_ipc_rcu.h" #include <string> #include <vector> #include "comcastIrKeyCodes.h" typedef std::vector<unsigned char> byte_vector_t; typedef std::vector<int> int_vector_t; #define RAMS_USE_FORCE_DOWNLOAD 1 struct controller_info { ctrlm_network_id_t network_id; ctrlm_controller_id_t controller_id; ctrlm_controller_status_t status; }; struct rf4ceBindRemotes_t { int numBindRemotes; controller_info remotes[CTRLM_MAIN_MAX_BOUND_CONTROLLERS]; }; // Mapped MSO RF Keys #define MSO_RFKEY_INPUT_SELECT 0x034 #define MSO_RFKEY_VOL_PLUS 0x041 #define MSO_RFKEY_VOL_MINUS 0x042 #define MSO_RFKEY_MUTE 0x043 #define XRC_RFKEY_TV_PWR_TOGGLE 0x040 // 3 new TV power keycodes (XRC Profile update) #define XRC_RFKEY_TV_PWR_ON 0x04D #define XRC_RFKEY_TV_PWR_OFF 0x04E #define XRC_RFKEY_AVR_PWR_TOGGLE 0x068 // 3 new AVR power keycodes (XRC Profile update) #define XRC_RFKEY_AVR_PWR_OFF 0x069 #define XRC_RFKEY_AVR_PWR_ON 0x06A #define MSO_RFKEY_PWR_TOGGLE 0x06B // Older power keycodes #define MSO_RFKEY_PWR_OFF 0x06C #define MSO_RFKEY_PWR_ON 0x06D // IR-RF Database Flags byte bit masks #define MSO_RIB_IRRFDB_PERMANENT_BIT 0x080 #define MSO_RIB_IRRFDB_DEFAULT_BIT 0x040 #define MSO_RIB_IRRFDB_DEVICETYPE_BITS 0x030 #define MSO_RIB_IRRFDB_DEVICETYPE_AVR 0x020 #define MSO_RIB_IRRFDB_IRSPECIFIED_BIT 0x008 #define MSO_RIB_IRRFDB_RFRELEASED_BIT 0x004 #define MSO_RIB_IRRFDB_RFREPEATED_BIT 0x002 #define MSO_RIB_IRRFDB_RFPRESSED_BIT 0x001 // IR-RF Status Flags byte bit masks #define XRC_RIB_IRRFSTATUS_DOWNLOAD_IRDB_BIT 0x080 #define XRC_RIB_IRRFSTATUS_DONT_DOWNLOAD_IRDB_BIT 0x040 #define XRC_RIB_IRRFSTATUS_CLEAR_ALL_5DCODES_BIT 0x010 #define XRC_RIB_IRRFSTATUS_TRANSMIT_DESCRIPTOR_BIT 0x008 #define XRC_RIB_IRRFSTATUS_DOWNLOAD_AVR_5DCODE_BIT 0x004 #define XRC_RIB_IRRFSTATUS_DOWNLOAD_TV_5DCODE_BIT 0x002 #define XRC_RIB_IRRFSTATUS_FORCE_IRDB_BIT 0x001 // Controller IRDB Status Flags byte bit masks #define XRC_RIB_CTRLR_STATUS_FLAGS_5DIGIT_SUPPORT_BIT 0x080 #define XRC_RIB_CTRLR_STATUS_FLAGS_AVR_CODE_PRESENT_BIT 0x010 #define XRC_RIB_CTRLR_STATUS_FLAGS_TV_CODE_PRESENT_BIT 0x008 #define XRC_RIB_CTRLR_STATUS_FLAGS_IRRF_DATABASE_BIT 0x004 #define XRC_RIB_CTRLR_STATUS_FLAGS_IRDB_TYPE_BIT 0x002 #define XRC_RIB_CTRLR_STATUS_FLAGS_NO_IR_PROGRAMMED_BIT 0x001 // Controller IRDB Status Load Status byte bit masks #define XRC_RIB_CTRLR_STATUS_LOAD_RESULT_BITS 0x0F0 // Target IRDB Status Flags byte bit masks #define XRC_RIB_TARGET_STATUS_FLAGS_AVR_CODE_PRESENT_BIT 0x010 #define XRC_RIB_TARGET_STATUS_FLAGS_TV_CODE_PRESENT_BIT 0x008 #define XRC_RIB_TARGET_STATUS_FLAGS_IRRF_DATABASE_BIT 0x004 #define XRC_RIB_TARGET_STATUS_FLAGS_NO_IR_PROGRAMMED_BIT 0x001 // Maximum size (in bytes) of the IR waveform data #define CONTROLMGR_MAX_IR_DATA_SIZE (80) // Enumeration for combinations of 5-Digit Code flags in the IR-RF Status Flags byte. typedef enum { FIVE_DIGIT_CODE_MODE_NONE, FIVE_DIGIT_CODE_MODE_TV_SET, FIVE_DIGIT_CODE_MODE_AVR_SET, FIVE_DIGIT_CODE_MODE_TVAVR_SET, FIVE_DIGIT_CODE_MODE_CLEAR } FiveDigitCodeMode; // Definitions used for key group decision making typedef enum { KEY_GROUP_SRC_CLEAR, KEY_GROUP_SRC_TV, KEY_GROUP_SRC_AVR, KEY_GROUP_SRC_TV_PWR_CROSS, // xxx_PWR_CROSS are only used for the DiscretePower group, KEY_GROUP_SRC_AVR_PWR_CROSS // to implement DiscretePower when only TogglePower is available. } KeyGroupSrc; class KeyGroupSrcInfo { public: KeyGroupSrc groupInputSelect; KeyGroupSrc groupVolume; // Includes VOL_UP and VOL_DOWN KeyGroupSrc groupMute; KeyGroupSrc groupTogglePower; KeyGroupSrc groupDiscretePower; // Includes Discrete Power ON and OFF KeyGroupSrcInfo() { groupInputSelect = groupVolume = groupMute = groupTogglePower = groupDiscretePower = KEY_GROUP_SRC_CLEAR; } }; // Classes to aid in key group decisions (for the original 7 IRRFDB slots, especially the legacy power slots) class RFKeyFlags { public: bool input; bool vol_up; bool vol_dn; bool mute; bool pwr_toggle; bool pwr_on; bool pwr_off; RFKeyFlags() { input = vol_up = vol_dn = mute = pwr_toggle = pwr_on = pwr_off = false; } void setKey(int rfKey) { switch (rfKey) { case MSO_RFKEY_INPUT_SELECT: input = true; break; case MSO_RFKEY_VOL_PLUS: vol_up = true; break; case MSO_RFKEY_VOL_MINUS: vol_dn = true; break; case MSO_RFKEY_MUTE: mute = true; break; case MSO_RFKEY_PWR_TOGGLE: pwr_toggle = true; break; case MSO_RFKEY_PWR_OFF: pwr_off = true; break; case MSO_RFKEY_PWR_ON: pwr_on = true; break; } } void clearKey(int rfKey) { switch (rfKey) { case MSO_RFKEY_INPUT_SELECT: input = false; break; case MSO_RFKEY_VOL_PLUS: vol_up = false; break; case MSO_RFKEY_VOL_MINUS: vol_dn = false; break; case MSO_RFKEY_MUTE: mute = false; break; case MSO_RFKEY_PWR_TOGGLE: pwr_toggle = false; break; case MSO_RFKEY_PWR_OFF: pwr_off = false; break; case MSO_RFKEY_PWR_ON: pwr_on = false; break; } } bool isSet(int rfKey) { bool isset = false; switch (rfKey) { case MSO_RFKEY_INPUT_SELECT: isset = input; break; case MSO_RFKEY_VOL_PLUS: isset = vol_up; break; case MSO_RFKEY_VOL_MINUS: isset = vol_dn; break; case MSO_RFKEY_MUTE: isset = mute; break; case MSO_RFKEY_PWR_TOGGLE: isset = pwr_toggle; break; case MSO_RFKEY_PWR_OFF: isset = pwr_off; break; case MSO_RFKEY_PWR_ON: isset = pwr_on; break; } return isset; } }; class KeyPresenceFlags { public: RFKeyFlags tv; RFKeyFlags avr; }; // Class used for evaluating the target controller's IR-RF Database read/load progress class IRRFDBCtrlrLoadProgress { public: bool slot_INPUT_SELECT; bool slot_VOL_PLUS; bool slot_VOL_MINUS; bool slot_MUTE; bool slot_TV_PWR_TOGGLE; bool slot_TV_PWR_ON; bool slot_TV_PWR_OFF; bool slot_AVR_PWR_TOGGLE; bool slot_AVR_PWR_OFF; bool slot_AVR_PWR_ON; bool slot_PWR_TOGGLE; bool slot_PWR_OFF; bool slot_PWR_ON; IRRFDBCtrlrLoadProgress() { clear(); } void clear() { slot_INPUT_SELECT = slot_VOL_PLUS = slot_VOL_MINUS = slot_MUTE = slot_TV_PWR_TOGGLE = slot_TV_PWR_ON = slot_TV_PWR_OFF = slot_AVR_PWR_TOGGLE = slot_AVR_PWR_OFF = slot_AVR_PWR_ON = slot_PWR_TOGGLE = slot_PWR_OFF = slot_PWR_ON = false; } void setSlotRead(int rfKey, bool state) { switch (rfKey) { case MSO_RFKEY_INPUT_SELECT: slot_INPUT_SELECT = state; break; case MSO_RFKEY_VOL_PLUS: slot_VOL_PLUS = state; break; case MSO_RFKEY_VOL_MINUS: slot_VOL_MINUS = state; break; case MSO_RFKEY_MUTE: slot_MUTE = state; break; case XRC_RFKEY_TV_PWR_TOGGLE: slot_TV_PWR_TOGGLE = state; break; case XRC_RFKEY_TV_PWR_ON: slot_TV_PWR_ON = state; break; case XRC_RFKEY_TV_PWR_OFF: slot_TV_PWR_OFF = state; break; case XRC_RFKEY_AVR_PWR_TOGGLE: slot_AVR_PWR_TOGGLE = state; break; case XRC_RFKEY_AVR_PWR_OFF: slot_AVR_PWR_OFF = state; break; case XRC_RFKEY_AVR_PWR_ON: slot_AVR_PWR_ON = state; break; case MSO_RFKEY_PWR_TOGGLE: slot_PWR_TOGGLE = state; break; case MSO_RFKEY_PWR_OFF: slot_PWR_OFF = state; break; case MSO_RFKEY_PWR_ON: slot_PWR_ON = state; break; } } bool getSlotRead(int rfKey) { bool state = false; switch (rfKey) { case MSO_RFKEY_INPUT_SELECT: state = slot_INPUT_SELECT; break; case MSO_RFKEY_VOL_PLUS: state = slot_VOL_PLUS; break; case MSO_RFKEY_VOL_MINUS: state = slot_VOL_MINUS; break; case MSO_RFKEY_MUTE: state = slot_MUTE; break; case XRC_RFKEY_TV_PWR_TOGGLE: state = slot_TV_PWR_TOGGLE; break; case XRC_RFKEY_TV_PWR_ON: state = slot_TV_PWR_ON; break; case XRC_RFKEY_TV_PWR_OFF: state = slot_TV_PWR_OFF; break; case XRC_RFKEY_AVR_PWR_TOGGLE: state = slot_AVR_PWR_TOGGLE; break; case XRC_RFKEY_AVR_PWR_OFF: state = slot_AVR_PWR_OFF; break; case XRC_RFKEY_AVR_PWR_ON: state = slot_AVR_PWR_ON; break; case MSO_RFKEY_PWR_TOGGLE: state = slot_PWR_TOGGLE; break; case MSO_RFKEY_PWR_OFF: state = slot_PWR_OFF; break; case MSO_RFKEY_PWR_ON: state = slot_PWR_ON; break; } return state; } }; // Class to represent a single instance of a keyActionMap class keyActionMap { public: int keyName; int rfKeyCode; byte_vector_t tvIRData; byte_vector_t avrIRData; }; namespace WPEFramework { namespace Plugin { // Helper class for the RemoteActionMapping plugin - contains details of IARM communication with ControlMgr class RemoteActionMappingHelper { public: int getLastUsedDeviceID(std::string& remoteType, bool& bFiveDigitCodeSet, bool& bFiveDigitCodeSupported); bool getControllerByID(int deviceID, std::string& remoteType, bool& pbFiveDigitCodeSet, bool& pbFiveDigitCodeSupported); bool setKeyActionMap(int deviceID, int keymapType, keyActionMap& actionMap, const KeyGroupSrcInfo& srcInfo); bool getKeyActionMap(int deviceID, int keymapType, keyActionMap& actionMap); // In this case, actionMap is an in/out parameter bool clearKeyActionMap(int deviceID, int keymapType, int keyName); bool setFiveDigitCode(int deviceID, int tvFiveDigitCode, int avrFiveDigitCode); bool setIRDBDownloadFlag(int deviceID, bool bDownload); bool setFiveDigitCodeFlags(int deviceID, int mode); bool cancelCodeDownload(int deviceID); bool getControllerLoadStatus(int deviceID, unsigned& tvLoadStatus, unsigned& avrLoadStatus); int lookupRFKey(int keyName); int lookupKeyname(int rfKey); bool setDevicePower(int deviceID, int keymapType, keyActionMap& actionMap); bool clearDevicePower(int deviceID, int keymapType, int rfKeyCode); private: ctrlm_network_id_t getRf4ceNetworkID(void); bool getRf4ceBindRemotes(rf4ceBindRemotes_t* bindRemotes); bool setRIBDevicePower(int deviceID, int keymapType, int rfKeyCode, byte_vector_t& irData); bool clearRIBDevicePower(int deviceID, int keymapType, int rfKeyCode); }; } // namespace Plugin } // namespace WPEFramework
39.242812
141
0.682325
[ "vector" ]
644dabcaf9d61dc9d953763a30f86b50d4559ac0
535
c
C
src/lib/system.c
slash-lang/slash
5e773f6f4259376f13a30a5bc546ed162dd6daff
[ "MIT" ]
60
2015-02-01T17:52:49.000Z
2022-02-21T21:34:29.000Z
src/lib/system.c
slash-lang/slash
5e773f6f4259376f13a30a5bc546ed162dd6daff
[ "MIT" ]
2
2015-03-16T22:25:21.000Z
2015-04-26T09:12:56.000Z
src/lib/system.c
slash-lang/slash
5e773f6f4259376f13a30a5bc546ed162dd6daff
[ "MIT" ]
8
2015-06-14T21:07:46.000Z
2021-06-06T09:26:17.000Z
#include <slash/value.h> #include <slash/vm.h> #include <slash/class.h> #include <slash/string.h> #include <slash/object.h> #include <slash/lib/bignum.h> #include <stdlib.h> #include <time.h> static SLVAL object_exit(sl_vm_t* vm, SLVAL self, size_t argc, SLVAL* argv) { SLVAL exit_code = sl_make_int(vm, 0); if(argc) { exit_code = argv[0]; } sl_exit(vm, exit_code); return self; /* never reached */ } void sl_init_system(sl_vm_t* vm) { sl_define_method(vm, vm->lib.Object, "exit", -1, object_exit); }
20.576923
66
0.665421
[ "object" ]
64529fbd59bdf97608b2624dbec1926867c34d34
8,630
h
C
3dEngine/Shader.h
ForNextSoftwareDevelopment/3dEngine
7ebd5fb5ef91c08e98dbacaaa335ac1911f1d3e1
[ "Unlicense" ]
null
null
null
3dEngine/Shader.h
ForNextSoftwareDevelopment/3dEngine
7ebd5fb5ef91c08e98dbacaaa335ac1911f1d3e1
[ "Unlicense" ]
null
null
null
3dEngine/Shader.h
ForNextSoftwareDevelopment/3dEngine
7ebd5fb5ef91c08e98dbacaaa335ac1911f1d3e1
[ "Unlicense" ]
null
null
null
#pragma once #include <windows.h> #include "Mesh.h" #include "Objects.h" #include "VecMat.h" #define SHADOWMAP_WIDTH 1024 #define SHADOWMAP_HEIGHT 1024 // Ambient / Diffuse light struct Light { GLfloat r; GLfloat g; GLfloat b; GLfloat a; }; // Drawing modes for mesh typedef unsigned int RenderMode; #define RM_VERTICES 0x0 #define RM_EDGES 0x1 #define RM_FACES 0x2 // Near- and farplane positions (default) #define NEARPLANEPOS 2.0f #define FARPLANEPOS 800.0f // Left, right, top and bottom of nearplane #define NPLEFT -1.0f #define NPRIGHT 1.0f #define NPBOTTOM -1.0f #define NPTOP 1.0f // Default angle offset for left and right window (eye) on extended display #define DEFAULTOFFSETANGLE 20 class Shader { private: // Objects for rendering / use as material etc. Objects *pObjects; // Render mode (vertices, edges or faces) RenderMode render_mode; // Show textures bool show_textures; // Show normalmap bool show_normalmap; // Test bool test; // Filter textures bool filter_textures; // Repeat textures bool repeat_textures; // Show outlining bool show_outlining; // Show axis bool show_axis; // Screen (window) scale factor GLint screen_width; GLint screen_height; // Size of the vertices drawn GLshort vertex_size; // Mesh angles GLfloat angle_x, angle_y, angle_z; // Mesh angles VecMat::Mat4 angle_matrix; // Mesh position GLfloat pos_x, pos_y, pos_z; // Mesh position VecMat::Mat4 position_matrix; // Mesh offset (angles and translation) VecMat::Mat4 offset_matrix; // Ambient color Light ambient_light; // Diffuse color Light diffuse_light; // Diffuse light position GLfloat diff_pos_x, diff_pos_y, diff_pos_z; // Reflectivity factor GLint reflectivity; // Position of Near Plane GLfloat pos_np; // Position of Far Plane GLfloat pos_fp; // Vertex shader name GLuint vertex_shader; // Fragment shader name GLuint fragment_shader; // Vertex shadow shader handler GLuint vertex_shadow_shader; // Fragment shadow shader handler GLuint fragment_shadow_shader; // Vertex array object GLuint vao[MAX_NUM_MESHES]; // Names (int) of the vertex buffers GLuint vertex_buffer[MAX_NUM_MESHES]; // Names (int) of the normal buffers GLuint normal_buffer[MAX_NUM_MESHES]; // Names (int) of the index buffers GLuint index_buffer[MAX_NUM_MESHES]; // Names (int) of the texture buffers GLuint texture_color_buffer[MAX_NUM_MATERIALS]; // Names (int) of the texture normal buffers GLuint texture_normal_buffer[MAX_NUM_MATERIALS]; // Name (int) of the framebuffer used for shadow mapping GLuint frame_buffer; // Name (int) of the texturebuffer used for shadow mapping GLuint texture_shadow_buffer; // Matrices for object path and projection GLuint path_matrix_location; GLuint path_shadow_matrix_location; GLuint proj_matrix_location; GLuint proj_shadow_matrix_location; GLuint path_lightspace_matrix_location; // Mesh texture GLuint texture_color_data_location; GLuint texture_normal_data_location; GLuint texture_position_location; GLuint texture_color_enable_location; GLuint texture_normal_enable_location; GLuint texture_scale_location; GLuint texture_offset_location; // Screen size scale GLuint screen_scale_location; // Ambulant light GLuint ambient_light_location; // Diffuse light GLuint diffuse_position_location; GLuint diffuse_light_location; // Material properties GLuint ambient_albedo_location; GLuint diffuse_albedo_location; GLuint specular_albedo_location; // Reflectivity factor GLuint reflectivity_location; // Illumination model GLuint illumination_location; // Vertices GLuint vertex_position_location; // Vertex normals GLuint normal_position_location; // (Bi-)Tangents GLuint tangent_position_location; GLuint bitangent_position_location; // Test in shader GLuint test_location; // Vertices in shadow shader GLuint vertex_shadow_position_location; // Texture shadow map data location GLuint texture_shadow_data_location; // Shader program name GLuint program; // Shadow shader program name GLuint program_shadow; // Vertex shader static const char *vs_source[]; // Fragment shader static const char *fs_source[]; // Vertex shadow shader static const char *vs_shadow_source[]; // Fragment shadow shader static const char *fs_shadow_source[]; // Create and compile the vertex and fragment shader void CreateShaders (void); // Create programs for OpenGL void CreatePrograms (void); // Create and set buffers (vertex, index) void CreateBuffers (void); // Create and set framebuffer (shadows) void CreateFrameBuffer(void); // Create and set textures void CreateTextures (void); // Draw all objects void DrawObjects(bool shadowMap); public: // Constructor Shader (Objects *pObjects); // Destructor ~Shader (void); // Render mesh object void Render (GLint screen_width, GLint screen_height); // Set color for ambient light void SetAmbientLight (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); // Set color for diffuse light void SetDiffuseLight (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); // Set position for diffuse light (and Bulb) void SetDiffusePosition (GLfloat x, GLfloat y, GLfloat z); // Set view angle void SetViewAngle (GLfloat angle_x, GLfloat angle_y, GLfloat angle_z); // Set view angle (quaternion) void SetViewAngle (VecMat::Mat4 rotate); // Change view angle void ChangeViewAngle (GLfloat delta_angle_x, GLfloat delta_angle_y, GLfloat delta_angle_z); // Set view position void SetViewPosition (GLfloat x, GLfloat y, GLfloat z); // Change view position void ChangeViewPosition (GLfloat delta_pos_x, GLfloat delta_pos_y, GLfloat delta_pos_z); // Get view position with provided delta void GetDeltaViewPosition(GLfloat& x, GLfloat& y, GLfloat& z, GLfloat delta_pos_x, GLfloat delta_pos_y, GLfloat delta_pos_z); // Set offset void SetOffset (GLfloat pos_x, GLfloat pos_y, GLfloat pos_z, GLfloat angle_x, GLfloat angle_y, GLfloat angle_z); // Set near plane vision (perspective) void SetNearPlanePosition (GLfloat pos_np); // Set position of far plane void SetFarPlanePosition (GLfloat pos_fp); // Set rendermode (vertices, edges or faces) void SetRenderMode (RenderMode render_mode); // Set show textures void ShowTextures (bool show); // Set show normalmap void ShowNormalMap (bool show); // Set test conditions in shader void SetTest (bool test); // Set filter textures void FilterTextures (bool filter); // Set repeat textures void RepeatTextures (bool repeat); // Set show oulining void ShowOutlining (bool show); // Set show axis void ShowAxis(bool show); // Set vertex size void SetVertexSize (GLint vsize); // Set screen size void SetScreenSize (GLint width, GLint height); // Get info (position, angle etc.) std::string GetInfo (void); };
27.138365
134
0.607184
[ "mesh", "render", "object", "model" ]
6455a43d7a0fadbda5ff04aff4a3e79e8724c0a1
10,822
c
C
netbsdsrc/sys/arch/pmax/pmax/cpu_cons.c
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
netbsdsrc/sys/arch/pmax/pmax/cpu_cons.c
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
netbsdsrc/sys/arch/pmax/pmax/cpu_cons.c
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* $NetBSD: cpu_cons.c,v 1.20 1997/10/19 10:25:52 jonathan Exp $ */ /* * Copyright (c) 1988 University of Utah. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Systems Programming Group of the University of Utah Computer * Science Department and Ralph Campbell. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: Utah Hdr: cons.c 1.1 90/07/09 * * @(#)cons.c 8.2 (Berkeley) 1/11/94 */ #include <sys/cdefs.h> /* RCS ID & Copyright macro defns */ __KERNEL_RCSID(0, "$NetBSD: cpu_cons.c,v 1.20 1997/10/19 10:25:52 jonathan Exp $"); #include <sys/param.h> #include <sys/device.h> #include <dev/cons.h> #include <sys/proc.h> #include <sys/systm.h> #include <sys/buf.h> #include <sys/ioctl.h> #include <sys/tty.h> #include <sys/file.h> #include <sys/conf.h> #include <pmax/stand/dec_prom.h> #include <pmax/pmax/kn01.h> #include <pmax/pmax/kn02.h> #include <pmax/pmax/kmin.h> #include <pmax/pmax/kn03.h> #include <pmax/pmax/asic.h> #include <pmax/pmax/turbochannel.h> #include <pmax/pmax/pmaxtype.h> #include <machine/pmioctl.h> #include <machine/fbio.h> #include <machine/fbvar.h> #include <pmax/dev/fbreg.h> #include <machine/autoconf.h> #include <pmax/dev/lk201var.h> #include <dev/tc/tcvar.h> #include "pm.h" #include "cfb.h" #include "mfb.h" #include "xcfb.h" #include "sfb.h" #include "dc_ds.h" #include "dc_ioasic.h" #include "dtop.h" #include "scc.h" #include "asc.h" #include "tc.h" #include "rasterconsole.h" #if (NDC_DS > 0) || (NDC_IOASIC > 0) #include <machine/dc7085cons.h> #include <pmax/dev/dc_cons.h> #include <pmax/dev/dc_ds_cons.h> #include <pmax/dev/dc_ioasic_cons.h> #endif #if NDTOP > 0 #include <pmax/dev/dtopvar.h> #endif #if NSCC > 0 #include <pmax/tc/sccvar.h> #endif #if NPM > 0 #include <pmax/dev/pmvar.h> #endif #if NXCFB > 0 #include <pmax/dev/xcfbvar.h> #endif static int romgetc __P ((dev_t)); static void romputc __P ((dev_t, int)); static void rompollc __P((dev_t, int)); extern int pmax_boardtype; /* Mother board type */ /* * Major device numbers for possible console devices. XXX */ #define DTOPDEV 15 #define DCDEV 16 #define SCCDEV 17 #define RCONSDEV 85 /* * Console I/O is redirected to the appropriate device, either a screen and * keyboard, a serial port, or the "virtual" console. */ extern struct consdev *cn_tab; /* Console I/O table... */ extern void rcons_vputc __P((dev_t, int)); /* XXX */ struct consdev cd = { (void (*)(struct consdev *))0, /* probe */ (void (*)(struct consdev *))0, /* init */ (int (*)(dev_t)) romgetc, /* getc */ (void (*)(dev_t, int))romputc, /* putc */ (void (*)(dev_t, int))rompollc, /* pollc */ makedev (0, 0), CN_DEAD, }; /* * Should be locals of consinit, but that's split in two until * new-style config is finished */ /* * Forward declarations */ void consinit __P((void)); void xconsinit __P((void)); extern struct tc_cpu_desc * cpu_tcdesc __P ((int cputype)); int kbd; int pending_remcons = 0; /* * Console initialization: called early on from main, * before vm init or startup. Do enough configuration * to choose and initialize a console. */ void consinit() { int crt; register char *oscon; int screen = 0; #ifdef RCONS_HACK extern void (*v_putc) __P ((dev_t, int)); #endif cn_tab = &cd; /* * First get the "osconsole" environment variable. */ oscon = (*callv->_getenv)("osconsole"); crt = kbd = -1; if (oscon && *oscon >= '0' && *oscon <= '9') { kbd = *oscon - '0'; /*cn_tab.cn_pri = CN_DEAD;*/ screen = 0; while (*++oscon) { if (*oscon == ',') /*cn_tab.cn_pri = CN_INTERNAL;*/ screen = 1; else if (screen && *oscon >= '0' && *oscon <= '9') { crt = kbd; kbd = *oscon - '0'; break; } } } /* * We can't do anything until auto-configuration * has run, and that requires kmalloc(), which * hasn't been initialized yet. Just keep using * whatever the PROM vector gave us. */ #if NRASTERCONSOLE > 0 if (pmax_boardtype == DS_PMAX && kbd == 1) screen = 1; /* * The boot program uses PMAX ROM entrypoints so the ROM sets * osconsole to '1' like the PMAX. */ if (pmax_boardtype == DS_3MAX && crt == -1 && kbd == 1) { /* Try to use pmax onboard framebuffer */ screen = 1; crt = 0; kbd = 7; } /* * First try the keyboard/crt cases then fall through to the * remote serial lines. */ if (screen) { switch (pmax_boardtype) { case DS_PMAX: #if NDC_DS > 0 && NPM > 0 if (pminit(0, 0, 1)) { cd.cn_pri = CN_INTERNAL; cd.cn_dev = makedev(DCDEV, DCKBD_PORT); cd.cn_getc = LKgetc; lk_divert(dcGetc, makedev(DCDEV, DCKBD_PORT)); cd.cn_putc = rcons_vputc; /*XXX*/ return; } #endif /* NDC_DS and NPM */ goto remcons; case DS_MAXINE: #if NDTOP > 0 if (kbd == 3) { cd.cn_dev = makedev(DTOPDEV, 0); cd.cn_getc = dtopKBDGetc; } else #endif /* NDTOP */ goto remcons; #if NXCFB > 0 if (crt == 3 && xcfbinit(NULL, NULL, 0, 0)) { cd.cn_pri = CN_INTERNAL; cd.cn_putc = rcons_vputc; /*XXX*/ return; } #endif /* XCFB */ break; case DS_3MAX: #if NDC_IOASIC > 0 if (kbd == 7) { cd.cn_dev = makedev(DCDEV, DCKBD_PORT); cd.cn_getc = LKgetc; lk_divert(dcGetc, makedev(DCDEV, DCKBD_PORT)); } else #endif /* NDC_IOASIC */ goto remcons; break; case DS_3MIN: case DS_3MAXPLUS: #if NSCC > 0 if (kbd == 3) { /*cd.cn_dev = makedev (RCONSDEV, 0);*/ cd.cn_dev = makedev(SCCDEV, SCCKBD_PORT); lk_divert(sccGetc, makedev(SCCDEV, SCCKBD_PORT)); cd.cn_getc = LKgetc; } else #endif /* NSCC */ goto remcons; break; default: goto remcons; }; /* * Check for a suitable turbochannel frame buffer. */ #if NTC>0 if (tc_findconsole(crt)) { cd.cn_pri = CN_NORMAL; #ifdef RCONS_HACK /* FIXME */ cd.cn_putc = v_putc; cd.cn_dev = makedev (RCONSDEV, 0); #endif /* RCONS_HACK */ cd.cn_putc = rcons_vputc; /*XXX*/ return; } else #endif { printf("No supported console device in slot %d. ", crt); printf("Switching over to serial console!\n"); } } remcons: #endif /* NRASTERCONSOLE > 0 */ /* * Configure a serial port as a remote console. */ switch (pmax_boardtype) { case DS_PMAX: #if NDC_DS > 0 if (kbd == 4) cd.cn_dev = makedev(DCDEV, DCCOMM_PORT); else cd.cn_dev = makedev(DCDEV, DCPRINTER_PORT); dc_ds_consinit(cd.cn_dev); return; #endif /* NDC_DS */ break; case DS_3MAX: #if (NDC_IOASIC > 0) cd.cn_dev = makedev(DCDEV, DCPRINTER_PORT); dc_ioasic_consinit(cd.cn_dev); return; #endif /* NDC_IOASIC */ break; } /* * XXX * scc serial drivers need to be rewritten to handle init this early. * Defer switching to non-PROM driver until after serial device * is configured normally. */ pending_remcons = 1; printf("Using PROM serial output until serial drivers initialized\n"); /* We never changed output; go back to using PROM input */ cd.cn_dev = makedev (0, 0); cd.cn_getc = /*(int (*)(dev_t)) */ romgetc; } /* * Configure a serial port as a remote console. * Called by configure() to switch from PROM I/O when the serial * device-driver cannot be set up as a serial console until * autoconfiguration is done. (i.e., only needed for scc serial driver.) */ void xconsinit() { if (!pending_remcons) return; pending_remcons = 0; switch (pmax_boardtype) { case DS_3MIN: case DS_3MAXPLUS: #if NSCC > 0 cd.cn_dev = makedev(SCCDEV, SCCCOMM3_PORT); cd.cn_getc = sccGetc; cd.cn_putc = sccPutc; cd.cn_pri = CN_REMOTE; #endif /* NSCC */ break; case DS_MAXINE: #if NSCC > 0 cd.cn_dev = makedev(SCCDEV, SCCCOMM2_PORT); cd.cn_getc = sccGetc; cd.cn_putc = sccPutc; cd.cn_pri = CN_REMOTE; #endif /* NSCC */ break; }; if (cd.cn_dev == NODEV) printf("Can't configure console!\n"); } /* * Get character from ROM console. */ static int romgetc(dev) dev_t dev; { int s = splhigh (); int chr; chr = (*callv->_getchar)(); splx (s); return chr; } /* * Print a character on ROM console. */ static void romputc (dev, c) dev_t dev; register int c; { int s; s = splhigh(); (*callv->_printf)("%c", c); splx(s); } static void rompollc (dev, c) dev_t dev; register int c; { return; } #ifdef notanymore /* * select() on a possibly-redirected console. */ extern struct tty *constty; /* virtual console output device */ extern struct consdev *cn_tab; /* physical console device info */ extern struct vnode *cn_devvp; /* vnode for underlying device. */ /*ARGSUSED*/ int pmax_cnselect(dev, rw, p) dev_t dev; int rw; struct proc *p; { /* * Redirect the ioctl, if that's appropriate. * I don't want to think of the possible side effects * of console redirection here. */ if (constty != NULL && (cn_tab == NULL || cn_tab->cn_pri != CN_REMOTE)) dev = constty->t_dev; else if (cn_tab == NULL) return ENXIO; else dev = cn_tab->cn_dev; #ifdef RCONS if (cn_tab -> cn_dev == makedev (85, 0)) return rconsselect (cn_tab -> cn_dev, rw, p); #endif return (ttselect(cn_tab->cn_dev, rw, p)); } #endif /* notanymore */
22.976645
83
0.666235
[ "vector" ]
64574ef68e174c93bd1c77c8863fb398b450b69d
7,007
c
C
HW8/HW8.X/main.c
YaelBenShalom/Advanced-Mechatronics
cb19e6d0500b68b6ae2a23bf41d1b47ce8f93adb
[ "MIT" ]
null
null
null
HW8/HW8.X/main.c
YaelBenShalom/Advanced-Mechatronics
cb19e6d0500b68b6ae2a23bf41d1b47ce8f93adb
[ "MIT" ]
null
null
null
HW8/HW8.X/main.c
YaelBenShalom/Advanced-Mechatronics
cb19e6d0500b68b6ae2a23bf41d1b47ce8f93adb
[ "MIT" ]
null
null
null
#include "i2c_master_noint.h" #include <stdio.h> #include <sys/attribs.h> // __ISR macro #include <xc.h> // processor SFR definitions // DEVCFG0 #pragma config DEBUG = OFF // disable debugging #pragma config JTAGEN = OFF // disable jtag #pragma config ICESEL = ICS_PGx1 // use PGED1 and PGEC1 #pragma config PWP = OFF // disable flash write protect #pragma config BWP = OFF // disable boot write protect #pragma config CP = OFF // disable code protect // DEVCFG1 #pragma config FNOSC = FRCPLL // use internal oscillator with pll #pragma config FSOSCEN = OFF // disable secondary oscillator #pragma config IESO = OFF // disable switching clocks #pragma config POSCMOD = OFF // RC mode #pragma config OSCIOFNC = OFF // disable clock output #pragma config FPBDIV = \ DIV_1 // divide sysclk freq by 1 for peripheral bus clock #pragma config FCKSM = CSDCMD // disable clock switch and FSCM #pragma config WDTPS = PS1048576 // use largest wdt #pragma config WINDIS = OFF // use non-window mode wdt #pragma config FWDTEN = OFF // wdt disabled #pragma config FWDTWINSZ = WINSZ_25 // wdt window at 25% // DEVCFG2 - get the sysclk clock to 48MHz from the 8MHz crystal #pragma config FPLLIDIV = DIV_2 // divide input clock to be in range 4-5MHz #pragma config FPLLMUL = MUL_24 // multiply clock after FPLLIDIV #pragma config FPLLODIV = DIV_2 // divide clock after FPLLMUL to get 48MHz // DEVCFG3 #pragma config USERID = 0 // some 16bit userid, doesn't matter what #pragma config PMDL1WAY = OFF // allow multiple reconfigurations #pragma config IOL1WAY = OFF // allow multiple reconfigurations void readUART1(char *string, int maxLength); void writeUART1(const char *string); void writePin(unsigned char address, unsigned char reg, unsigned char value); unsigned char readPin(unsigned char address, unsigned char address2, unsigned char reg, int ack); void initSPI(); int main() { __builtin_disable_interrupts(); // disable interrupts while initializing // things // set the CP0 CONFIG register to indicate that kseg0 is cacheable (0x3) __builtin_mtc0(_CP0_CONFIG, _CP0_CONFIG_SELECT, 0xa4210583); // 0 data RAM access wait states BMXCONbits.BMXWSDRM = 0x0; // enable multi vector interrupts INTCONbits.MVEC = 0x1; // disable JTAG to get pins back DDPCONbits.JTAGEN = 0; // do your TRIS and LAT commands here TRISBbits.TRISB4 = 1; // B4 is input TRISAbits.TRISA4 = 0; // A4 is output LATAbits.LATA4 = 0; // A4 is low initSPI(); U1RXRbits.U1RXR = 0b0001; // U1RX is B6 RPB7Rbits.RPB7R = 0b0001; // U1TX is B7 // turn on UART3 without an interrupt U1MODEbits.BRGH = 0; // set baud to NU32_DESIRED_BAUD U1BRG = ((48000000 / 115200) / 16) - 1; // 8 bit, no parity bit, and 1 stop bit (8N1 setup) U1MODEbits.PDSEL = 0; U1MODEbits.STSEL = 0; // configure TX & RX pins as output & input pins U1STAbits.UTXEN = 1; U1STAbits.URXEN = 1; // enable the uart U1MODEbits.ON = 1; __builtin_enable_interrupts(); // Initialize I2C i2c_master_setup(); // set all A pins to output writePin(0x40, 0x00, 0x00); i2c_master_start(); i2c_master_send(0b01000000); // send address + write bit 0b01000000 i2c_master_send(0x00); // command register address for IODIRA i2c_master_send(0x00); // set all A pins to output i2c_master_stop(); writePin(0x40, 0x14, 0xFF); // turn on pin GPA7 // set all B pins to input writePin(0x40, 0x01, 0xFF); i2c_master_start(); i2c_master_send(0x40); // send address + write bit i2c_master_send(0x01); // command register address for IODIRB i2c_master_send(0xFF); // set all A pins to output i2c_master_stop(); unsigned char value; while (1) { _CP0_SET_COUNT(0); // reset core timer LATAINV = 0b10000; // toggle pin A4 while (_CP0_GET_COUNT() < 6000000) { ; } // 0.25s delay value = readPin(0b01000000, 0b01000001, 0x13, 1); value &= 1; char m[100]; sprintf(m, "%d\r\n", value); writeUART1(m); // call on writeUART1 to send PIC a message if (value == 0) { writePin(0x40, 0x14, 0xFF); // turn on pin GPA7 } if (value == 1) { writePin(0x40, 0x14, 0x00); // turn off pin GPA7 } } } // Read from UART1 // block other functions until you get a '\r' or '\n' // send the pointer to your char array and the number of elements in the array void readUART1(char *message, int maxLength) { char data = 0; int complete = 0, num_bytes = 0; // loop until you get a '\r' or '\n' while (!complete) { if (U1STAbits.URXDA) { // if data is available data = U1RXREG; // read the data if ((data == '\n') || (data == '\r')) { complete = 1; } else { message[num_bytes] = data; ++num_bytes; // roll over if the array is too small if (num_bytes >= maxLength) { num_bytes = 0; } } } } // end the string message[num_bytes] = '\0'; } // Write a character array using UART3 void writeUART1(const char *string) { while (*string != '\0') { while (U1STAbits.UTXBF) { ; // wait until tx buffer isn't full } U1TXREG = *string; ++string; } } void writePin(unsigned char address, unsigned char reg, unsigned char value) { i2c_master_start(); i2c_master_send(address); // send address + write bit i2c_master_send(reg); // send command register address i2c_master_send(value); // send value i2c_master_stop(); } unsigned char readPin(unsigned char address, unsigned char address2, unsigned char reg, int ack) { unsigned char value; i2c_master_start(); i2c_master_send(address); // send address + read bit i2c_master_send(reg); // send command register address i2c_master_restart(); // send a restart i2c_master_send(address2); value = i2c_master_recv(); // receive byte from device char m[100]; sprintf(m, "read to here\r\n"); writeUART1(m); // call on writeUART1 to send PIC a message i2c_master_ack(ack); // send acknowledge bit i2c_master_stop(); return value; } void initSPI() { // Pin B14 has to be SCK1 // Turn off analog pins ANSELA = 0; // 1 for analog // Make A0 an output pin for CS TRISAbits.TRISA0 = 0; LATAbits.LATA0 = 1; // Make A1 SDO1 RPA1Rbits.RPA1R = 0b0011; // Make B5 SDI1 SDI1Rbits.SDI1R = 0b0001; // setup SPI1 SPI1CON = 0; // turn off the SPI module and reset it SPI1BUF; // clear the rx buffer by reading from it SPI1BRG = 1000; // 1000 for 12 kHz, 1 for 12 MHz; // baud rate to 10 MHz // (SPI4BRG = (4000000/(2*desired)-1)) SPI1STATbits.SPIROV = 0; // clear the overflow bit SPI1CONbits.CKE = 1; // data changes when clock goes from hi to lo (bc CKP is 0) SPI1CONbits.MSTEN = 1; // master operation SPI1CONbits.ON = 1; // turn on SPI }
32.439815
80
0.653632
[ "vector" ]
6457c0deaede39a7a442489b014a01fa60b5994c
6,856
h
C
include/pcl/PhaseMatrices.h
kkretzschmar/PCL
6354627260482afcb278a3f3a2bf30c26210d4fa
[ "JasPer-2.0" ]
null
null
null
include/pcl/PhaseMatrices.h
kkretzschmar/PCL
6354627260482afcb278a3f3a2bf30c26210d4fa
[ "JasPer-2.0" ]
null
null
null
include/pcl/PhaseMatrices.h
kkretzschmar/PCL
6354627260482afcb278a3f3a2bf30c26210d4fa
[ "JasPer-2.0" ]
null
null
null
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 02.01.11.0938 // ---------------------------------------------------------------------------- // pcl/PhaseMatrices.h - Released 2019-01-21T12:06:07Z // ---------------------------------------------------------------------------- // This file is part of the PixInsight Class Library (PCL). // PCL is a multiplatform C++ framework for development of PixInsight modules. // // Copyright (c) 2003-2019 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (http://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ---------------------------------------------------------------------------- #ifndef __PCL_PhaseMatrices_h #define __PCL_PhaseMatrices_h /// \file pcl/PhaseMatrices.h #include <pcl/Defs.h> #include <pcl/Image.h> namespace pcl { // ---------------------------------------------------------------------------- /*! * Calculation of the phase correlation matrix (PCM). * * \param[out] R The resulting PCM as a single-channel complex image with the * same dimensions of the source images \a A and \a B. * * \param A A single-channel complex image with the discrete Fourier * transform of the reference image. * * \param B A single-channel complex image with the discrete Fourier * transform of the working image. * * Both source images \a A and \a B must be nonempty and have the same * dimensions. If the result image \a R does not have the same geometry as the * source images, it is reallocated as necessary. * * \note Increments the status monitoring object of the result image \a R by * its area in square pixels. * * \ingroup phase_matrices */ template <class P1, class P2> inline void PCL_FUNC PhaseCorrelationMatrix( GenericImage<P1>& R, const GenericImage<P2>& A, const GenericImage<P2>& B ) { const typename GenericImage<P2>::sample::component tiny( 1.0e-20 ); size_type N = A.NumberOfPixels(); if ( A.IsEmpty() || B.NumberOfPixels() != N ) throw Error( "Invalid image geometry in PhaseCorrelationMatrix()" ); if ( R.NumberOfPixels() != N ) R.AllocateData( A.Width(), B.Width() ); if ( R.Status().IsInitializationEnabled() ) R.Status().Initialize( "Phase correlation matrix", N ); const typename GenericImage<P2>::sample* a = *A; const typename GenericImage<P2>::sample* b = *B; typename GenericImage<P1>::sample* r = *R; typename GenericImage<P1>::sample* rN = r + N; for ( ; r < rN; ++r, ++a, ++b, ++R.Status() ) { typename GenericImage<P2>::sample num = *a * ~*b; *r = P1::ToSample( num/Max( tiny, Abs( num ) ) ); } } /*! * Calculation of the cross power spectrum matrix (CPSM). * * \param[out] R The resulting CPSM as a single-channel complex image with the * same dimensions of the source images \a A and \a B. * * \param A A single-channel complex image with the discrete Fourier * transform of the reference image. * * \param B A single-channel complex image with the discrete Fourier * transform of the working image. * * Both source images \a A and \a B must be nonempty and have the same * dimensions. If the result image \a R does not have the same geometry as the * source images, it is reallocated as necessary. * * \note Increments the status monitoring object of the result image \a R by * its area in square pixels. * * \ingroup phase_matrices */ template <class P1, class P2> inline void PCL_FUNC CrossPowerSpectrumMatrix( GenericImage<P1>& R, const GenericImage<P2>& A, const GenericImage<P2>& B ) { const typename GenericImage<P2>::sample::component tiny( 1.0e-20 ); size_type N = A.NumberOfPixels(); if ( A.IsEmpty() || B.NumberOfPixels() != N ) throw Error( "Invalid image geometry in CrossPowerSpectrumMatrix()" ); if ( R.NumberOfPixels() != N ) R.AllocateData( A.Width(), B.Width() ); if ( R.Status().IsInitializationEnabled() ) R.Status().Initialize( "Cross power spectrum matrix", N ); const typename GenericImage<P2>::sample* a = *A; const typename GenericImage<P2>::sample* b = *B; typename GenericImage<P1>::sample* r = *R; typename GenericImage<P1>::sample* rN = r + N; for ( ; r < rN; ++r, ++a, ++b, ++R.Status() ) *r = P1::ToSample( (*b * ~*a)/Max( tiny, Abs( *a ) * Abs( *b ) ) ); } // ---------------------------------------------------------------------------- } // pcl #endif // __PCL_PhaseMatrices_h // ---------------------------------------------------------------------------- // EOF pcl/PhaseMatrices.h - Released 2019-01-21T12:06:07Z
40.568047
115
0.638273
[ "geometry", "object", "transform" ]
ea810e9cefbd76bf1e6ef0f65a476d798b1cf0dc
13,486
c
C
subversion/libsvn_delta/xdelta.c
tux-mind/platform_external_subversion
e3e715b637b0b7c6a6a02316f3be48f2c1d5181c
[ "Apache-2.0" ]
2
2019-10-31T18:33:15.000Z
2021-09-19T20:04:03.000Z
subversion/libsvn_delta/xdelta.c
wbond/subversion
018aaa1933687f28bbfdcad9b7b988fd7435afcd
[ "Apache-2.0" ]
null
null
null
subversion/libsvn_delta/xdelta.c
wbond/subversion
018aaa1933687f28bbfdcad9b7b988fd7435afcd
[ "Apache-2.0" ]
2
2019-10-31T18:33:29.000Z
2020-02-15T03:57:13.000Z
/* * xdelta.c: xdelta generator. * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== */ #include <assert.h> #include <apr_general.h> /* for APR_INLINE */ #include <apr_hash.h> #include "svn_delta.h" #include "delta.h" #include "private/svn_adler32.h" /* This is pseudo-adler32. It is adler32 without the prime modulus. The idea is borrowed from monotone, and is a translation of the C++ code. Graydon Hoare, the author of the original code, gave his explicit permission to use it under these terms at 8:02pm on Friday, February 11th, 2005. */ /* Size of the blocks we compute checksums for. This was chosen out of thin air. Monotone used 64, xdelta1 used 64, rsync uses 128. However, later optimizations assume it to be 256 or less. */ #define MATCH_BLOCKSIZE 64 /* Feed C_IN into the adler32 checksum and remove C_OUT at the same time. * This function may (and will) only be called for characters that are * MATCH_BLOCKSIZE positions apart. * * Please note that the lower 16 bits cannot overflow in neither direction. * Therefore, we don't need to split the value into separate values for * sum(char) and sum(sum(char)). */ static APR_INLINE apr_uint32_t adler32_replace(apr_uint32_t adler32, const char c_out, const char c_in) { adler32 -= (MATCH_BLOCKSIZE * 0x10000u * ((unsigned char) c_out)); adler32 -= (unsigned char)c_out; adler32 += (unsigned char)c_in; return adler32 + adler32 * 0x10000; } /* Calculate an peudo-adler32 checksum for MATCH_BLOCKSIZE bytes starting at DATA. Return the checksum value. */ static APR_INLINE apr_uint32_t init_adler32(const char *data) { const unsigned char *input = (const unsigned char *)data; const unsigned char *last = input + MATCH_BLOCKSIZE; apr_uint32_t s1 = 0; apr_uint32_t s2 = 0; for (; input < last; input += 8) { s1 += input[0]; s2 += s1; s1 += input[1]; s2 += s1; s1 += input[2]; s2 += s1; s1 += input[3]; s2 += s1; s1 += input[4]; s2 += s1; s1 += input[5]; s2 += s1; s1 += input[6]; s2 += s1; s1 += input[7]; s2 += s1; } return s2 * 0x10000 + s1; } /* Information for a block of the delta source. The length of the block is the smaller of MATCH_BLOCKSIZE and the difference between the size of the source data and the position of this block. */ struct block { apr_uint32_t adlersum; apr_size_t pos; }; /* A hash table, using open addressing, of the blocks of the source. */ struct blocks { /* The largest valid index of slots. */ apr_size_t max; /* Source buffer that the positions in SLOTS refer to. */ const char* data; /* The vector of blocks. A pos value of (apr_size_t)-1 represents an unused slot. */ struct block *slots; }; /* Return a hash value calculated from the adler32 SUM, suitable for use with our hash table. */ static apr_size_t hash_func(apr_uint32_t sum) { /* Since the adl32 checksum have a bad distribution for the 11th to 16th bits when used for our small block size, we add some bits from the other half of the checksum. */ return sum ^ (sum >> 12); } /* Insert a block with the checksum ADLERSUM at position POS in the source data into the table BLOCKS. Ignore true duplicates, i.e. blocks with actually the same content. */ static void add_block(struct blocks *blocks, apr_uint32_t adlersum, apr_size_t pos) { apr_size_t h = hash_func(adlersum) & blocks->max; /* This will terminate, since we know that we will not fill the table. */ for (; blocks->slots[h].pos != (apr_size_t)-1; h = (h + 1) & blocks->max) if (blocks->slots[h].adlersum == adlersum) if (memcmp(blocks->data + blocks->slots[h].pos, blocks->data + pos, MATCH_BLOCKSIZE) == 0) return; blocks->slots[h].adlersum = adlersum; blocks->slots[h].pos = pos; } /* Find a block in BLOCKS with the checksum ADLERSUM and matching the content at DATA, returning its position in the source data. If there is no such block, return (apr_size_t)-1. */ static apr_size_t find_block(const struct blocks *blocks, apr_uint32_t adlersum, const char* data) { apr_size_t h = hash_func(adlersum) & blocks->max; for (; blocks->slots[h].pos != (apr_size_t)-1; h = (h + 1) & blocks->max) if (blocks->slots[h].adlersum == adlersum) if (memcmp(blocks->data + blocks->slots[h].pos, data, MATCH_BLOCKSIZE) == 0) return blocks->slots[h].pos; return (apr_size_t)-1; } /* Initialize the matches table from DATA of size DATALEN. This goes through every block of MATCH_BLOCKSIZE bytes in the source and checksums it, inserting the result into the BLOCKS table. */ static void init_blocks_table(const char *data, apr_size_t datalen, struct blocks *blocks, apr_pool_t *pool) { apr_size_t i; apr_size_t nblocks; apr_size_t nslots = 1; /* Be pesimistic about the block count. */ nblocks = datalen / MATCH_BLOCKSIZE + 1; /* Find nearest larger power of two. */ while (nslots <= nblocks) nslots *= 2; /* Double the number of slots to avoid a too high load. */ nslots *= 2; blocks->max = nslots - 1; blocks->data = data; blocks->slots = apr_palloc(pool, nslots * sizeof(*(blocks->slots))); for (i = 0; i < nslots; ++i) { /* Avoid using an indeterminate value in the lookup. */ blocks->slots[i].adlersum = 0; blocks->slots[i].pos = (apr_size_t)-1; } /* If there is an odd block at the end of the buffer, we will not use that shorter block for deltification (only indirectly as an extension of some previous block). */ for (i = 0; i + MATCH_BLOCKSIZE <= datalen; i += MATCH_BLOCKSIZE) add_block(blocks, init_adler32(data + i), i); } /* Return the lowest position at which A and B differ. If no difference * can be found in the first MAX_LEN characters, MAX_LEN will be returned. */ static apr_size_t match_length(const char *a, const char *b, apr_size_t max_len) { apr_size_t pos = 0; #if SVN_UNALIGNED_ACCESS_IS_OK /* Chunky processing is so much faster ... * * We can't make this work on architectures that require aligned access * because A and B will probably have different alignment. So, skipping * the first few chars until alignment is reached is not an option. */ for (; pos + sizeof(apr_size_t) <= max_len; pos += sizeof(apr_size_t)) if (*(const apr_size_t*)(a + pos) != *(const apr_size_t*)(b + pos)) break; #endif for (; pos < max_len; ++pos) if (a[pos] != b[pos]) break; return pos; } /* Try to find a match for the target data B in BLOCKS, and then extend the match as long as data in A and B at the match position continues to match. We set the position in A we ended up in (in case we extended it backwards) in APOSP and update the correspnding position within B given in BPOSP. PENDING_INSERT_START sets the lower limit to BPOSP. Return number of matching bytes starting at ASOP. Return 0 if no match has been found. */ static apr_size_t find_match(const struct blocks *blocks, const apr_uint32_t rolling, const char *a, apr_size_t asize, const char *b, apr_size_t bsize, apr_size_t *bposp, apr_size_t *aposp, apr_size_t pending_insert_start) { apr_size_t apos, bpos = *bposp; apr_size_t delta, max_delta; apos = find_block(blocks, rolling, b + bpos); /* See if we have a match. */ if (apos == (apr_size_t)-1) return 0; /* Extend the match forward as far as possible */ max_delta = asize - apos - MATCH_BLOCKSIZE < bsize - bpos - MATCH_BLOCKSIZE ? asize - apos - MATCH_BLOCKSIZE : bsize - bpos - MATCH_BLOCKSIZE; delta = match_length(a + apos + MATCH_BLOCKSIZE, b + bpos + MATCH_BLOCKSIZE, max_delta); /* See if we can extend backwards (max MATCH_BLOCKSIZE-1 steps because A's content has been sampled only every MATCH_BLOCKSIZE positions). */ while (apos > 0 && bpos > pending_insert_start && a[apos-1] == b[bpos-1]) { --apos; --bpos; ++delta; } *aposp = apos; *bposp = bpos; return MATCH_BLOCKSIZE + delta; } /* Compute a delta from A to B using xdelta. The basic xdelta algorithm is as follows: 1. Go through the source data, checksumming every MATCH_BLOCKSIZE block of bytes using adler32, and inserting the checksum into a match table with the position of the match. 2. Go through the target byte by byte, seeing if that byte starts a match that we have in the match table. 2a. If so, try to extend the match as far as possible both forwards and backwards, and then insert a source copy operation into the delta ops builder for the match. 2b. If not, insert the byte as new data using an insert delta op. Our implementation doesn't immediately insert "insert" operations, it waits until we have another copy, or we are done. The reasoning is twofold: 1. Otherwise, we would just be building a ton of 1 byte insert operations 2. So that we can extend a source match backwards into a pending insert operation, and possibly remove the need for the insert entirely. This can happen due to stream alignment. */ static void compute_delta(svn_txdelta__ops_baton_t *build_baton, const char *a, apr_uint32_t asize, const char *b, apr_uint32_t bsize, apr_pool_t *pool) { struct blocks blocks; apr_uint32_t rolling; apr_size_t lo = 0, pending_insert_start = 0; /* If the size of the target is smaller than the match blocksize, just insert the entire target. */ if (bsize < MATCH_BLOCKSIZE) { svn_txdelta__insert_op(build_baton, svn_txdelta_new, 0, bsize, b, pool); return; } /* Initialize the matches table. */ init_blocks_table(a, asize, &blocks, pool); /* Initialize our rolling checksum. */ rolling = init_adler32(b); while (lo < bsize) { apr_size_t matchlen = 0; apr_size_t apos; if (lo + MATCH_BLOCKSIZE <= bsize) matchlen = find_match(&blocks, rolling, a, asize, b, bsize, &lo, &apos, pending_insert_start); /* If we didn't find a real match, insert the byte at the target position into the pending insert. */ if (matchlen == 0) { /* move block one position forward. Short blocks at the end of the buffer cannot be used as the beginning of a new match */ if (lo + MATCH_BLOCKSIZE < bsize) rolling = adler32_replace(rolling, b[lo], b[lo+MATCH_BLOCKSIZE]); lo++; } else { /* store the sequence of B that is between the matches */ if (lo - pending_insert_start > 0) svn_txdelta__insert_op(build_baton, svn_txdelta_new, 0, lo - pending_insert_start, b + pending_insert_start, pool); /* Reset the pending insert start to immediately after the match. */ lo += matchlen; pending_insert_start = lo; svn_txdelta__insert_op(build_baton, svn_txdelta_source, apos, matchlen, NULL, pool); /* Calculate the Adler32 sum for the first block behind the match. * Ignore short buffers at the end of B. */ if (lo + MATCH_BLOCKSIZE <= bsize) rolling = init_adler32(b + lo); } } /* If we still have an insert pending at the end, throw it in. */ if (lo - pending_insert_start > 0) { svn_txdelta__insert_op(build_baton, svn_txdelta_new, 0, lo - pending_insert_start, b + pending_insert_start, pool); } } void svn_txdelta__xdelta(svn_txdelta__ops_baton_t *build_baton, const char *data, apr_size_t source_len, apr_size_t target_len, apr_pool_t *pool) { /* We should never be asked to compute something when the source_len is 0; we just use a single insert op there (and rely on zlib for compression). */ assert(source_len != 0); compute_delta(build_baton, data, source_len, data + source_len, target_len, pool); }
33.799499
78
0.640664
[ "vector" ]
ea8196ce6d8430adc3f9b4dad9ac40f341097e0d
4,298
h
C
src/api/video/video_stream_encoder_observer.h
ilya-fedin/tg_owt
d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589
[ "BSD-3-Clause" ]
162
2018-04-03T04:29:45.000Z
2022-03-30T19:41:27.000Z
src/api/video/video_stream_encoder_observer.h
ilya-fedin/tg_owt
d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589
[ "BSD-3-Clause" ]
59
2020-08-24T09:17:42.000Z
2022-02-27T23:33:37.000Z
src/api/video/video_stream_encoder_observer.h
ilya-fedin/tg_owt
d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589
[ "BSD-3-Clause" ]
62
2018-03-26T08:38:18.000Z
2022-03-14T02:29:47.000Z
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef API_VIDEO_VIDEO_STREAM_ENCODER_OBSERVER_H_ #define API_VIDEO_VIDEO_STREAM_ENCODER_OBSERVER_H_ #include <string> #include <vector> #include "absl/types/optional.h" #include "api/video/video_adaptation_counters.h" #include "api/video/video_adaptation_reason.h" #include "api/video/video_bitrate_allocation.h" #include "api/video/video_codec_constants.h" #include "api/video_codecs/video_encoder.h" #include "api/video_codecs/video_encoder_config.h" namespace webrtc { // TODO(nisse): Used for the OnSendEncodedImage callback below. The callback // wants metadata such as size, encode timing, qp, but doesn't need actual // encoded data. So use some other type to represent that. class EncodedImage; // Broken out into a base class, with public inheritance below, only to ease // unit testing of the internal class OveruseFrameDetector. class CpuOveruseMetricsObserver { public: virtual ~CpuOveruseMetricsObserver() = default; virtual void OnEncodedFrameTimeMeasured(int encode_duration_ms, int encode_usage_percent) = 0; }; class VideoStreamEncoderObserver : public CpuOveruseMetricsObserver { public: struct AdaptationSettings { AdaptationSettings() : resolution_scaling_enabled(false), framerate_scaling_enabled(false) {} AdaptationSettings(bool resolution_scaling_enabled, bool framerate_scaling_enabled) : resolution_scaling_enabled(resolution_scaling_enabled), framerate_scaling_enabled(framerate_scaling_enabled) {} bool resolution_scaling_enabled; bool framerate_scaling_enabled; }; // TODO(nisse): Duplicates enum EncodedImageCallback::DropReason. enum class DropReason { kSource, kEncoderQueue, kEncoder, kMediaOptimization, kCongestionWindow }; ~VideoStreamEncoderObserver() override = default; virtual void OnIncomingFrame(int width, int height) = 0; // TODO(nisse): Merge into one callback per encoded frame. using CpuOveruseMetricsObserver::OnEncodedFrameTimeMeasured; virtual void OnSendEncodedImage(const EncodedImage& encoded_image, const CodecSpecificInfo* codec_info) = 0; virtual void OnEncoderImplementationChanged( const std::string& implementation_name) = 0; virtual void OnFrameDropped(DropReason reason) = 0; // Used to indicate change in content type, which may require a change in // how stats are collected and set the configured preferred media bitrate. virtual void OnEncoderReconfigured( const VideoEncoderConfig& encoder_config, const std::vector<VideoStream>& streams) = 0; virtual void OnAdaptationChanged( VideoAdaptationReason reason, const VideoAdaptationCounters& cpu_steps, const VideoAdaptationCounters& quality_steps) = 0; virtual void ClearAdaptationStats() = 0; virtual void UpdateAdaptationSettings( AdaptationSettings cpu_settings, AdaptationSettings quality_settings) = 0; virtual void OnMinPixelLimitReached() = 0; virtual void OnInitialQualityResolutionAdaptDown() = 0; virtual void OnSuspendChange(bool is_suspended) = 0; virtual void OnBitrateAllocationUpdated( const VideoCodec& codec, const VideoBitrateAllocation& allocation) {} // Informes observer if an internal encoder scaler has reduced video // resolution or not. `is_scaled` is a flag indicating if the video is scaled // down. virtual void OnEncoderInternalScalerUpdate(bool is_scaled) {} // TODO(nisse): VideoStreamEncoder wants to query the stats, which makes this // not a pure observer. GetInputFrameRate is needed for the cpu adaptation, so // can be deleted if that responsibility is moved out to a VideoStreamAdaptor // class. virtual int GetInputFrameRate() const = 0; }; } // namespace webrtc #endif // API_VIDEO_VIDEO_STREAM_ENCODER_OBSERVER_H_
36.735043
80
0.755002
[ "vector" ]
ea89f70b271c1e021e17634bb1c84fc148fcac62
6,013
h
C
libs/quadwild/libs/vcglib/wrap/io_trimesh/export_field.h
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
null
null
null
libs/quadwild/libs/vcglib/wrap/io_trimesh/export_field.h
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
null
null
null
libs/quadwild/libs/vcglib/wrap/io_trimesh/export_field.h
Pentacode-IAFA/Quad-Remeshing
f8fd4c10abf1c54656b38a00b8a698b952a85fe2
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004-2016 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #ifndef __VCGLIB_EXPORTERFIELD #define __VCGLIB_EXPORTERFIELD #include <vcg/complex/algorithms/parametrization/tangent_field_operators.h> namespace vcg { namespace tri { namespace io { /** This class encapsulate a filter for saving field formats */ template <class MeshType> class ExporterFIELD { typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::CoordType CoordType; public: ///load a field on the mesh, it could be a vfield file (per vertex) ///or an ffield file (per face) static void SaveFaceFIELD(MeshType &mesh, const char *path) { FILE *f = fopen(path,"wt"); //if (!f)return false; // char word[512]; word[0]=0; // fscanf(f,"%s",word); // char c=0; // if (word[0]=='#') { // // skip comment line // while (fscanf(f,"%c",&c)!=EOF) if (c=='\n') break; // } // else // { // return false; // } int nf = mesh.fn;//-1; fprintf(f,"# frame generated with VCG \n"); fprintf(f,"target frame \n"); fprintf(f,"%d\n",nf); // // if( per_vertex && !HasPerVertexCurvatureDir(mesh)) throw vcg::MissingComponentException("PerVertexCurvatureDir"); // if(!per_vertex && !HasPerFaceCurvatureDir(mesh)) throw vcg::MissingComponentException("PerFaceCurvatureDir"); if (!HasPerFaceCurvatureDir(mesh)) throw vcg::MissingComponentException("PerFaceCurvatureDir"); fprintf(f,"k1 k2 k1v_x k1v_y k1v_z k2v_x k2v_y k2v_z\n"); for (int i=0; i<nf; i++){ vcg::Point3<float> u; u.Import(mesh.face[i].PD1()); vcg::Point3<float> v; v.Import(mesh.face[i].PD2()); fprintf(f,"1 1 %f %f %f %f %f %f\n", (u.X()),(u.Y()),(u.Z()), (v.X()),(v.Y()),(v.Z())); } fclose(f); } ///Save a 4 rosy format file as used by ///Interactive Visualization of Rotational Symmetry Fields on Surfaces ///Jonathan Palacios and Eugene Zhang static void Save4ROSY(MeshType &mesh, const char *path) { FILE *f = fopen(path,"wt"); fprintf(f,"%d\n",mesh.fn); fprintf(f,"4\n"); for (unsigned int i=0;i<mesh.face.size();i++) { float dirX=(float)mesh.face[i].PD1().X(); float dirY=(float)mesh.face[i].PD1().Y(); float dirZ=(float)mesh.face[i].PD1().Z(); fprintf(f,"%f %f %f \n",dirX,dirY,dirZ); } fclose(f); } //Save a 4 rosy format file as pair of angles static void Save2AngleFace(MeshType &mesh, const char *path) { FILE *f = fopen(path,"wt"); fprintf(f,"#%d param_field\n",mesh.fn); for (unsigned int i=0;i<mesh.face.size();i++) { ScalarType alpha1,alpha2; CoordType PD1Test=mesh.face[i].PD1(); CoordType PD2Test=mesh.face[i].PD2(); vcg::tri::CrossField<MeshType>::CrossFieldToAngles(mesh.face[i],alpha1,alpha2,1); fprintf(f,"%d %f %f \n",i,alpha1,alpha2); } fclose(f); } static void SaveCSVField(MeshType &mesh, const std::string &field_1, const std::string &field_2) { FILE *f1=NULL; FILE *f2=NULL; f1=fopen(field_1.c_str(),"wt"); f2=fopen(field_2.c_str(),"wt"); for (size_t i=0;i<mesh.face.size();i++) { typename MeshType::CoordType PD1=mesh.face[i].PD1(); typename MeshType::CoordType PD2=mesh.face[i].PD2(); fprintf(f1,"%e,%e,%e\n",PD1.X(),PD1.Y(),PD1.Z()); fprintf(f2,"%e,%e,%e\n",PD2.X(),PD2.Y(),PD2.Z()); } //then color by quality fclose(f1); fclose(f2); } }; // end class } // end namespace tri } // end namespace io } // end namespace vcg #endif
38.299363
127
0.459005
[ "mesh" ]
ea8a284d2baa3399b6df0867e2aad6a3ec2dcb60
2,653
h
C
Engine/Game/ComponentManagers/TransformManager.h
guimeixen/Engine
fcea39d2099b613b32b20462586e1c932bbb24fc
[ "MIT" ]
null
null
null
Engine/Game/ComponentManagers/TransformManager.h
guimeixen/Engine
fcea39d2099b613b32b20462586e1c932bbb24fc
[ "MIT" ]
17
2021-03-12T18:19:07.000Z
2021-08-06T21:25:35.000Z
Engine/Game/ComponentManagers/TransformManager.h
guimeixen/Engine
fcea39d2099b613b32b20462586e1c932bbb24fc
[ "MIT" ]
null
null
null
#pragma once #include "Game/EntityManager.h" #include "include/glm/glm.hpp" #include "include/glm/gtc/quaternion.hpp" #include <unordered_map> namespace Engine { class Transform; class Allocator; struct TransformInstanceData { unsigned int size; unsigned int capacity; unsigned char *buffer; glm::mat4 *localToWorld; glm::vec3 *localPosition; glm::quat *localRotation; glm::vec3 *localScale; Entity *parent; Entity *firstChild; Entity *prevSibling; Entity *nextSibling; bool *modified; }; struct ModifiedTransform { Entity e; const glm::mat4 *localToWorld; }; class TransformManager { public: void Init(Allocator *allocator, unsigned int initialCapacity); void Dispose(); void ClearModifiedTransforms(); void AddTransform(Entity e); void DuplicateTransform(Entity e, Entity newE); void RemoveTransform(Entity e); void SetParent(Entity e, Entity parent); void RemoveParent(Entity e); void SetLocalPosition(Entity e, const glm::vec3 &position); void SetLocalRotation(Entity e, const glm::quat &rotation); void SetLocalRotationEuler(Entity e, const glm::vec3 &euler); void SetLocalScale(Entity e, const glm::vec3 &scale); void SetLocalToWorld(Entity e, const glm::mat4 &localToWorld); void SetLocalToParent(Entity e, const glm::mat4 &localToParent); void Rotate(Entity e, const glm::vec3 &rot); const glm::mat4 &GetLocalToWorld(Entity e) const; bool HasParent(Entity e) const; bool HasChildren(Entity e) const; // Don't return const otherwise it will not be possible to change them through script glm::vec3 &GetLocalPosition(Entity e) const { return instanceData.localPosition[e.id]; } glm::quat &GetLocalRotation(Entity e) const { return instanceData.localRotation[e.id]; } glm::vec3 &GetLocalScale(Entity e) const { return instanceData.localScale[e.id]; } glm::vec3 GetWorldPosition(Entity e) const { return instanceData.localToWorld[e.id][3]; } Entity GetParent(Entity e); Entity GetFirstChild(Entity e); Entity GetNextSibling(Entity e); unsigned int GetNumModifiedTransforms() const { return numModifiedTransforms; } const ModifiedTransform *GetModifiedTransforms() const { return modifiedTransforms; } void Serialize(Serializer &s); void Deserialize(Serializer &s); private: void CalcTransform(Entity e); void CalcTransform(Entity e, const glm::mat4 &parent); private: Allocator *allocator; bool isInit = false; TransformInstanceData instanceData; static const unsigned int MAX_MODIFIED_TRANSFORMS = 4096; unsigned int numModifiedTransforms = 0; ModifiedTransform modifiedTransforms[MAX_MODIFIED_TRANSFORMS]; }; }
28.223404
91
0.751602
[ "transform" ]
ea8b3a8dc4620d22d14071d46fb7f8ee6ec70ceb
7,776
h
C
ros/src/sensing/filters/packages/points_preprocessor/nodes/ray_ground_filter/include/ray_ground_filter.h
izeki/Autoware
21dcd18c4166331c290bd573733e0b881ca29ad7
[ "BSD-3-Clause" ]
8
2019-10-04T13:47:38.000Z
2021-11-23T09:49:36.000Z
ros/src/sensing/filters/packages/points_preprocessor/nodes/ray_ground_filter/include/ray_ground_filter.h
izeki/Autoware
21dcd18c4166331c290bd573733e0b881ca29ad7
[ "BSD-3-Clause" ]
null
null
null
ros/src/sensing/filters/packages/points_preprocessor/nodes/ray_ground_filter/include/ray_ground_filter.h
izeki/Autoware
21dcd18c4166331c290bd573733e0b881ca29ad7
[ "BSD-3-Clause" ]
7
2019-07-03T07:24:10.000Z
2021-12-28T03:24:16.000Z
/* * Copyright (c) 2017, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************** * v1.0: amc-nu (abrahammonrroy@yahoo.com) */ #ifndef RAY_GROUND_FILTER_H_ #define RAY_GROUND_FILTER_H_ #include <iostream> #include <algorithm> #include <vector> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <pcl_ros/point_cloud.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_types.h> #include <pcl/features/normal_3d.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/filters/extract_indices.h> #include <velodyne_pointcloud/point_types.h> #include "autoware_msgs/ConfigRayGroundFilter.h" #include <opencv2/core/version.hpp> #if (CV_MAJOR_VERSION == 3) #include "gencolors.cpp" #else #include <opencv2/contrib/contrib.hpp> #endif class RayGroundFilter { private: ros::NodeHandle node_handle_; ros::Subscriber points_node_sub_; ros::Subscriber config_node_sub_; ros::Publisher groundless_points_pub_; ros::Publisher ground_points_pub_; std::string input_point_topic_; double sensor_height_;//meters double general_max_slope_;//degrees double local_max_slope_;//degrees double radial_divider_angle_;//distance in rads between dividers double concentric_divider_distance_;//distance in meters between concentric divisions double min_height_threshold_;//minimum height threshold regardless the slope, useful for close points double clipping_height_; //the points higher than this will be removed from the input cloud. double min_point_distance_;//minimum distance from the origin to consider a point as valid double reclass_distance_threshold_;//distance between points at which re classification will occur size_t radial_dividers_num_; size_t concentric_dividers_num_; std::vector<cv::Scalar> colors_; const size_t color_num_ = 60;//different number of color to generate struct PointXYZIRTColor { pcl::PointXYZI point; float radius; //cylindric coords on XY Plane float theta; //angle deg on XY plane size_t radial_div; //index of the radial divsion to which this point belongs to size_t concentric_div;//index of the concentric division to which this points belongs to size_t red; //Red component [0-255] size_t green; //Green Component[0-255] size_t blue; //Blue component [0-255] size_t original_index; //index of this point in the source pointcloud }; typedef std::vector<PointXYZIRTColor> PointCloudXYZIRTColor; void update_config_params(const autoware_msgs::ConfigRayGroundFilter::ConstPtr& param); void publish_cloud(const ros::Publisher& in_publisher, const pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud_to_publish_ptr, const std_msgs::Header& in_header); /*! * * @param[in] in_cloud Input Point Cloud to be organized in radial segments * @param[out] out_organized_points Custom Point Cloud filled with XYZRTZColor data * @param[out] out_radial_divided_indices Indices of the points in the original cloud for each radial segment * @param[out] out_radial_ordered_clouds Vector of Points Clouds, each element will contain the points ordered */ void ConvertXYZIToRTZColor(const pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud, PointCloudXYZIRTColor& out_organized_points, std::vector<pcl::PointIndices>& out_radial_divided_indices, std::vector<PointCloudXYZIRTColor>& out_radial_ordered_clouds); /*! * Classifies Points in the PointCoud as Ground and Not Ground * @param in_radial_ordered_clouds Vector of an Ordered PointsCloud ordered by radial distance from the origin * @param out_ground_indices Returns the indices of the points classified as ground in the original PointCloud * @param out_no_ground_indices Returns the indices of the points classified as not ground in the original PointCloud */ void ClassifyPointCloud(std::vector<PointCloudXYZIRTColor>& in_radial_ordered_clouds, pcl::PointIndices& out_ground_indices, pcl::PointIndices& out_no_ground_indices); /*! * Removes the points higher than a threshold * @param in_cloud_ptr PointCloud to perform Clipping * @param in_clip_height Maximum allowed height in the cloud * @param out_clipped_cloud_ptr Resultung PointCloud with the points removed */ void ClipCloud(const pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud_ptr, double in_clip_height, pcl::PointCloud<pcl::PointXYZI>::Ptr out_clipped_cloud_ptr); /*! * Returns the resulting complementary PointCloud, one with the points kept and the other removed as indicated * in the indices * @param in_cloud_ptr Input PointCloud to which the extraction will be performed * @param in_indices Indices of the points to be both removed and kept * @param out_only_indices_cloud_ptr Resulting PointCloud with the indices kept * @param out_removed_indices_cloud_ptr Resulting PointCloud with the indices removed */ void ExtractPointsIndices(const pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud_ptr, const pcl::PointIndices& in_indices, pcl::PointCloud<pcl::PointXYZI>::Ptr out_only_indices_cloud_ptr, pcl::PointCloud<pcl::PointXYZI>::Ptr out_removed_indices_cloud_ptr); /*! * Removes points up to a certain distance in the XY Plane * @param in_cloud_ptr Input PointCloud * @param in_min_distance Minimum valid distance, points closer than this will be removed. * @param out_filtered_cloud_ptr Resulting PointCloud with the invalid points removed. */ void RemovePointsUpTo(const pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud_ptr, double in_min_distance, pcl::PointCloud<pcl::PointXYZI>::Ptr out_filtered_cloud_ptr); void CloudCallback(const sensor_msgs::PointCloud2ConstPtr &in_sensor_cloud); friend class RayGroundFilter_clipCloud_Test; public: RayGroundFilter(); void Run(); }; #endif // RAY_GROUND_FILTER_H_
44.434286
118
0.729167
[ "vector" ]
ea8c9f82dcf1ce3e4df72d090b6a018656f59b55
11,963
c
C
donem5/sistem-programlama/ders-icerigi/kodlar/ebbchar.c
getmewrong/IstanbulUniversityCerrahpasa-CE
1735f7a6f39c256affaa530653df65a99fdfef3c
[ "Apache-2.0" ]
19
2019-10-25T22:05:22.000Z
2020-02-16T10:44:51.000Z
donem5/sistem-programlama/ders-icerigi/kodlar/ebbchar.c
getmewrong/IstanbulUniversityCerrahpasa-CE
1735f7a6f39c256affaa530653df65a99fdfef3c
[ "Apache-2.0" ]
36
2019-10-21T23:22:45.000Z
2020-02-19T17:19:12.000Z
donem5/sistem-programlama/ders-icerigi/kodlar/ebbchar.c
getmewrong/IstanbulUniversityCerrahpasa-CE
1735f7a6f39c256affaa530653df65a99fdfef3c
[ "Apache-2.0" ]
18
2019-10-20T20:10:49.000Z
2020-01-24T09:18:58.000Z
/** * @file ebbchar.c * @author Derek Molloy * @date 7 April 2015 * @version 0.1 * @brief An introductory character driver to support the second article of my series on * Linux loadable kernel module (LKM) development. This module maps to /dev/ebbchar and * comes with a helper C program that can be run in Linux user space to communicate with * this the LKM. * @see http://www.derekmolloy.ie/ for a full description and follow-up descriptions. */ #include <linux/init.h> // Macros used to mark up functions e.g. __init __exit #include <linux/module.h> // Core header for loading LKMs into the kernel #include <linux/device.h> // Header to support the kernel Driver Model #include <linux/kernel.h> // Contains types, macros, functions for the kernel #include <linux/fs.h> // Header for the Linux file system support #include <asm/uaccess.h> // Required for the copy to user function #define DEVICE_NAME "ebbchar" ///< The device will appear at /dev/ebbchar using this value #define CLASS_NAME "ebb" ///< The device class -- this is a character device driver MODULE_LICENSE("GPL"); ///< The license type -- this affects available functionality MODULE_AUTHOR("Derek Molloy"); ///< The author -- visible when you use modinfo MODULE_DESCRIPTION("A simple Linux char driver for the BBB"); ///< The description -- see modinfo MODULE_VERSION("0.1"); ///< A version number to inform users static int majorNumber; ///< Stores the device number -- determined automatically static char message[256] = {0}; ///< Memory for the string that is passed from userspace static short size_of_message; ///< Used to remember the size of the string stored static int numberOpens = 0; ///< Counts the number of times the device is opened static struct class* ebbcharClass = NULL; ///< The device-driver class struct pointer static struct device* ebbcharDevice = NULL; ///< The device-driver device struct pointer // The prototype functions for the character driver -- must come before the struct definition static int dev_open(struct inode *, struct file *); static int dev_release(struct inode *, struct file *); static ssize_t dev_read(struct file *, char *, size_t, loff_t *); static ssize_t dev_write(struct file *, const char *, size_t, loff_t *); /** @brief Devices are represented as file structure in the kernel. The file_operations structure from * /linux/fs.h lists the callback functions that you wish to associated with your file operations * using a C99 syntax structure. char devices usually implement open, read, write and release calls */ static struct file_operations fops = { .open = dev_open, .read = dev_read, .write = dev_write, .release = dev_release, }; /** @brief The LKM initialization function * The static keyword restricts the visibility of the function to within this C file. The __init * macro means that for a built-in driver (not a LKM) the function is only used at initialization * time and that it can be discarded and its memory freed up after that point. * @return returns 0 if successful */ static int __init ebbchar_init(void){ printk(KERN_INFO "EBBChar: Initializing the EBBChar LKM\n"); // Try to dynamically allocate a major number for the device -- more difficult but worth it majorNumber = register_chrdev(0, DEVICE_NAME, &fops); if (majorNumber<0){ printk(KERN_ALERT "EBBChar failed to register a major number\n"); return majorNumber; } printk(KERN_INFO "EBBChar: registered correctly with major number %d\n", majorNumber); // Register the device class ebbcharClass = class_create(THIS_MODULE, CLASS_NAME); if (IS_ERR(ebbcharClass)){ // Check for error and clean up if there is unregister_chrdev(majorNumber, DEVICE_NAME); printk(KERN_ALERT "Failed to register device class\n"); return PTR_ERR(ebbcharClass); // Correct way to return an error on a pointer } printk(KERN_INFO "EBBChar: device class registered correctly\n"); // Register the device driver ebbcharDevice = device_create(ebbcharClass, NULL, MKDEV(majorNumber, 0), NULL, DEVICE_NAME); if (IS_ERR(ebbcharDevice)){ // Clean up if there is an error class_destroy(ebbcharClass); // Repeated code but the alternative is goto statements unregister_chrdev(majorNumber, DEVICE_NAME); printk(KERN_ALERT "Failed to create the device\n"); return PTR_ERR(ebbcharDevice); } printk(KERN_INFO "EBBChar: device class created correctly\n"); // Made it! device was initialized return 0; } /** @brief The LKM cleanup function * Similar to the initialization function, it is static. The __exit macro notifies that if this * code is used for a built-in driver (not a LKM) that this function is not required. */ static void __exit ebbchar_exit(void){ device_destroy(ebbcharClass, MKDEV(majorNumber, 0)); // remove the device class_unregister(ebbcharClass); // unregister the device class class_destroy(ebbcharClass); // remove the device class unregister_chrdev(majorNumber, DEVICE_NAME); // unregister the major number printk(KERN_INFO "EBBChar: Goodbye from the LKM!\n"); } /** @brief The device open function that is called each time the device is opened * This will only increment the numberOpens counter in this case. * @param inodep A pointer to an inode object (defined in linux/fs.h) * @param filep A pointer to a file object (defined in linux/fs.h) */ static int dev_open(struct inode *inodep, struct file *filep){ numberOpens++; printk(KERN_INFO "EBBChar: Device has been opened %d time(s)\n", numberOpens); return 0; } /** @brief This function is called whenever device is being read from user space i.e. data is * being sent from the device to the user. In this case is uses the copy_to_user() function to * send the buffer string to the user and captures any errors. * @param filep A pointer to a file object (defined in linux/fs.h) * @param buffer The pointer to the buffer to which this function writes the data * @param len The length of the b * @param offset The offset if required */ static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset){ int error_count = 0; // copy_to_user has the format ( * to, *from, size) and returns 0 on success error_count = copy_to_user(buffer, message, size_of_message); if (error_count==0){ // if true then have success printk(KERN_INFO "EBBChar: Sent %d characters to the user\n", size_of_message); return (size_of_message=0); // clear the position to the start and return 0 } else { printk(KERN_INFO "EBBChar: Failed to send %d characters to the user\n", error_count); return -EFAULT; // Failed -- return a bad address message (i.e. -14) } } /** @brief This function is called whenever the device is being written to from user space i.e. * data is sent to the device from the user. The data is copied to the message[] array in this * LKM using the sprintf() function along with the length of the string. * @param filep A pointer to a file object * @param buffer The buffer to that contains the string to write to the device * @param len The length of the array of data that is being passed in the const char buffer * @param offset The offset if required */ static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, loff_t *offset){ sprintf(message, "%s(%zu letters)", buffer, len); // appending received string with its length size_of_message = strlen(message); // store the length of the stored message printk(KERN_INFO "EBBChar: Received %zu characters from the user\n", len); return len; } /** @brief The device release function that is called whenever the device is closed/released by * the userspace program * @param inodep A pointer to an inode object (defined in linux/fs.h) * @param filep A pointer to a file object (defined in linux/fs.h) */ static int dev_release(struct inode *inodep, struct file *filep){ printk(KERN_INFO "EBBChar: Device successfully closed\n"); return 0; } /** @brief A module must use the module_init() module_exit() macros from linux/init.h, which * identify the initialization function at insertion time and the cleanup function (as * listed above) */ module_init(ebbchar_init); module_exit(ebbchar_exit); /* dev_open(): Called each time the device is opened from user space. dev_read(): Called when data is sent from the device to user space. dev_write(): Called when data is sent from user space to the device. dev_release(): Called when the device is closed in user space. obj-m+=ebbchar.o all: make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules $(CC) testebbchar.c -o test clean: make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) clean rm test All going well, the process to build the kernel module should be straightforward, provided that you have installed the Linux headers as described in the first article. The steps are as follows: molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ make molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ ls -l *.ko -rw-r--r-- 1 molloyd molloyd 7075 Apr 8 19:04 ebbchar.ko molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ ls -l test -rwxr-xr-x 1 molloyd molloyd 6342 Apr 8 19:23 test molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ sudo insmod ebbchar.ko molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ lsmod Module Size Used by ebbchar 2521 0 The device is now present in the /dev directory, with the following attributes: molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ cd /dev molloyd@beaglebone:/dev$ ls -l ebb* crw------- 1 root root 240, 0 Apr 8 19:28 ebbchar You can see that the major number is 240 — this is automatically assigned by the code in Listing 2. We can then use the testebbchar program (Listing 4) to test that the LKM is working correctly. For the moment, the test program must be executed with root privileges — that issue is addressed shortly. molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ sudo insmod ebbchar.ko molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ sudo ./test Starting device test code example... Type in a short string to send to the kernel module: This is a test of the ebbchar LKM Writing message to the device [This is a test of the ebbchar LKM]. Press ENTER to read back from the device... Reading from the device... The received message is: [This is a test of the ebbchar LKM(33 letters)] End of the program molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ sudo rmmod ebbchar The printk() output can be viewed by examining the kernel logs as follows: molloyd@beaglebone:~/exploringBB/extras/kernel/ebbchar$ sudo tail -f /var/log/kern.log Apr 11 22:24:50 beaglebone kernel: [358664.365942] EBBChar: Initializing the EBBChar LKM Apr 11 22:24:50 beaglebone kernel: [358664.365980] EBBChar: registered correctly with major number 240 Apr 11 22:24:50 beaglebone kernel: [358664.366061] EBBChar: device class registered correctly Apr 11 22:24:50 beaglebone kernel: [358664.368383] EBBChar: device class created correctly Apr 11 22:25:15 beaglebone kernel: [358689.812483] EBBChar: Device has been opened 1 time(s) Apr 11 22:25:31 beaglebone kernel: [358705.451551] EBBChar: Received 33 characters from the user Apr 11 22:25:32 beaglebone kernel: [358706.403818] EBBChar: Sent 45 characters to the user Apr 11 22:25:32 beaglebone kernel: [358706.404207] EBBChar: Device successfully closed Apr 11 22:25:44 beaglebone kernel: [358718.497000] EBBChar: Goodbye from the LKM! */
52.933628
200
0.719636
[ "object", "model" ]
ea95d5a08ae6b509d66efebbc2bcf85aee3b4d4f
2,639
h
C
src/vm/natives.h
dartino/fletch
aa7aba8473f405dd49b9c81b0faeeebfa6e94fc8
[ "BSD-3-Clause" ]
144
2016-01-29T00:14:04.000Z
2021-02-20T09:36:11.000Z
src/vm/natives.h
akashfoss/sdk
aa7aba8473f405dd49b9c81b0faeeebfa6e94fc8
[ "BSD-3-Clause" ]
241
2016-01-27T15:37:56.000Z
2016-09-09T07:34:07.000Z
src/vm/natives.h
akashfoss/sdk
aa7aba8473f405dd49b9c81b0faeeebfa6e94fc8
[ "BSD-3-Clause" ]
30
2016-02-23T18:14:54.000Z
2020-10-18T13:49:34.000Z
// Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. #ifndef SRC_VM_NATIVES_H_ #define SRC_VM_NATIVES_H_ #include "src/shared/assert.h" #include "src/shared/globals.h" #include "src/shared/natives.h" namespace dartino { // Forward declarations. class Assembler; class Object; class OneByteString; class Process; class TwoByteString; // TODO(kasperl): Move this elsewhere. char* AsForeignString(Object* object); // Wrapper for arguments to native functions, where argument indexing is // growing. class Arguments { public: explicit Arguments(Object** raw) : raw_(raw) {} Object* operator[](word index) const { return raw_[-index]; } private: Object** raw_; }; // A NativeVerifier is stack allocated at the start of a native and // destructed at the end of the native. In debug mode, the verifier // tracks allocations and the destructor verifies that the native only // performed one allocation. #ifdef DEBUG class NativeVerifier { public: explicit NativeVerifier(Process* process); ~NativeVerifier(); void RegisterAllocation() { ++allocation_count_; } private: Process* process_; int allocation_count_; }; #else class NativeVerifier { public: explicit NativeVerifier(Process* process) {} void RegisterAllocation() { UNREACHABLE(); } }; #endif typedef Object* (*NativeFunction)(Process*, Arguments); #define DECLARE_NATIVE(n) \ extern "C" Object* Native_##n(Process* process, Arguments arguments); #define BEGIN_NATIVE(n) \ extern "C" Object* Native_##n(Process* process, Arguments arguments) { // Leaf natives are not at a safe point and may not invoke GCs or call back into // Dart. #define BEGIN_LEAF_NATIVE(n) \ BEGIN_NATIVE(n) \ static_assert(kIsLeaf_##n, "Incorrect use of natives macro"); \ NativeVerifier verifier(process); #define END_NATIVE() } #define EVALUATE_FFI_CALL_AND_RETURN_AND_GC(expr) \ int64 value = (expr); \ if (Smi::IsValid(value)) return Smi::FromWord(value); \ return process->NewIntegerWithGC(value); #define EVALUATE_FFI_CALL_AND_RETURN_VOID(expr) \ (expr); \ return Smi::FromWord(0); #define N(e, c, n, d) DECLARE_NATIVE(e) NATIVES_DO(N) #undef N } // namespace dartino #endif // SRC_VM_NATIVES_H_
28.074468
80
0.661235
[ "object" ]
ea963c808d7d8091f02639e872a867c4e6891d15
9,046
h
C
similarity_search/include/params.h
jvkersch/nmslib
f3a068e364cb3f86539002700cb2944b5c1798e9
[ "Apache-2.0" ]
null
null
null
similarity_search/include/params.h
jvkersch/nmslib
f3a068e364cb3f86539002700cb2944b5c1798e9
[ "Apache-2.0" ]
null
null
null
similarity_search/include/params.h
jvkersch/nmslib
f3a068e364cb3f86539002700cb2944b5c1798e9
[ "Apache-2.0" ]
null
null
null
/** * Non-metric Space Library * * Main developers: Bilegsaikhan Naidan, Leonid Boytsov, Yury Malkov, Ben Frederickson, David Novak * * For the complete list of contributors and further details see: * https://github.com/nmslib/nmslib * * Copyright (c) 2013-2018 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #ifndef PARAMS_H #define PARAMS_H #include <string> #include <vector> #include <limits> #include <map> #include <set> #include <memory> #include <sstream> #include <algorithm> #include <stdexcept> #include "logging.h" #include "utils.h" namespace similarity { using std::string; using std::vector; using std::multimap; using std::set; using std::stringstream; using std::shared_ptr; using std::unique_ptr; #define FAKE_MAX_LEAVES_TO_VISIT std::numeric_limits<int>::max() class AnyParams { public: /* * Each element of the description array is in the form: * <param name>=<param value> */ AnyParams(const vector<string>& Desc) :ParamNames(0), ParamValues(0) { set<string> seen; for (unsigned i = 0; i < Desc.size(); ++i) { vector<string> OneParamPair; if (!SplitStr(Desc[i], OneParamPair, '=') || OneParamPair.size() != 2) { stringstream err; err << "Wrong format of an argument: '" << Desc[i] << "' should be in the format: <Name>=<Value>"; LOG(LIB_ERROR) << err.str(); throw runtime_error(err.str()); } const string& Name = OneParamPair[0]; const string& sVal = OneParamPair[1]; if (seen.count(Name)) { string err = "Duplicate parameter: " + Name; LOG(LIB_ERROR) << err; throw runtime_error(err); } seen.insert(Name); ParamNames.push_back(Name); ParamValues.push_back(sVal); } } /* * Compare parameters against parameters in the other parameter container. * In doing so, IGNORE parameters from the exception list. */ bool equalsIgnoreInList(const AnyParams& that, const vector<string>& ExceptList) { /* * These loops are reasonably efficient, unless * we have thousands of parameters in the exception * list (which realistically won't happen) */ vector<pair<string, string>> vals[2], inter; const AnyParams* objRefs[2] = {this, &that}; for (size_t objId = 0; objId < 2; ++objId) { const AnyParams& obj = *objRefs[objId]; for (size_t i = 0; i < obj.ParamNames.size(); ++i) { const string& name = obj.ParamNames[i]; if (find(ExceptList.begin(), ExceptList.end(), name) == ExceptList.end()) { vals[objId].push_back(make_pair(name, obj.ParamValues[i])); } } sort(vals[objId].begin(), vals[objId].end()); } inter.resize(ParamNames.size() + that.ParamNames.size()); size_t qty = set_intersection(vals[0].begin(), vals[0].end(), vals[1].begin(), vals[1].end(), inter.begin()) - inter.begin(); /* * We computed the size of the intersection. * If it is equal to the size of either of the original * param lists (entries in the exception lists are excluded * at this point), then both sets are equal. */ return qty == vals[0].size() && qty == vals[1].size(); } string ToString() const { stringstream res; for (unsigned i = 0; i < ParamNames.size(); ++i) { if (i) res << ","; res << ParamNames[i] << "=" << ParamValues[i]; } return res.str(); } template <typename ParamType> void ChangeParam(const string& Name, const ParamType& Value) { for (unsigned i = 0; i < ParamNames.size(); ++i) if (Name == ParamNames[i]) { stringstream str; str << Value; ParamValues[i] = str.str(); return; } string err = "Parameter not found: " + Name; LOG(LIB_ERROR) << err; throw runtime_error(err); } template <typename ParamType> void AddChangeParam(const string& Name, const ParamType& Value) { stringstream str; str << Value; for (unsigned i = 0; i < ParamNames.size(); ++i) if (Name == ParamNames[i]) { ParamValues[i] = str.str(); return; } ParamNames.push_back(Name); ParamValues.push_back(str.str()); } AnyParams(){} AnyParams(const vector<string>& Names, const vector<string>& Values) : ParamNames(Names), ParamValues(Values) {} AnyParams(const AnyParams& that) : ParamNames(that.ParamNames), ParamValues(that.ParamValues) {} vector<string> ParamNames; vector<string> ParamValues; }; const inline AnyParams& getEmptyParams() { static AnyParams empty; return empty; } class AnyParamManager { public: AnyParamManager(const AnyParams& params) : params(params), seen() { if (params.ParamNames.size() != params.ParamValues.size()) { string err = "Bug: different # of parameters and values"; LOG(LIB_ERROR) << err; throw runtime_error(err); } } template <typename ParamType> void GetParamRequired(const string& Name, ParamType& Value) { GetParam<ParamType>(Name, Value, true); } template <typename ParamType, typename DefaultType> void GetParamOptional(const string& Name, ParamType& Value, const DefaultType& DefaultValue) { Value=DefaultValue; GetParam<ParamType>(Name, Value, false); } /* * Takes a list of exceptions and extracts all parameter values, * except parameters from the exceptions' list. The extracted parameters * are added to the list of parameters already seen. */ AnyParams ExtractParametersExcept(const vector<string>& ExceptList) { set<string> except(ExceptList.begin(), ExceptList.end()); vector<string> names, values; for (size_t i = 0; i < params.ParamNames.size(); ++i) { const string& name = params.ParamNames[i]; if (except.count(name) == 0) { // Not on the exception list names.push_back(name); values.push_back(params.ParamValues[i]); seen.insert(name); } } return AnyParams(names, values); } /* * Extract all parameter values, whose values are on the list. * The extracted parameters are added to the list of parameters already seen. */ AnyParams ExtractParameters(const vector<string>& CheckList) { set<string> except(CheckList.begin(), CheckList.end()); vector<string> names, values; for (size_t i = 0; i < params.ParamNames.size(); ++i) { const string& name = params.ParamNames[i]; if (except.count(name)) { // On the list names.push_back(name); values.push_back(params.ParamValues[i]); seen.insert(name); } } return AnyParams(names, values); } bool hasParam(const string& name) { for (const string& s: params.ParamNames) if (s == name) return true; return false; }; void CheckUnused() { bool bFail = false; for (size_t i = 0; i < params.ParamNames.size(); ++i) { const string& name = params.ParamNames[i]; if (seen.count(name) == 0) { bFail = true; LOG(LIB_ERROR) << "Unknown parameter: '" << name << "'"; } } if (bFail) throw runtime_error("Unknown parameters found!"); } const AnyParams& GetAllParams() const { return params; } void copySeen(AnyParamManager& other) { for (const string& s: seen) other.seen.insert(s); } private: const AnyParams& params; set<string> seen; template <typename ParamType> void GetParam(const string& Name, ParamType& Value, bool bRequired) { bool bFound = false; /* * This loop is reasonably efficient, unless * we have thousands of parameters (which realistically won't happen) */ for (size_t i =0; i < params.ParamNames.size(); ++i) if (Name == params.ParamNames[i]) { bFound = true; ConvertStrToValue<ParamType>(params.ParamValues[i], Value); } if (bFound) { seen.insert(Name); } if (!bFound) { if (bRequired) { stringstream err; err << "Mandatory parameter: '" << Name << "' is missing!"; LOG(LIB_ERROR) << err.str(); throw runtime_error(err.str()); } } } template <typename ParamType> void ConvertStrToValue(const string& s, ParamType& Value); }; template <typename ParamType> inline void AnyParamManager::ConvertStrToValue(const string& s, ParamType& Value) { stringstream str(s); if (!(str>>Value) || !str.eof()) { stringstream err; err << "Failed to convert value '" << s << "' from type: " << typeid(Value).name(); LOG(LIB_ERROR) << err.str(); throw runtime_error(err.str()); } } template <> inline void AnyParamManager::ConvertStrToValue<string>(const string& str, string& Value) { Value = str; } // Parse space name/parameters void ParseSpaceArg(const string& str, string& SpaceType, vector<string>& SpaceDesc); // Take a comma-separated list of parameters and split them. void ParseArg(const string& str, vector<string>& vDesc); }; #endif
28.26875
106
0.630776
[ "vector" ]
ea9ec29b43784a2e8b7f6213763784b930a2f8ca
1,800
h
C
Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/include/openfl/_v2/utils/Float32Array.h
as3boyan/Uber-Duper-Simulation
a3942831a1acf08479f06fd8cfe8896ec00ac32c
[ "MIT" ]
null
null
null
Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/include/openfl/_v2/utils/Float32Array.h
as3boyan/Uber-Duper-Simulation
a3942831a1acf08479f06fd8cfe8896ec00ac32c
[ "MIT" ]
null
null
null
Uber_Duper_Simulation_Haxe/bin/windows/cpp/obj/include/openfl/_v2/utils/Float32Array.h
as3boyan/Uber-Duper-Simulation
a3942831a1acf08479f06fd8cfe8896ec00ac32c
[ "MIT" ]
null
null
null
#ifndef INCLUDED_openfl__v2_utils_Float32Array #define INCLUDED_openfl__v2_utils_Float32Array #ifndef HXCPP_H #include <hxcpp.h> #endif #include <openfl/_v2/utils/ArrayBufferView.h> HX_DECLARE_CLASS3(openfl,_v2,utils,ArrayBufferView) HX_DECLARE_CLASS3(openfl,_v2,utils,Float32Array) HX_DECLARE_CLASS3(openfl,_v2,utils,IMemoryRange) HX_DECLARE_CLASS2(openfl,geom,Matrix3D) namespace openfl{ namespace _v2{ namespace utils{ class HXCPP_CLASS_ATTRIBUTES Float32Array_obj : public ::openfl::_v2::utils::ArrayBufferView_obj{ public: typedef ::openfl::_v2::utils::ArrayBufferView_obj super; typedef Float32Array_obj OBJ_; Float32Array_obj(); Void __construct(Dynamic bufferOrArray,hx::Null< int > __o_start,Dynamic elements); public: inline void *operator new( size_t inSize, bool inContainer=true) { return hx::Object::operator new(inSize,inContainer); } static hx::ObjectPtr< Float32Array_obj > __new(Dynamic bufferOrArray,hx::Null< int > __o_start,Dynamic elements); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~Float32Array_obj(); HX_DO_RTTI; static void __boot(); static void __register(); ::String __ToString() const { return HX_CSTRING("Float32Array"); } typedef Float __array_access; int BYTES_PER_ELEMENT; int length; virtual Void __setLength( int nbFloat); Dynamic __setLength_dyn(); virtual Float __get( int index); Dynamic __get_dyn(); virtual Void __set( int index,Float value); Dynamic __set_dyn(); static int SBYTES_PER_ELEMENT; static ::openfl::_v2::utils::Float32Array fromMatrix( ::openfl::geom::Matrix3D matrix); static Dynamic fromMatrix_dyn(); }; } // end namespace openfl } // end namespace _v2 } // end namespace utils #endif /* INCLUDED_openfl__v2_utils_Float32Array */
29.508197
116
0.772222
[ "object" ]
eaa5e24287c5030346feb8bd1194eddba81255e2
3,468
h
C
libraries/libgraphic/Painter.h
jimil749/skift
7e84726ddc99bcb72175914cfc7f271e953cfc9c
[ "MIT" ]
null
null
null
libraries/libgraphic/Painter.h
jimil749/skift
7e84726ddc99bcb72175914cfc7f271e953cfc9c
[ "MIT" ]
null
null
null
libraries/libgraphic/Painter.h
jimil749/skift
7e84726ddc99bcb72175914cfc7f271e953cfc9c
[ "MIT" ]
null
null
null
#pragma once #include <libgraphic/Bitmap.h> #include <libgraphic/Font.h> #include <libgraphic/Icon.h> #include <libgraphic/TrueTypeFont.h> #include <libgraphic/vector/Path.h> #include <libsystem/algebra/Trans2.h> #define STATESTACK_SIZE 32 struct PainterState { Vec2i origine; Rectangle clip; }; class Painter { private: RefPtr<Bitmap> _bitmap; int _state_stack_top = 0; PainterState _state_stack[STATESTACK_SIZE]; public: Painter(RefPtr<Bitmap> bitmap); void push(); void pop(); void clip(Rectangle rectangle); void transform(Vec2i offset); void plot_pixel(Vec2i position, Color color); void blit_bitmap(Bitmap &bitmap, Rectangle source, Rectangle destination); void blit_bitmap_no_alpha(Bitmap &bitmap, Rectangle source, Rectangle destination); void blit_icon(Icon &icon, IconSize size, Rectangle destination, Color color); void clear(Color color); void clear_rectangle(Rectangle rectangle, Color color); void fill_rectangle(Rectangle rectangle, Color color); void fill_insets(Rectangle rectangle, Insets insets, Color color); void fill_triangle(Vec2i p0, Vec2i p1, Vec2i p2, Color color); void fill_rounded_rectangle(Rectangle bound, int radius, Color color); void fill_checkboard(Rectangle bound, int cell_size, Color fg_color, Color bg_color); void draw_line(Vec2i from, Vec2i to, Color color); void draw_line_antialias(Vec2i from, Vec2i to, Color color); void draw_rectangle(Rectangle rectangle, Color color); void draw_triangle(Vec2i p0, Vec2i p1, Vec2i p2, Color color); void draw_path(const graphic::Path &path, Vec2f pos, Trans2f transform, Color color); void draw_rounded_rectangle(Rectangle bound, int radius, int thickness, Color color); void draw_glyph(Font &font, Glyph &glyph, Vec2i position, Color color); void draw_string(Font &font, const char *str, Vec2i position, Color color); void draw_string_within(Font &font, const char *str, Rectangle container, Position position, Color color); void draw_truetype_glyph(TrueTypeFont *font, TrueTypeGlyph *glyph, Vec2i position, Color color); void draw_truetype_string(TrueTypeFont *font, const char *string, Vec2i position, Color color); void draw_truetype_string_within(TrueTypeFont *font, const char *str, Rectangle container, Position position, Color color); void blur_rectangle(Rectangle rectangle, int radius); private: Rectangle clip() { return _state_stack[_state_stack_top].clip; } Vec2i origine() { return _state_stack[_state_stack_top].origine; }; Rectangle apply_clip(Rectangle rectangle); Rectangle apply_transform(Rectangle rectangle); void blit_bitmap_fast(Bitmap &bitmap, Rectangle source, Rectangle destination); void blit_bitmap_scaled(Bitmap &bitmap, Rectangle source, Rectangle destination); void blit_bitmap_fast_no_alpha(Bitmap &bitmap, Rectangle source, Rectangle destination); void blit_bitmap_scaled_no_alpha(Bitmap &bitmap, Rectangle source, Rectangle destination); void draw_line_x_aligned(int x, int start, int end, Color color); void draw_line_y_aligned(int y, int start, int end, Color color); void draw_line_not_aligned(Vec2i a, Vec2i b, Color color); void blit_bitmap_colored(Bitmap &src, Rectangle src_rect, Rectangle dst_rect, Color color); void draw_circle_helper(Rectangle bound, Vec2i center, int radius, int thickness, Color color); };
31.243243
127
0.752884
[ "vector", "transform" ]
eaaf30acdb08fdbbdfd5e45fce4cc4fc7159b172
20,352
c
C
dlls/wineqtdecoder/qtvdecoder.c
maolin-sen/wine
c3165b4c96a021a96dc6dd8a0b8e1030682dd6e5
[ "MIT" ]
null
null
null
dlls/wineqtdecoder/qtvdecoder.c
maolin-sen/wine
c3165b4c96a021a96dc6dd8a0b8e1030682dd6e5
[ "MIT" ]
null
null
null
dlls/wineqtdecoder/qtvdecoder.c
maolin-sen/wine
c3165b4c96a021a96dc6dd8a0b8e1030682dd6e5
[ "MIT" ]
null
null
null
/* * QuickTime Toolkit decoder filter for video * * Copyright 2010 Aric Stewart, CodeWeavers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include "config.h" #define ULONG CoreFoundation_ULONG #define HRESULT CoreFoundation_HRESULT #define LoadResource __carbon_LoadResource #define CompareString __carbon_CompareString #define GetCurrentThread __carbon_GetCurrentThread #define GetCurrentProcess __carbon_GetCurrentProcess #define AnimatePalette __carbon_AnimatePalette #define EqualRgn __carbon_EqualRgn #define FillRgn __carbon_FillRgn #define FrameRgn __carbon_FrameRgn #define GetPixel __carbon_GetPixel #define InvertRgn __carbon_InvertRgn #define LineTo __carbon_LineTo #define OffsetRgn __carbon_OffsetRgn #define PaintRgn __carbon_PaintRgn #define Polygon __carbon_Polygon #define ResizePalette __carbon_ResizePalette #define SetRectRgn __carbon_SetRectRgn #define CheckMenuItem __carbon_CheckMenuItem #define DeleteMenu __carbon_DeleteMenu #define DrawMenuBar __carbon_DrawMenuBar #define EnableMenuItem __carbon_EnableMenuItem #define EqualRect __carbon_EqualRect #define FillRect __carbon_FillRect #define FrameRect __carbon_FrameRect #define GetCursor __carbon_GetCursor #define GetMenu __carbon_GetMenu #define InvertRect __carbon_InvertRect #define IsWindowVisible __carbon_IsWindowVisible #define MoveWindow __carbon_MoveWindow #define OffsetRect __carbon_OffsetRect #define PtInRect __carbon_PtInRect #define SetCursor __carbon_SetCursor #define SetRect __carbon_SetRect #define ShowCursor __carbon_ShowCursor #define ShowWindow __carbon_ShowWindow #define UnionRect __carbon_UnionRect #include <QuickTime/ImageCompression.h> #include <CoreVideo/CVPixelBuffer.h> #undef LoadResource #undef CompareString #undef GetCurrentThread #undef _CDECL #undef GetCurrentProcess #undef AnimatePalette #undef EqualRgn #undef FillRgn #undef FrameRgn #undef GetPixel #undef InvertRgn #undef LineTo #undef OffsetRgn #undef PaintRgn #undef Polygon #undef ResizePalette #undef SetRectRgn #undef CheckMenuItem #undef DeleteMenu #undef DrawMenuBar #undef EnableMenuItem #undef EqualRect #undef FillRect #undef FrameRect #undef GetCursor #undef GetMenu #undef InvertRect #undef IsWindowVisible #undef MoveWindow #undef OffsetRect #undef PtInRect #undef SetCursor #undef SetRect #undef ShowCursor #undef ShowWindow #undef UnionRect #undef ULONG #undef HRESULT #undef STDMETHODCALLTYPE #define COBJMACROS #include "windef.h" #include "winbase.h" #include "wtypes.h" #include "winuser.h" #include "dshow.h" #include "uuids.h" #include "amvideo.h" #include "strmif.h" #include "vfwmsgs.h" #include "vfw.h" #include "dvdmedia.h" #include <assert.h> #include "wine/unicode.h" #include "wine/debug.h" #include "wine/strmbase.h" #include "qtprivate.h" #include "wineqtdecoder_classes.h" extern CLSID CLSID_QTVDecoder; WINE_DEFAULT_DEBUG_CHANNEL(qtdecoder); typedef struct QTVDecoderImpl { struct strmbase_filter filter; CRITICAL_SECTION stream_cs; struct strmbase_source source; IUnknown *seeking; struct strmbase_sink sink; ImageDescriptionHandle hImageDescription; CFMutableDictionaryRef outputBufferAttributes; ICMDecompressionSessionRef decompressionSession; HRESULT decodeHR; DWORD outputSize; } QTVDecoderImpl; static inline QTVDecoderImpl *impl_from_strmbase_filter(struct strmbase_filter *iface) { return CONTAINING_RECORD(iface, QTVDecoderImpl, filter); } static HRESULT video_decoder_sink_query_interface(struct strmbase_pin *iface, REFIID iid, void **out) { QTVDecoderImpl *filter = impl_from_strmbase_filter(iface->filter); if (IsEqualGUID(iid, &IID_IMemInputPin)) *out = &filter->sink.IMemInputPin_iface; else return E_NOINTERFACE; IUnknown_AddRef((IUnknown *)*out); return S_OK; } static HRESULT video_decoder_sink_query_accept(struct strmbase_pin *iface, const AM_MEDIA_TYPE *mt) { return S_OK; } static void trackingCallback( void *decompressionTrackingRefCon, OSStatus result, ICMDecompressionTrackingFlags decompressionTrackingFlags, CVPixelBufferRef pixelBuffer, TimeValue64 displayTime, TimeValue64 displayDuration, ICMValidTimeFlags validTimeFlags, void *reserved, void *sourceFrameRefCon ) { QTVDecoderImpl *This = (QTVDecoderImpl*)decompressionTrackingRefCon; IMediaSample *pSample = (IMediaSample*)sourceFrameRefCon; HRESULT hr = S_OK; IMediaSample* pOutSample = NULL; LPBYTE pbDstStream; DWORD cbDstStream; if (result != noErr) { ERR("Error from Codec, no frame decompressed\n"); return; } if (!pixelBuffer) { ERR("No pixel buffer, no frame decompressed\n"); return; } EnterCriticalSection(&This->stream_cs); hr = BaseOutputPinImpl_GetDeliveryBuffer(&This->source, &pOutSample, NULL, NULL, 0); if (FAILED(hr)) { ERR("Unable to get delivery buffer (%x)\n", hr); goto error; } hr = IMediaSample_SetActualDataLength(pOutSample, 0); assert(hr == S_OK); hr = IMediaSample_GetPointer(pOutSample, &pbDstStream); if (FAILED(hr)) { ERR("Unable to get pointer to buffer (%x)\n", hr); goto error; } cbDstStream = IMediaSample_GetSize(pOutSample); if (cbDstStream < This->outputSize) { ERR("Sample size is too small %d < %d\n", cbDstStream, This->outputSize); hr = E_FAIL; goto error; } hr = AccessPixelBufferPixels(pixelBuffer, pbDstStream); if (FAILED(hr)) goto error; IMediaSample_SetActualDataLength(pOutSample, This->outputSize); IMediaSample_SetPreroll(pOutSample, (IMediaSample_IsPreroll(pSample) == S_OK)); IMediaSample_SetDiscontinuity(pOutSample, (IMediaSample_IsDiscontinuity(pSample) == S_OK)); IMediaSample_SetSyncPoint(pOutSample, (IMediaSample_IsSyncPoint(pSample) == S_OK)); if (!validTimeFlags) IMediaSample_SetTime(pOutSample, NULL, NULL); else { LONGLONG tStart, tStop; if (validTimeFlags & kICMValidTime_DisplayTimeStampIsValid) tStart = displayTime; else tStart = 0; if (validTimeFlags & kICMValidTime_DisplayDurationIsValid) tStop = tStart + displayDuration; else tStop = tStart; IMediaSample_SetTime(pOutSample, &tStart, &tStop); } hr = IMemInputPin_Receive(This->source.pMemInputPin, pOutSample); if (hr != S_OK && hr != VFW_E_NOT_CONNECTED) ERR("Error sending sample (%x)\n", hr); error: LeaveCriticalSection(&This->stream_cs); if (pOutSample) IMediaSample_Release(pOutSample); This->decodeHR = hr; } static HRESULT WINAPI video_decoder_Receive(struct strmbase_sink *iface, IMediaSample *pSample) { QTVDecoderImpl *This = impl_from_strmbase_filter(iface->pin.filter); HRESULT hr; DWORD cbSrcStream; LPBYTE pbSrcStream; ICMFrameTimeRecord frameTime = {{0}}; TimeValue time = 1; TimeScale timeScale = 1; OSStatus err = noErr; LONGLONG tStart, tStop; EnterCriticalSection(&This->stream_cs); hr = IMediaSample_GetPointer(pSample, &pbSrcStream); if (FAILED(hr)) { ERR("Cannot get pointer to sample data (%x)\n", hr); goto error; } cbSrcStream = IMediaSample_GetActualDataLength(pSample); if (IMediaSample_GetTime(pSample, &tStart, &tStop) != S_OK) tStart = tStop = 0; time = tStart; frameTime.recordSize = sizeof(ICMFrameTimeRecord); *(TimeValue64 *)&frameTime.value = tStart; frameTime.scale = 1; frameTime.rate = fixed1; frameTime.duration = tStop - tStart; frameTime.frameNumber = 0; frameTime.flags = icmFrameTimeIsNonScheduledDisplayTime; err = ICMDecompressionSessionDecodeFrame(This->decompressionSession, (UInt8 *)pbSrcStream, cbSrcStream, NULL, &frameTime, pSample); if (err != noErr) { ERR("Error with ICMDecompressionSessionDecodeFrame\n"); hr = E_FAIL; goto error; } ICMDecompressionSessionSetNonScheduledDisplayTime(This->decompressionSession, time, timeScale, 0); ICMDecompressionSessionFlush(This->decompressionSession); hr = This->decodeHR; error: LeaveCriticalSection(&This->stream_cs); return hr; } static HRESULT video_decoder_sink_connect(struct strmbase_sink *iface, IPin *peer, const AM_MEDIA_TYPE *pmt) { QTVDecoderImpl *This = impl_from_strmbase_filter(iface->pin.filter); HRESULT hr = VFW_E_TYPE_NOT_ACCEPTED; OSErr err = noErr; AM_MEDIA_TYPE *outpmt = &This->mt; CFNumberRef n = NULL; FreeMediaType(outpmt); CopyMediaType(outpmt, pmt); if (This->hImageDescription) DisposeHandle((Handle)This->hImageDescription); This->hImageDescription = (ImageDescriptionHandle) NewHandleClear(sizeof(ImageDescription)); if (This->hImageDescription != NULL) { (**This->hImageDescription).idSize = sizeof(ImageDescription); (**This->hImageDescription).spatialQuality = codecNormalQuality; (**This->hImageDescription).frameCount = 1; (**This->hImageDescription).clutID = -1; } else { ERR("Failed to create ImageDescription\n"); goto failed; } /* Check root (GUID w/o FOURCC) */ if ((IsEqualIID(&pmt->majortype, &MEDIATYPE_Video)) && (!memcmp(((const char *)&pmt->subtype)+4, ((const char *)&MEDIATYPE_Video)+4, sizeof(GUID)-4))) { VIDEOINFOHEADER *format1 = (VIDEOINFOHEADER *)outpmt->pbFormat; VIDEOINFOHEADER2 *format2 = (VIDEOINFOHEADER2 *)outpmt->pbFormat; BITMAPINFOHEADER *bmi; OSType fourCC; DecompressorComponent dc; OSType format; DWORD outputWidth, outputHeight, outputDepth; if (IsEqualIID(&pmt->formattype, &FORMAT_VideoInfo)) bmi = &format1->bmiHeader; else if (IsEqualIID(&pmt->formattype, &FORMAT_VideoInfo2)) bmi = &format2->bmiHeader; else goto failed; TRACE("Fourcc: %s\n", debugstr_an((const char *)&pmt->subtype.Data1, 4)); fourCC = ((const char *)&pmt->subtype.Data1)[3] | (((const char *)&pmt->subtype.Data1)[2]<<8) | (((const char *)&pmt->subtype.Data1)[1]<<16) | (((const char *)&pmt->subtype.Data1)[0]<<24); err = FindCodec(fourCC,NULL,NULL,&dc); if (err != noErr || dc == 0x0) { TRACE("Codec not found\n"); goto failed; } outputWidth = bmi->biWidth; outputHeight = bmi->biHeight; (**This->hImageDescription).cType = fourCC; (**This->hImageDescription).width = outputWidth; (**This->hImageDescription).height = outputHeight; (**This->hImageDescription).depth = bmi->biBitCount; (**This->hImageDescription).hRes = 72<<16; (**This->hImageDescription).vRes = 72<<16; if (This->outputBufferAttributes) CFRelease(This->outputBufferAttributes); This->outputBufferAttributes = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (!This->outputBufferAttributes) { ERR("Failed to create outputBufferAttributes\n"); goto failed; } n = CFNumberCreate(NULL, kCFNumberIntType, &outputWidth); CFDictionaryAddValue(This->outputBufferAttributes, kCVPixelBufferWidthKey, n); CFRelease(n); n = CFNumberCreate(NULL, kCFNumberIntType, &outputHeight); CFDictionaryAddValue(This->outputBufferAttributes, kCVPixelBufferHeightKey, n); CFRelease(n); /* yes this looks wrong. but 32ARGB is 24 RGB with an alpha channel */ format = k32ARGBPixelFormat; n = CFNumberCreate(NULL, kCFNumberIntType, &format); CFDictionaryAddValue(This->outputBufferAttributes, kCVPixelBufferPixelFormatTypeKey, n); CFRelease(n); CFDictionaryAddValue(This->outputBufferAttributes, kCVPixelBufferCGBitmapContextCompatibilityKey, kCFBooleanTrue); CFDictionaryAddValue(This->outputBufferAttributes, kCVPixelBufferCGImageCompatibilityKey, kCFBooleanTrue); outputDepth = 3; This->outputSize = outputWidth * outputHeight * outputDepth; bmi->biCompression = BI_RGB; bmi->biBitCount = 24; outpmt->subtype = MEDIASUBTYPE_RGB24; return S_OK; } failed: if (This->hImageDescription) { DisposeHandle((Handle)This->hImageDescription); This->hImageDescription = NULL; } if (This->outputBufferAttributes) { CFRelease(This->outputBufferAttributes); This->outputBufferAttributes = NULL; } TRACE("Connection refused\n"); return hr; } static void video_decoder_sink_disconnect(struct strmbase_sink *iface) { QTVDecoderImpl *This = impl_from_strmbase_filter(iface->pin.filter); if (This->hImageDescription) DisposeHandle((Handle)This->hImageDescription); if (This->outputBufferAttributes) CFRelease(This->outputBufferAttributes); This->hImageDescription = NULL; This->outputBufferAttributes = NULL; } static const struct strmbase_sink_ops sink_ops = { .base.pin_query_interface = video_decoder_sink_query_interface, .base.pin_query_accept = video_decoder_sink_query_accept, .base.pin_get_media_type = strmbase_pin_get_media_type, .pfnReceive = video_decoder_sink_Receive, .sink_connect = video_decoder_sink_connect, .sink_disconnect = video_decoder_sink_disconnect, }; static HRESULT video_decoder_source_query_interface(struct strmbase_pin *iface, REFIID iid, void **out) { QTVDecoderImpl *filter = impl_from_strmbase_filter(iface->filter); if (IsEqualGUID(iid, &IID_IMediaSeeking)) return IUnknown_QueryInterface(filter->seeking, iid, out); else return E_NOINTERFACE; IUnknown_AddRef((IUnknown *)*out); return S_OK; } static HRESULT video_decoder_source_query_accept(struct strmbase_pin *iface, const AM_MEDIA_TYPE *mt) { QTVDecoderImpl *filter = impl_from_strmbase_filter(iface->filter); if (IsEqualGUID(&mt->majortype, &filter->mt.majortype) && (IsEqualGUID(&mt->subtype, &filter->mt.subtype) || IsEqualGUID(&filter->mt.subtype, &GUID_NULL))) return S_OK; return S_FALSE; } static HRESULT video_decoder_source_get_media_type(struct strmbase_pin *iface, unsigned int index, AM_MEDIA_TYPE *mt) { QTVDecoderImpl *filter = impl_from_strmbase_filter(iface->filter); if (index) return VFW_S_NO_MORE_ITEMS; CopyMediaType(mt, &filter->mt); return S_OK; } static HRESULT WINAPI video_decoder_DecideBufferSize(struct strmbase_source *iface, IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *ppropInputRequest) { QTVDecoderImpl *This = impl_from_strmbase_filter(iface->pin.filter); ALLOCATOR_PROPERTIES actual; if (!ppropInputRequest->cbAlign) ppropInputRequest->cbAlign = 1; if (ppropInputRequest->cbBuffer < This->outputSize) ppropInputRequest->cbBuffer = This->outputSize + ppropInputRequest->cbAlign; if (!ppropInputRequest->cBuffers) ppropInputRequest->cBuffers = 1; return IMemAllocator_SetProperties(pAlloc, ppropInputRequest, &actual); } static const struct strmbase_source_ops source_ops = { .base.pin_query_interface = video_decoder_source_query_interface, .base.pin_query_accept = video_decoder_source_query_accept, .base.pin_get_media_type = video_decoder_source_get_media_type, .pfnAttemptConnection = BaseOutputPinImpl_AttemptConnection, .pfnDecideAllocator = BaseOutputPinImpl_DecideAllocator, .pfnDecideBufferSize = video_decoder_source_DecideBufferSize, }; static struct strmbase_pin *video_decoder_get_pin(struct strmbase_filter *iface, unsigned int index) { QTVDecoderImpl *filter = impl_from_strmbase_filter(iface); if (index == 0) return &filter->sink.pin; else if (index == 1) return &filter->source.pin; return NULL; } static void video_decoder_destroy(struct strmbase_filter *iface) { QTVDecoderImpl *filter = impl_from_strmbase_filter(iface); if (filter->sink.pin.peer) IPin_Disconnect(filter->sink.pin.peer); IPin_Disconnect(&filter->sink.pin.IPin_iface); if (filter->source.pin.peer) IPin_Disconnect(filter->source.pin.peer); IPin_Disconnect(&filter->source.pin.IPin_iface); strmbase_sink_cleanup(&filter->sink); strmbase_source_cleanup(&filter->source); filter->stream_cs.DebugInfo->Spare[0] = 0; DeleteCriticalSection(&filter->stream_cs); FreeMediaType(&filter->mt); IUnknown_Release(filter->seeking); strmbase_filter_cleanup(&filter->filter); free(filter); } static HRESULT video_decoder_init_stream(struct strmbase_filter *iface) { QTVDecoderImpl *This = impl_from_strmbase_filter(iface); OSErr err = noErr; ICMDecompressionSessionOptionsRef sessionOptions = NULL; ICMDecompressionTrackingCallbackRecord trackingCallbackRecord; trackingCallbackRecord.decompressionTrackingCallback = trackingCallback; trackingCallbackRecord.decompressionTrackingRefCon = (void*)This; err = ICMDecompressionSessionCreate(NULL, This->hImageDescription, sessionOptions, This->outputBufferAttributes, &trackingCallbackRecord, &This->decompressionSession); if (err != noErr) { ERR("Error with ICMDecompressionSessionCreate %i\n",err); return E_FAIL; } return BaseOutputPinImpl_Active(&This->source); } static HRESULT video_decoder_cleanup_stream(struct strmbase_filter *iface) { QTVDecoderImpl* This = impl_from_TransformFilter(pTransformFilter); if (This->decompressionSession) ICMDecompressionSessionRelease(This->decompressionSession); This->decompressionSession = NULL; return BaseOutputPinImpl_Inactive(&This->source); } static const struct strmbase_filter_ops filter_ops = { .filter_get_pin = video_decoder_get_pin, .filter_destroy = video_decoder_destroy, .filter_init_stream = video_decoder_init_stream, .filter_cleanup_stream = video_decoder_cleanup_stream, }; HRESULT video_decoder_create(IUnknown *outer, IUnknown **out) { QTVDecoderImpl *object; HRESULT hr; if (!(object = calloc(1, sizeof(*object)))) return E_OUTOFMEMORY; strmbase_filter_init(&object->filter, outer, &CLSID_QTVDecoder, &filter_ops); InitializeCriticalSection(&object->stream_cs); object->stream_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__": QTVDecoderImpl.stream_cs"); strmbase_sink_init(&object->sink, &object->filter, L"In", &sink_ops, NULL); strmbase_source_init(&object->source, &object->filter, L"Out", &source_ops); if (FAILED(hr = CoCreateInstance(&CLSID_SeekingPassThru, (IUnknown *)&object->source.pin.IPin_iface, CLSCTX_INPROC_SERVER, &IID_IUnknown, (void **)&object->seeking))) { strmbase_sink_cleanup(&object->sink); strmbase_source_cleanup(&object->source); strmbase_filter_cleanup(&object->filter); free(object); return hr; } IUnknown_QueryInterface(object->seeking, &IID_ISeekingPassThru, (void **)&passthrough); ISeekingPassThru_Init(passthrough, FALSE, &object->sink.pin.IPin_iface); ISeekingPassThru_Release(passthrough); TRACE("Created video decoder %p.\n", object); *out = &object->tf.filter.IUnknown_inner; return S_OK; }
31.504644
171
0.714475
[ "object" ]
eab05c79d46e3102098cffe14850788e0a35141d
2,596
h
C
src/services/durability/code/d__conflictMonitor.h
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
133
2017-11-09T02:10:00.000Z
2022-03-29T09:45:10.000Z
src/services/durability/code/d__conflictMonitor.h
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
131
2017-11-07T14:48:43.000Z
2022-03-13T15:30:47.000Z
src/services/durability/code/d__conflictMonitor.h
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
94
2017-11-09T02:26:19.000Z
2022-02-24T06:38:25.000Z
/* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to TO_YEAR ADLINK * Technology Limited, its affiliated companies and licensors. All rights * reserved. * * Licensed under the ADLINK Software License Agreement Rev 2.7 2nd October * 2014 (the "License"); you may not use this file except in compliance with * the License. * You may obtain a copy of the License at: * $OSPL_HOME/LICENSE * * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef D__CONFLICT_MONITOR_H #define D__CONFLICT_MONITOR_H #include "d__types.h" #include "d__conflict.h" #include "d__admin.h" #include "os_time.h" #if defined (__cplusplus) extern "C" { #endif /** * Macro that checks the d_conflictMonitor validity. * Because d_conflictMonitor is a concrete class typechecking is required. */ #define d_conflictMonitorIsValid(_this) \ d_objectIsValid(d_object(_this), D_CONFLICT_MONITOR) /** * \brief The <code>d_conflictMonitor</code> cast macro. * * This macro casts an object to a <code>d_conflictMonitor</code> object. */ #define d_conflictMonitor(_this) ((d_conflictMonitor)(_this)) C_STRUCT(d_conflictMonitor) { C_EXTENDS(d_lock); os_timeM lastTimeChecked; d_admin admin; }; d_conflictMonitor d_conflictMonitorNew (d_admin admin); void d_conflictMonitorDeinit (d_conflictMonitor conflictMonitor); void d_conflictMonitorFree (d_conflictMonitor conflictMonitor); void d_conflictMonitorCheckForConflicts (d_conflictMonitor conflictMonitor, d_fellow fellow, d_nameSpace nameSpace); void d_conflictMonitorCheckFellowDisconnected (d_conflictMonitor conflictMonitor, d_fellow fellow); void d_conflictMonitorCheckFellowConnected (d_conflictMonitor conflictMonitor, d_fellow fellow); void d_conflictMonitorCheckFederationDisconnected(d_conflictMonitor conflictMonitor); d_conflict d_conflictMonitorEvaluateConflict (d_conflictMonitor conflictMonitor, d_conflict conflict); #if defined (__cplusplus) } #endif #endif /* D__CONFLICT_MONITOR_H */
32.049383
99
0.628659
[ "object" ]
eab6d894ca803dce284bb66fbb8bd6caf0900dad
18,223
h
C
code/type_objid.h
kkouptsov/C-plus-plus-ASN.1-2008-coder-decoder
3b439b2803251b67d0378f656c0eb916a9343945
[ "BSD-2-Clause" ]
20
2016-02-12T06:21:02.000Z
2021-04-25T21:40:38.000Z
code/type_objid.h
kkouptsov/C-plus-plus-ASN.1-2008-coder-decoder
3b439b2803251b67d0378f656c0eb916a9343945
[ "BSD-2-Clause" ]
2
2017-05-18T13:27:50.000Z
2022-01-20T22:12:44.000Z
code/type_objid.h
kkouptsov/C-plus-plus-ASN.1-2008-coder-decoder
3b439b2803251b67d0378f656c0eb916a9343945
[ "BSD-2-Clause" ]
3
2019-05-06T15:32:55.000Z
2022-01-02T15:23:08.000Z
/* * Copyright (c) 2012 Yury Strozhevsky <www.strozhevsky.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _ABF41DE2_8824_46AE_94CE_552B79A68D99 #define _ABF41DE2_8824_46AE_94CE_552B79A68D99 //************************************************************************** template< typename In, typename Out > struct SID_value_block : virtual public hex_block_type< In, Out > { unsigned long long value_dec; bool is_first_sid; SID_value_block(); virtual std::string block_name(); virtual MSXML2::IXMLDOMElementPtr to_xml( MSXML2::IXMLDOMDocumentPtr pDoc ); virtual bool from_xml( MSXML2::IXMLDOMElementPtr element ); virtual In decode_BER( unsigned long long max_block_len ); virtual unsigned long long encode_BER( bool size_only = false ); }; //************************************************************************** template< typename In, typename Out > SID_value_block< In, Out >::SID_value_block() : value_dec( 0 ), is_first_sid( false ) { } //************************************************************************** template< typename In, typename Out > std::string SID_value_block< In, Out >::block_name() { return "sid_block"; } //************************************************************************** template< typename In, typename Out > MSXML2::IXMLDOMElementPtr SID_value_block< In, Out >::to_xml( MSXML2::IXMLDOMDocumentPtr pDoc ) { MSXML2::IXMLDOMElementPtr result = block_type< In, Out >::to_xml( pDoc ); if( error[ 0 ] != 0x00 ) return result; if( !block_length ) return result; MSXML2::IXMLDOMElementPtr is_first_sid_xml = pDoc->createElement( L"is_first_sid" ); is_first_sid_xml->appendChild( pDoc->createTextNode( ( is_first_sid )? L"true" : L"false" ) ); result->appendChild( is_first_sid_xml ); MSXML2::IXMLDOMElementPtr is_hex_only_xml = pDoc->createElement( L"is_hex_only" ); is_hex_only_xml->appendChild( pDoc->createTextNode( ( is_hex_only )? L"true" : L"false" ) ); result->appendChild( is_hex_only_xml ); if( is_hex_only ) { std::string codes = hex_codes( value_hex, block_length ); wchar_t* whex = ( wchar_t* ) malloc( ( codes.length() + 1 ) * sizeof( wchar_t ) ); memset( whex, 0x00, ( codes.length() + 1 ) * sizeof( wchar_t ) ); size_t converted = 0; errno_t error_num = mbstowcs_s( &converted, whex, codes.length() + 1, codes.c_str(), codes.length() ); if( error_num ) { free( whex ); return result; } MSXML2::IXMLDOMElementPtr value_hex_xml = pDoc->createElement( L"value_hex" ); value_hex_xml->appendChild( pDoc->createTextNode( whex ) ); result->appendChild( value_hex_xml ); free( whex ); } else { wchar_t buf[255]; _ui64tow_s( value_dec, buf, 255, 10 ); MSXML2::IXMLDOMElementPtr value_dec_xml = pDoc->createElement( L"value_dec" ); value_dec_xml->appendChild( pDoc->createTextNode( buf ) ); result->appendChild( value_dec_xml ); } return result; } //************************************************************************** template< typename In, typename Out > bool SID_value_block< In, Out >::from_xml( MSXML2::IXMLDOMElementPtr element ) { if( !element ) return false; MSXML2::IXMLDOMElementPtr is_first_sid_xml = element->selectSingleNode( L"is_first_sid" ); if( !is_first_sid_xml ) return false; if( is_first_sid_xml->text == ( _bstr_t )L"true" ) is_first_sid = true; else { if( is_first_sid_xml->text == ( _bstr_t )L"false" ) is_first_sid = false; else return false; } MSXML2::IXMLDOMElementPtr is_hex_only_xml = element->selectSingleNode( L"is_hex_only" ); if( !is_hex_only_xml ) return false; if( is_hex_only_xml->text == ( _bstr_t )L"true" ) is_hex_only = true; else { if( is_hex_only_xml->text == ( _bstr_t )L"false" ) is_hex_only = false; else return false; } if( is_hex_only ) { MSXML2::IXMLDOMElementPtr value_hex_xml = element->selectSingleNode( L"value_hex" ); if( !value_hex_xml ) return false; std::wstring str_hex = ( wchar_t* ) value_hex_xml->text; str_hex = wreplace( str_hex.c_str(), L" ", L"" ); if( !from_whex_codes( str_hex.c_str(), str_hex.length(), &value_hex ) ) return false; block_length = str_hex.length() >> 1; } else { MSXML2::IXMLDOMElementPtr value_dec_xml = element->selectSingleNode( L"value_dec" ); if( !value_dec_xml ) return false; value_dec = _wtoi64( ( wchar_t* ) value_dec_xml->text ); if( errno && !value_dec ) return false; } return true; } //************************************************************************** template< typename In, typename Out > In SID_value_block< In, Out >::decode_BER( unsigned long long max_block_len ) { if( !max_block_len ) return stream_in; if( stream_in == In() ) { sprintf_s( error, 255, "End of input reached before message was fully decoded" ); return stream_in; } value_hex = ( unsigned char* ) malloc( ( size_t )max_block_len ); if( !value_hex ) return In(); In end = stream_in; unsigned char* data = value_hex; while( (unsigned char)(*end) & 0x80 ) { if( block_length > ( max_block_len - 1 ) ) { sprintf_s( error, 255, "End of input reached before message was fully decoded" ); return end; } *data = (unsigned char)(*end) & 0x7F; data++; end++; block_length++; if( end == In() ) { sprintf_s( error, 255, "End of input reached before message was fully decoded" ); return end; } } // The least octet if( end == In() ) { sprintf_s( error, 255, "End of input reached before message was fully decoded" ); return end; } *data = (unsigned char)(*end) & 0x7F; block_length++; end++; if( !value_hex[ 0 ] ) warnings.push_back( "Needlessly long format of SID encoding" ); if( block_length <= 8 ) from_base( value_hex, &value_dec, 7, ( unsigned char )block_length ); else { is_hex_only = true; warnings.push_back( "Too big SID for decoding, hex only" ); } return end; } //************************************************************************** template< typename In, typename Out > unsigned long long SID_value_block< In, Out >::encode_BER( bool size_only ) { if( is_hex_only ) { if( !size_only ) { for( unsigned long long i = 0; i < ( block_length - 1 ); i++ ) stream_out = value_hex[ i ] | 0x80; stream_out = value_hex[ block_length - 1 ]; } return block_length; } unsigned char* encoded; int size = to_base( value_dec, &encoded, 7 ); if( !size ) { sprintf_s( error, 255, "Error during encoding SID value" ); free( encoded ); return 0; } if( !size_only ) { for( int i = 0; i < ( size - 1 ); i++ ) stream_out = encoded[ i ] | 0x80; stream_out = encoded[ size - 1 ]; } free( encoded ); return size; } //************************************************************************** template< typename In, typename Out > struct OID_value_block : virtual public value_block_type< In, Out > { std::vector< SID_value_block< In, Out >* > value; virtual ~OID_value_block(); virtual MSXML2::IXMLDOMElementPtr to_xml( MSXML2::IXMLDOMDocumentPtr pDoc ); virtual bool from_xml( MSXML2::IXMLDOMElementPtr element ); virtual In decode_BER( unsigned long long max_block_len ); virtual unsigned long long encode_BER( bool size_only = false ); }; //************************************************************************** template< typename In, typename Out > OID_value_block< In, Out >::~OID_value_block() { for( std::vector< SID_value_block< In, Out >* >::iterator i = value.begin(); i != value.end(); i++ ) delete (*i); } //************************************************************************** template< typename In, typename Out > MSXML2::IXMLDOMElementPtr OID_value_block< In, Out >::to_xml( MSXML2::IXMLDOMDocumentPtr pDoc ) { MSXML2::IXMLDOMElementPtr result = block_type< In, Out >::to_xml( pDoc ); if( error[ 0 ] != 0x00 ) return result; std::string oid; MSXML2::IXMLDOMElementPtr sid_blocks_xml = pDoc->createElement( L"sid_blocks" ); bool is_hex_only = false; for( std::vector< SID_value_block< In, Out >* >::iterator i = value.begin(); i != value.end(); i++ ) { is_hex_only |= (*i)->is_hex_only; MSXML2::IXMLDOMElementPtr element = (*i)->to_xml( pDoc ); sid_blocks_xml->appendChild( element ); if( i != value.begin() ) oid += "."; if( (*i)->is_hex_only ) { char* buf = ( char* ) malloc( ( size_t ) ( (*i)->block_length + 1 ) ); if( !buf ) return result; memcpy( buf, (*i)->value_hex, ( size_t )(*i)->block_length ); buf[ (*i)->block_length ] = 0x00; std::string temp_oid = "{" + hex_codes( (*i)->value_hex, (*i)->block_length ) + "}"; if( (*i)->is_first_sid ) oid = "2.{" + temp_oid + " - 80}"; else oid += temp_oid; free( buf ); } else { unsigned long long sid = (*i)->value_dec; if( (*i)->is_first_sid ) { if( (*i)->value_dec <= 39 ) oid = "0."; else { if( (*i)->value_dec <= 79 ) { oid = "1."; sid -= 40; } else { oid = "2."; sid -= 80; } } } char buf[255]; _ui64toa_s( sid, buf, 255, 10 ); oid += buf; } } result->appendChild( sid_blocks_xml ); MSXML2::IXMLDOMElementPtr is_hex_only_xml = pDoc->createElement( L"is_hex_only" ); is_hex_only_xml->appendChild( pDoc->createTextNode( ( is_hex_only )? L"true" : L"false" ) ); result->appendChild( is_hex_only_xml ); wchar_t* whex = ( wchar_t* ) malloc( ( oid.length() + 1 ) * sizeof( wchar_t ) ); memset( whex, 0x00, ( oid.length() + 1 ) * sizeof( wchar_t ) ); size_t converted = 0; errno_t error_num = mbstowcs_s( &converted, whex, oid.length() + 1, oid.c_str(), oid.length() ); if( error_num ) { free( whex ); return NULL; } MSXML2::IXMLDOMElementPtr value_xml = pDoc->createElement( L"value_dec" ); value_xml->appendChild( pDoc->createTextNode( whex ) ); free( whex ); result->appendChild( value_xml ); return result; } //************************************************************************** template< typename In, typename Out > bool OID_value_block< In, Out >::from_xml( MSXML2::IXMLDOMElementPtr element ) { if( !element ) return false; bool is_hex_only = false; MSXML2::IXMLDOMElementPtr is_hex_only_xml = element->selectSingleNode( L"is_hex_only" ); if( !is_hex_only_xml ) return false; if( is_hex_only_xml->text == ( _bstr_t )L"true" ) is_hex_only = true; else { if( is_hex_only_xml->text == ( _bstr_t )L"false" ) is_hex_only = false; else return false; } if( is_hex_only ) { MSXML2::IXMLDOMNodeListPtr list = element->selectNodes( L"./sid_blocks/sid_block" ); for( int i = 0; i < list->length; i++ ) { SID_value_block< In, Out >* sid = new SID_value_block< In, Out >(); sid->from_xml( list->item[ i ] ); value.push_back( sid ); } return true; } MSXML2::IXMLDOMNodePtr value_dec_xml = element->selectSingleNode( L"value_dec" ); if( !value_dec_xml ) return false; std::wstring str_value = ( wchar_t* )value_dec_xml->firstChild->text; std::wstring sid; std::wstring::size_type pos1 = 0, pos2; bool flag = false; do { pos2 = str_value.find( L".", pos1 ); sid.assign( str_value, pos1, pos2 - pos1 ); pos1 = pos2 + 1; SID_value_block< In, Out >* sid_block = NULL; if( flag ) { sid_block = value[ 0 ]; unsigned long long plus = 0; switch( sid_block->value_dec ) { case 0: break; case 1: plus = 40; break; case 2: plus = 80; break; default: return false; } sid_block->value_dec = _wtoi64( sid.c_str() ) + plus; flag = false; } else { sid_block = new SID_value_block< In, Out >(); sid_block->value_dec = _wtoi64( sid.c_str() ); if( !value.size() ) { sid_block->is_first_sid = true; flag = true; } value.push_back( sid_block ); } }while( pos2 != std::wstring::npos ); return true; } //************************************************************************** template< typename In, typename Out > In OID_value_block< In, Out >::decode_BER( unsigned long long max_block_len ) { In end = stream_in; while( max_block_len ) { if( end == In() ) { sprintf_s( error, 255, "End of input reached before message was fully decoded" ); return end; } SID_value_block< In, Out >* sid_type = new SID_value_block< In, Out >(); sid_type->stream_in = end; end = sid_type->decode_BER( max_block_len ); if( sid_type->error[ 0 ] != 0x00 ) { block_length = 0; sprintf_s( error, 255, sid_type->error ); delete sid_type; return end; } if( !(value.size()) ) sid_type->is_first_sid = true; block_length += sid_type->block_length; max_block_len -= sid_type->block_length; value.push_back( sid_type ); if( end == In() ) break; } return end; } //************************************************************************** template< typename In, typename Out > unsigned long long OID_value_block< In, Out >::encode_BER( bool size_only ) { unsigned long long result = 0; unsigned long long encoded = 0; for( std::vector< SID_value_block< In, Out >* >::iterator i = value.begin(); i != value.end(); i++ ) { (*i)->stream_out = stream_out; encoded = (*i)->encode_BER( size_only ); if( !encoded ) { sprintf_s( error, 255, (*i)->error ); return 0; } result += encoded; } return result; } //************************************************************************** template< typename In, typename Out > struct OID_type : virtual public BASIC_type< In, Out > { OID_type(); static std::string block_name_static(); virtual std::string block_name(); }; //************************************************************************** template< typename In, typename Out > OID_type< In, Out >::OID_type() { tag_class = 1; tag_number = 6; value_block = new OID_value_block< In, Out >(); } //************************************************************************** template< typename In, typename Out > std::string OID_type< In, Out >::block_name_static() { return "OBJECT IDENTIFIER"; } //************************************************************************** template< typename In, typename Out > std::string OID_type< In, Out >::block_name() { return block_name_static(); } //************************************************************************** template< typename In, typename Out > struct ROID_value_block : virtual public OID_value_block< In, Out > { virtual In decode_BER( unsigned long long max_block_len ); }; //************************************************************************** template< typename In, typename Out > In ROID_value_block< In, Out >::decode_BER( unsigned long long max_block_len ) { In end = stream_in; while( max_block_len ) { if( end == In() ) { sprintf_s( error, 255, "End of input reached before message was fully decoded" ); return end; } SID_value_block< In, Out >* sid_type = new SID_value_block< In, Out >(); sid_type->stream_in = end; end = sid_type->decode_BER( max_block_len ); if( sid_type->error[ 0 ] != 0x00 ) { block_length = 0; sprintf_s( error, 255, sid_type->error ); delete sid_type; return end; } block_length += sid_type->block_length; max_block_len -= sid_type->block_length; value.push_back( sid_type ); if( end == In() ) break; } return end; } //************************************************************************** template< typename In, typename Out > struct ROID_type : virtual public BASIC_type< In, Out > { ROID_type(); static std::string block_name_static(); virtual std::string block_name(); }; //************************************************************************** template< typename In, typename Out > ROID_type< In, Out >::ROID_type() { tag_class = 1; tag_number = 13; value_block = new ROID_value_block< In, Out >(); } //************************************************************************** template< typename In, typename Out > std::string ROID_type< In, Out >::block_name_static() { return "RELATIVE OBJECT IDENTIFIER"; } //************************************************************************** template< typename In, typename Out > std::string ROID_type< In, Out >::block_name() { return block_name_static(); } //************************************************************************** #endif
27.652504
105
0.576469
[ "object", "vector" ]
eabcec2c66f78e53324ac328fb199a7f3333e7db
53,099
c
C
layer2/CoordSet.c
hryknkgw/pymolwin
4a1335e90497dbcbfa789f1285a7c1ad84a051f8
[ "CNRI-Python" ]
null
null
null
layer2/CoordSet.c
hryknkgw/pymolwin
4a1335e90497dbcbfa789f1285a7c1ad84a051f8
[ "CNRI-Python" ]
null
null
null
layer2/CoordSet.c
hryknkgw/pymolwin
4a1335e90497dbcbfa789f1285a7c1ad84a051f8
[ "CNRI-Python" ]
null
null
null
/* A* ------------------------------------------------------------------- B* This file contains source code for the PyMOL computer program C* copyright 1998-2000 by Warren Lyford Delano of DeLano Scientific. D* ------------------------------------------------------------------- E* It is unlawful to modify or remove this copyright notice. F* ------------------------------------------------------------------- G* Please see the accompanying LICENSE file for further information. H* ------------------------------------------------------------------- I* Additional authors of this source file include: -* -* -* Z* ------------------------------------------------------------------- */ #include"os_python.h" #include"os_predef.h" #include"os_std.h" #include"Base.h" #include"OOMac.h" #include"MemoryDebug.h" #include"Err.h" #include"Scene.h" #include"CoordSet.h" #include"Color.h" #include"PConv.h" #include"P.h" #include"Matrix.h" #include"Sphere.h" #include"Util.h" #include"Feedback.h" #include"RepWireBond.h" #include"RepCylBond.h" #include"RepDot.h" #include"RepMesh.h" #include"RepSphere.h" #include"RepRibbon.h" #include"RepCartoon.h" #include"RepSurface.h" #include"RepLabel.h" #include"RepNonbonded.h" #include"RepNonbondedSphere.h" #include"RepEllipsoid.h" #include"PyMOLGlobals.h" #include"PyMOLObject.h" static void CoordSetUpdate(CoordSet * I, int state); void CoordSetFree(CoordSet * I); void CoordSetRender(CoordSet * I, RenderInfo * info); void CoordSetEnumIndices(CoordSet * I); void CoordSetInvalidateRep(CoordSet * I, int type, int level); int CoordSetExtendIndices(CoordSet * I, int nAtom); void CoordSetAppendIndices(CoordSet * I, int offset); /*========================================================================*/ static char sATOM[] = "ATOM "; static char sHETATM[] = "HETATM"; int CoordSetValidateRefPos(CoordSet * I) { if(I->RefPos) { VLACheck(I->RefPos, RefPosType, I->NIndex); return true; } else { int ok = true && (I->RefPos = VLACalloc(RefPosType, I->NIndex)); if(ok) { int a; for(a = 0; a < I->NIndex; a++) { float *src = I->Coord + 3 * a; copy3f(src, I->RefPos[a].coord); I->RefPos[a].specified = true; } } return ok; } } /*========================================================================*/ int BondCompare(BondType * a, BondType * b) { register int ai0 = a->index[0]; register int bi0 = b->index[0]; if(ai0 == bi0) { register int ai1 = a->index[1]; register int bi1 = b->index[1]; if(ai1 == bi1) { return 0; } else if(ai1 > bi1) { return 1; } else { return -1; } } else if(ai0 > bi0) { return 1; } else { return -1; } } /*========================================================================*/ int BondInOrder(BondType * a, int b1, int b2) { return (BondCompare(a + b1, a + b2) <= 0); } int CoordSetFromPyList(PyMOLGlobals * G, PyObject * list, CoordSet ** cs) { #ifdef _PYMOL_NOPY return 0; #else CoordSet *I = NULL; PyObject *tmp; int ok = true; int ll = 0; if(*cs) { CoordSetFree(*cs); *cs = NULL; } if(list == Py_None) { /* allow None for CSet */ *cs = NULL; } else { if(ok) I = CoordSetNew(G); if(ok) ok = (I != NULL); if(ok) ok = (list != NULL); if(ok) ok = PyList_Check(list); if(ok) ll = PyList_Size(list); /* TO SUPPORT BACKWARDS COMPATIBILITY... Always check ll when adding new PyList_GetItem's */ if(ok) ok = PConvPyIntToInt(PyList_GetItem(list, 0), &I->NIndex); if(ok) ok = PConvPyIntToInt(PyList_GetItem(list, 1), &I->NAtIndex); if(ok) ok = PConvPyListToFloatVLA(PyList_GetItem(list, 2), &I->Coord); if(ok) ok = PConvPyListToIntVLA(PyList_GetItem(list, 3), &I->IdxToAtm); if(ok) { tmp = PyList_GetItem(list, 4); /* Discrete CSets don't have this */ if(tmp != Py_None) ok = PConvPyListToIntVLA(tmp, &I->AtmToIdx); } if(ok && (ll > 5)) ok = PConvPyStrToStr(PyList_GetItem(list, 5), I->Name, sizeof(WordType)); if(ok && (ll > 6)) ok = ObjectStateFromPyList(G, PyList_GetItem(list, 6), &I->State); if(ok && (ll > 7)) I->Setting = SettingNewFromPyList(G, PyList_GetItem(list, 7)); if(ok && (ll > 8)) ok = PConvPyListToLabPosVLA(PyList_GetItem(list, 8), &I->LabPos); if(!ok) { if(I) CoordSetFree(I); *cs = NULL; } else { *cs = I; } } return (ok); #endif } PyObject *CoordSetAsPyList(CoordSet * I) { #ifdef _PYMOL_NOPY return NULL; #else PyObject *result = NULL; if(I) { result = PyList_New(9); PyList_SetItem(result, 0, PyInt_FromLong(I->NIndex)); PyList_SetItem(result, 1, PyInt_FromLong(I->NAtIndex)); PyList_SetItem(result, 2, PConvFloatArrayToPyList(I->Coord, I->NIndex * 3)); PyList_SetItem(result, 3, PConvIntArrayToPyList(I->IdxToAtm, I->NIndex)); if(I->AtmToIdx) PyList_SetItem(result, 4, PConvIntArrayToPyList(I->AtmToIdx, I->NAtIndex)); else PyList_SetItem(result, 4, PConvAutoNone(NULL)); PyList_SetItem(result, 5, PyString_FromString(I->Name)); PyList_SetItem(result, 6, ObjectStateAsPyList(&I->State)); PyList_SetItem(result, 7, SettingAsPyList(I->Setting)); PyList_SetItem(result, 8, PConvLabPosVLAToPyList(I->LabPos, I->NIndex)); /* TODO symmetry, spheroid, periodic box ... */ } return (PConvAutoNone(result)); #endif } void CoordSetAdjustAtmIdx(CoordSet * I, int *lookup, int nAtom) /* performs second half of removal */ { /* NOTE: only works in a compressive mode, where lookup[a]<=a */ int a; int a0; PRINTFD(I->State.G, FB_CoordSet) " CoordSetAdjustAtmIdx-Debug: entered NAtIndex: %d NIndex %d\n I->AtmToIdx %p\n", I->NAtIndex, I->NIndex, (void *) I->AtmToIdx ENDFD; if (I->AtmToIdx){ for(a = 0; a < I->NAtIndex; a++) { a0 = lookup[a]; if(a0 >= 0) { I->AtmToIdx[a0] = I->AtmToIdx[a]; } } } I->NAtIndex = nAtom; if (I->AtmToIdx){ VLASize(I->AtmToIdx, int, nAtom); } for(a = 0; a < I->NIndex; a++) { I->IdxToAtm[a] = lookup[I->IdxToAtm[a]]; } PRINTFD(I->State.G, FB_CoordSet) " CoordSetAdjustAtmIdx-Debug: leaving... NAtIndex: %d NIndex %d\n", I->NAtIndex, I->NIndex ENDFD; } /*========================================================================*/ int CoordSetMerge(ObjectMolecule *OM, CoordSet * I, CoordSet * cs) { /* must be non-overlapping */ int nIndex; int a, i0; int ok = true; /* calculate new size and make room for new data */ nIndex = I->NIndex + cs->NIndex; VLASize(I->IdxToAtm, int, nIndex); CHECKOK(ok, I->IdxToAtm); if (ok) VLACheck(I->Coord, float, nIndex * 3); CHECKOK(ok, I->Coord); if (ok){ for(a = 0; a < cs->NIndex; a++) { i0 = a + I->NIndex; I->IdxToAtm[i0] = cs->IdxToAtm[a]; if (OM->DiscreteFlag){ int idx = cs->IdxToAtm[a]; OM->DiscreteAtmToIdx[idx] = i0; OM->DiscreteCSet[idx] = I; } else { I->AtmToIdx[cs->IdxToAtm[a]] = i0; } copy3f(cs->Coord + a * 3, I->Coord + i0 * 3); } } if (ok){ if(cs->LabPos) { if(!I->LabPos) I->LabPos = VLACalloc(LabPosType, nIndex); else VLACheck(I->LabPos, LabPosType, nIndex); if(I->LabPos) { UtilCopyMem(I->LabPos + I->NIndex, cs->LabPos, sizeof(LabPosType) * cs->NIndex); } } else if(I->LabPos) { VLACheck(I->LabPos, LabPosType, nIndex); } CHECKOK(ok, I->LabPos); } if (ok){ if(cs->RefPos) { if(!I->RefPos) I->RefPos = VLACalloc(RefPosType, nIndex); else VLACheck(I->RefPos, RefPosType, nIndex); if(I->RefPos) { UtilCopyMem(I->RefPos + I->NIndex, cs->RefPos, sizeof(RefPosType) * cs->NIndex); } } else if(I->RefPos) { VLACheck(I->RefPos, RefPosType, nIndex); } CHECKOK(ok, I->RefPos); } if(ok && I->fInvalidateRep) I->fInvalidateRep(I, cRepAll, cRepInvAll); I->NIndex = nIndex; return ok; } /*========================================================================*/ void CoordSetPurge(CoordSet * I) /* performs first half of removal */ { int offset = 0; int a, a1, ao; AtomInfoType *ai; ObjectMolecule *obj; float *c0, *c1; LabPosType *l0, *l1; RefPosType *r0, *r1; obj = I->Obj; PRINTFD(I->State.G, FB_CoordSet) " CoordSetPurge-Debug: entering..." ENDFD; c0 = c1 = I->Coord; r0 = r1 = I->RefPos; l0 = l1 = I->LabPos; /* This loop slides down the atoms that are not deleted (deleteFlag) it moves the Coord, RefPos, and LabPos */ for(a = 0; a < I->NIndex; a++) { a1 = I->IdxToAtm[a]; ai = obj->AtomInfo + a1; if(ai->deleteFlag) { offset--; c0 += 3; if(l0) l0++; if(r0) r0++; } else if(offset) { ao = a + offset; *(c1++) = *(c0++); *(c1++) = *(c0++); *(c1++) = *(c0++); if(r1) { *(r1++) = *(r0++); } if(l0) { *(l1++) = *(l0++); } if (I->AtmToIdx) I->AtmToIdx[a1] = ao; I->IdxToAtm[ao] = a1; /* no adjustment of these indexes yet... */ if (I->Obj->DiscreteFlag){ I->Obj->DiscreteAtmToIdx[a1] = ao; I->Obj->DiscreteCSet[a1] = I; } } else { c0 += 3; c1 += 3; if(r1) { r0++; r1++; } if(l0) { l0++; l1++; } } } if(offset) { /* If there were deleted atoms, (offset < 0), then re-adjust the array sizes */ I->NIndex += offset; VLASize(I->Coord, float, I->NIndex * 3); if(I->LabPos) { VLASize(I->LabPos, LabPosType, I->NIndex); } if(I->RefPos) { VLASize(I->RefPos, RefPosType, I->NIndex); } VLASize(I->IdxToAtm, int, I->NIndex); PRINTFD(I->State.G, FB_CoordSet) " CoordSetPurge-Debug: I->IdxToAtm shrunk to %d\n", I->NIndex ENDFD; if(I->fInvalidateRep) I->fInvalidateRep(I, cRepAll, cRepInvAtoms); /* this will free Color */ } PRINTFD(I->State.G, FB_CoordSet) " CoordSetPurge-Debug: leaving NAtIndex %d NIndex %d...\n", I->NAtIndex, I->NIndex ENDFD; } /*========================================================================*/ int CoordSetTransformAtomTTTf(CoordSet * I, int at, float *TTT) { ObjectMolecule *obj; int a1 = -1; int result = 0; float *v1; obj = I->Obj; if(obj->DiscreteFlag) { if(I == obj->DiscreteCSet[at]) a1 = obj->DiscreteAtmToIdx[at]; } else a1 = I->AtmToIdx[at]; if(a1 >= 0) { result = 1; v1 = I->Coord + 3 * a1; MatrixTransformTTTfN3f(1, v1, TTT, v1); } return (result); } /*========================================================================*/ int CoordSetTransformAtomR44f(CoordSet * I, int at, float *matrix) { ObjectMolecule *obj; int a1 = -1; int result = 0; float *v1; obj = I->Obj; if(obj->DiscreteFlag) { if(I == obj->DiscreteCSet[at]) a1 = obj->DiscreteAtmToIdx[at]; } else a1 = I->AtmToIdx[at]; if(a1 >= 0) { result = 1; v1 = I->Coord + 3 * a1; MatrixTransformR44fN3f(1, v1, matrix, v1); } return (result); } /*========================================================================*/ void CoordSetRecordTxfApplied(CoordSet * I, float *matrix, int homogenous) { if(I->State.Matrix) { double temp[16]; if(!homogenous) { convertTTTfR44d(matrix, temp); } else { convert44f44d(matrix, temp); } left_multiply44d44d(temp, I->State.Matrix); } else { I->State.Matrix = Alloc(double, 16); if(I->State.Matrix) { if(!homogenous) convertTTTfR44d(matrix, I->State.Matrix); else { convert44f44d(matrix, I->State.Matrix); } } } /* dump44d(I->State.Matrix,"history"); */ } /*========================================================================*/ int CoordSetMoveAtom(CoordSet * I, int at, float *v, int mode) { ObjectMolecule *obj; int a1 = -1; int result = 0; float *v1; /* grab the CoordSet's MolecularObject and query * for a discrete load; if so, adjust index. */ obj = I->Obj; if(obj->DiscreteFlag) { if(I == obj->DiscreteCSet[at]) a1 = obj->DiscreteAtmToIdx[at]; } else a1 = I->AtmToIdx[at]; /* valid index, then set the new coord */ if(a1 >= 0) { result = 1; v1 = I->Coord + 3 * a1; if(mode) { add3f(v, v1, v1); } else { copy3f(v, v1); } } return (result); } /*========================================================================*/ int CoordSetMoveAtomLabel(CoordSet * I, int at, float *v, int mode) { ObjectMolecule *obj; int a1 = -1; int result = 0; LabPosType *lp; /* discrete index adjustments */ obj = I->Obj; if(obj->DiscreteFlag) { if(I == obj->DiscreteCSet[at]) a1 = obj->DiscreteAtmToIdx[at]; } else a1 = I->AtmToIdx[at]; /* if label is valid, get the label offset * and set the new position relative to that */ if(a1 >= 0) { if(!I->LabPos) I->LabPos = VLACalloc(LabPosType, I->NIndex); if(I->LabPos) { result = 1; lp = I->LabPos + a1; if(!lp->mode) { float *lab_pos = SettingGet_3fv(obj->Obj.G, I->Setting, obj->Obj.Setting, cSetting_label_position); copy3f(lab_pos, lp->pos); } lp->mode = 1; if(mode) { add3f(v, lp->offset, lp->offset); } else { copy3f(v, lp->offset); } } } return (result); } /*========================================================================*/ int CoordSetGetAtomVertex(CoordSet * I, int at, float *v) { register ObjectMolecule *obj; register int a1 = -1; register int result = 0; obj = I->Obj; if(obj->DiscreteFlag) { if(I == obj->DiscreteCSet[at]) a1 = obj->DiscreteAtmToIdx[at]; } else a1 = I->AtmToIdx[at]; if(a1 >= 0) { result = 1; copy3f(I->Coord + 3 * a1, v); } return (result); } /*========================================================================*/ int CoordSetGetAtomTxfVertex(CoordSet * I, int at, float *v) { register ObjectMolecule *obj; register int a1 = -1; register int result = 0; obj = I->Obj; if(obj->DiscreteFlag) { if(I == obj->DiscreteCSet[at]) a1 = obj->DiscreteAtmToIdx[at]; } else a1 = I->AtmToIdx[at]; if(a1 >= 0) { result = 1; copy3f(I->Coord + 3 * a1, v); if(I->State.Matrix && (SettingGet_i(I->State.G, obj->Obj.Setting, I->Setting, cSetting_matrix_mode) > 0)) { /* apply state transformation */ transform44d3f(I->State.Matrix, v, v); } if(obj->Obj.TTTFlag) { /* object transformation */ transformTTT44f3f(obj->Obj.TTT, v, v); } } return (result); } /*========================================================================*/ int CoordSetSetAtomVertex(CoordSet * I, int at, float *v) { ObjectMolecule *obj; int a1 = -1; int result = 0; obj = I->Obj; if(obj->DiscreteFlag) { if(I == obj->DiscreteCSet[at]) a1 = obj->DiscreteAtmToIdx[at]; } else a1 = I->AtmToIdx[at]; if(a1 >= 0) { result = 1; copy3f(v, I->Coord + 3 * a1); } return (result); } /*========================================================================*/ void CoordSetRealToFrac(CoordSet * I, CCrystal * cryst) { int a; float *v; v = I->Coord; for(a = 0; a < I->NIndex; a++) { transform33f3f(cryst->RealToFrac, v, v); v += 3; } } /*========================================================================*/ void CoordSetTransform44f(CoordSet * I, float *mat) { int a; float *v; v = I->Coord; for(a = 0; a < I->NIndex; a++) { transform44f3f(mat, v, v); v += 3; } } /*========================================================================*/ void CoordSetTransform33f(CoordSet * I, float *mat) { int a; float *v; v = I->Coord; for(a = 0; a < I->NIndex; a++) { transform33f3f(mat, v, v); v += 3; } } /*========================================================================*/ void CoordSetGetAverage(CoordSet * I, float *v0) { int a; float *v; double accum[3]; if(I->NIndex) { v = I->Coord; accum[0] = *(v++); accum[1] = *(v++); accum[2] = *(v++); for(a = 1; a < I->NIndex; a++) { accum[0] += *(v++); accum[1] += *(v++); accum[2] += *(v++); } v0[0] = (float) (accum[0] / I->NIndex); v0[1] = (float) (accum[1] / I->NIndex); v0[2] = (float) (accum[2] / I->NIndex); } } /*========================================================================*/ void CoordSetFracToReal(CoordSet * I, CCrystal * cryst) { int a; float *v; v = I->Coord; for(a = 0; a < I->NIndex; a++) { transform33f3f(cryst->FracToReal, v, v); v += 3; } } /*========================================================================*/ static char RotateU(double *matrix, float *anisou) /* Rotates the ANISOU vector * * matrix: flat 4x4, but only rotation (upper left 3x3) is considered * anisou: has 6 elements (of symmetric 3x3) and will be rotated in-place */ { int i, j, k; float Re[3][3]; double e_val[3], e_vec[3][3]; double U[3][3] = { { anisou[0], anisou[3], anisou[4] }, { anisou[3], anisou[1], anisou[5] }, { anisou[4], anisou[5], anisou[2] }, }; // e_val, e_vec = linalg.eigh(U) if(!xx_matrix_jacobi_solve(*e_vec, e_val, &i, *U, 3)) return false; // Re = dot(matrix[:3,:3], e_vec) for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { Re[i][j] = 0.0; for (k = 0; k < 3; k++) Re[i][j] += matrix[i * 4 + k] * e_vec[k][j]; } // U = dot(Re * e_val, Re.T) for (i = 0; i < 3; i++) for (j = 0; j <= i; j++) { U[i][j] = 0.0; for (k = 0; k < 3; k++) U[i][j] += Re[i][k] * e_val[k] * Re[j][k]; } anisou[0] = U[0][0]; anisou[1] = U[1][1]; anisou[2] = U[2][2]; anisou[3] = U[1][0]; anisou[4] = U[2][0]; anisou[5] = U[2][1]; return true; } /*========================================================================*/ void CoordSetAtomToPDBStrVLA(PyMOLGlobals * G, char **charVLA, int *c, AtomInfoType * ai, float *v, int cnt, PDBInfoRec * pdb_info, double *matrix) /* * v: 3x1 vertex in final output space * matrix: 4x4 homogenous transformation matrix from model space to output * space (view matrix * state matrix). Used for ANISOU. */ { char *aType; AtomName name; ResIdent resi; ResName resn; Chain chain; char formalCharge[4]; int rl; int literal = SettingGetGlobal_b(G, cSetting_pdb_literal_names); int reformat = SettingGetGlobal_i(G, cSetting_pdb_reformat_names_mode); WordType x, y, z; formalCharge[0] = 0; sprintf(resn, "%3s", ai->resn); if(SettingGetGlobal_b(G, cSetting_pdb_truncate_residue_name)) { resn[3] = 0; /* enforce 3-letter residue name in PDB files */ } if(SettingGetGlobal_b(G, cSetting_pdb_formal_charges)) { if((ai->formalCharge > 0) && (ai->formalCharge < 10)) { sprintf(formalCharge, "%d+", ai->formalCharge); } else if((ai->formalCharge < 0) && (ai->formalCharge > -10)) { sprintf(formalCharge, "%d-", -ai->formalCharge); } } if(ai->hetatm) aType = sHETATM; else aType = sATOM; strcpy(resi, ai->resi); rl = strlen(resi) - 1; if(rl >= 0) if((resi[rl] >= '0') && (resi[rl] <= '9')) { resi[rl + 1] = ' '; resi[rl + 2] = 0; } VLACheck(*charVLA, char, (*c) + 1000); if(!ai->name[0]) { if(!ai->elem[1]) sprintf(name, " %s", ai->elem); else sprintf(name, "%s", ai->elem); } else if(!literal) { if(strlen(ai->name) < 4) { /* atom name less than length 4 */ if(!((ai->name[0] >= '0') && (ai->name[0]) <= '9')) { /* doesn't start with a number */ if((toupper(ai->elem[0]) == toupper(ai->name[0])) && ((!ai->elem[1]) || /* symbol len = 1 */ (toupper(ai->elem[1]) == toupper(ai->name[1])))) { /* matched len 2 */ /* starts with corrent atomic symbol, so */ if(strlen(ai->elem) > 1) { /* if atom symbol is length 2 */ strcpy(name, ai->name); /* then start in column 0 */ } else { switch (reformat) { case 2: /* amber/iupac */ name[0] = ' '; strcpy(name + 1, ai->name); break; case 1: /* pdb with internal pdb */ case 3: /* pdb with internal iupac */ if((ai->elem[0] == 'H') && (!ai->elem[1]) && (ai->name[2])) { AtomInfoGetPDB3LetHydroName(G, resn, ai->name, name); } else { name[0] = ' '; strcpy(name + 1, ai->name); } break; case 4: default: /* otherwise, start in column 1 */ name[0] = ' '; strcpy(name + 1, ai->name); break; } } } else { /* name doesn't start with atomic symbol */ /* then just place it in column 1 as usual */ name[0] = ' '; strcpy(name + 1, ai->name); } } else { /* name starts with a number */ switch (reformat) { case 2: /* make Amber compliant */ if((ai->elem[0] == ai->name[1]) && ((!ai->elem[1]) || (toupper(ai->elem[1]) == toupper(ai->name[2])))) { /* rotate the name to place atom symbol in column 0 to comply with Amber PDB format */ name[0] = ' '; name[1] = ai->name[1]; name[2] = ai->name[2]; name[3] = ai->name[0]; name[4] = 0; } else { strcpy(name, ai->name); } break; default: /* otherwise, assume that number goes in column 0 */ strcpy(name, ai->name); break; } } /* just stick it in column 0 and hope for the best */ } else { /* if name is length 4 */ if((ai->elem[0] == ai->name[0]) && ((!ai->elem[1]) || /* symbol len = 1 */ (toupper(ai->elem[1]) == toupper(ai->name[1])))) { /* matched len 2 */ /* name starts with the atomic symbol */ if((!ai->elem[1]) && (ai->elem[0])) { /* but if element is one letter... */ switch (reformat) { case 1: /* retaining PDB compliance throughout, or */ case 3: /* saving as PDB compliant, but use IUPAC within PyMOL */ if((ai->name[3] >= '0') && (ai->name[3] <= '9')) { /* and last character is a number */ /* rotate the name to place atom symbol in column 1 to comply with PDB format */ name[0] = ai->name[3]; name[1] = ai->name[0]; name[2] = ai->name[1]; name[3] = ai->name[2]; name[4] = 0; } else { strcpy(name, ai->name); } break; case 4: default: /* no changes */ strcpy(name, ai->name); break; } } else { strcpy(name, ai->name); } } else { /* name does not start with the symbol... */ if(reformat == 2) { /* AMBER compliance mode */ if((ai->name[0] >= '0') && (ai->name[0] <= '9')) { if((ai->elem[0] == ai->name[1]) && ((!(ai->elem[1])) || (toupper(ai->elem[1]) == toupper(ai->name[2])))) { /* rotate the name to place atom symbol in column 0 to comply with Amber PDB format */ name[0] = ai->name[1]; name[1] = ai->name[2]; name[2] = ai->name[3]; name[3] = ai->name[0]; name[4] = 0; } else { strcpy(name, ai->name); } } else { strcpy(name, ai->name); } } else { strcpy(name, ai->name); } } } } else { /* LITERAL mode: preserve what was in the original PDB as best PyMOL can this should enable people to open and save amber pdb files without issues */ if(strlen(ai->name) == 4) { strcpy(name, ai->name); /* save literal contents of field */ } else { /* under length 4? check match with atomic symbol */ if((toupper(ai->elem[0]) == toupper(ai->name[0])) && ((!ai->elem[1]) || /* symbol len = 1 */ (toupper(ai->elem[1]) == toupper(ai->name[1])))) { /* matched len 2 */ /* starts with corrent atomic symbol, so */ if(strlen(ai->elem) > 1) { /* if atom symbol is length 2 */ strcpy(name, ai->name); /* then start in column 0 */ } else { /* otherwise, start in column 1 */ name[0] = ' '; strcpy(name + 1, ai->name); } } else { /* otherwise, start in column 1 */ name[0] = ' '; strcpy(name + 1, ai->name); } } } if(SettingGetGlobal_b(G, cSetting_pdb_retain_ids)) { cnt = ai->id - 1; } if(cnt > 99998) cnt = 99998; name[4] = 0; if((!pdb_info) || (!pdb_info->is_pqr_file)) { /* relying upon short-circuit */ short linelen; sprintf(x, "%8.3f", v[0]); x[8] = 0; sprintf(y, "%8.3f", v[1]); y[8] = 0; sprintf(z, "%8.3f", v[2]); z[8] = 0; linelen = sprintf((*charVLA) + (*c), "%6s%5i %-4s%1s%-4s%1s%5s %s%s%s%6.2f%6.2f %-4s%2s%2s\n", aType, cnt + 1, name, ai->alt, resn, ai->chain, resi, x, y, z, ai->q, ai->b, ai->segi, ai->elem, formalCharge); if(ai->U11 || ai->U22 || ai->U33 || ai->U12 || ai->U13 || ai->U23) { // Warning: anisotropic temperature factors are not rotated with the object matrix // Columns 7 - 27 and 73 - 80 are identical to the corresponding ATOM/HETATM record. char *atomline = (*charVLA) + (*c); char *anisoline = atomline + linelen; float anisou[6] = { ai->U11, ai->U22, ai->U33, ai->U12, ai->U13, ai->U23 }; if(matrix && !RotateU(matrix, anisou)) { PRINTFB(G, FB_CoordSet, FB_Errors) "RotateU failed\n" ENDFB(G); return; } strncpy(anisoline + 6, atomline + 6, 22); sprintf(anisoline + 28, "%7.0f%7.0f%7.0f%7.0f%7.0f%7.0f", anisou[0] * 1e4, anisou[1] * 1e4, anisou[2] * 1e4, anisou[3] * 1e4, anisou[4] * 1e4, anisou[5] * 1e4); strcpy(anisoline + 70, atomline + 70); strncpy(anisoline, "ANISOU", 6); (*c) += linelen; } (*c) += linelen; } else { Chain alt; if(pdb_info->is_pqr_file && pdb_info->pqr_workarounds) { int non_num = false; char *p = resi; while(*p) { if((((*p) <= '0') || ((*p) >= '9')) && (*p != ' ')) { non_num = true; break; } p++; } if(non_num) { sprintf(resi, "%d", ai->resv); rl = strlen(resi) - 1; if(rl >= 0) if((resi[rl] >= '0') && (resi[rl] <= '9')) { resi[rl + 1] = ' '; resi[rl + 2] = 0; } } chain[0] = 0; /* no chain IDs */ alt[0] = 0; /* not alt conf identifiers */ } else { alt[0] = ai->alt[0]; alt[1] = 0; chain[0] = ai->chain[0]; chain[1] = 0; } sprintf(x, "%8.3f", v[0]); if(x[0] != 32) sprintf(x, " %7.2f", v[0]); x[8] = 0; sprintf(y, "%8.3f", v[1]); y[8] = 0; if(y[0] != 32) sprintf(y, " %7.2f", v[1]); y[8] = 0; sprintf(z, "%8.3f", v[2]); if(z[0] != 32) sprintf(z, " %7.2f", v[2]); z[8] = 0; (*c) += sprintf((*charVLA) + (*c), "%6s%5i %-4s%1s%-4s%1s%5s %s%s%s %11.8f %7.3f\n", aType, cnt + 1, name, alt, resn, chain, resi, x, y, z, ai->partialCharge, ai->elec_radius); } } /*========================================================================*/ PyObject *CoordSetAtomToChemPyAtom(PyMOLGlobals * G, AtomInfoType * ai, float *v, float *ref, int index, double *matrix) { #ifdef _PYMOL_NOPY return NULL; #else int ok = true; PyObject *atom = PyObject_CallMethod(P_chempy, "Atom", ""); if(!atom) ok = ErrMessage(G, "CoordSetAtomToChemPyAtom", "can't create atom"); else { float tmp_array[6] = { ai->U11, ai->U22, ai->U33, ai->U12, ai->U13, ai->U23 }; if(matrix) { RotateU(matrix, tmp_array); } PConvFloat3ToPyObjAttr(atom, "coord", v); if(ref) PConvFloat3ToPyObjAttr(atom, "ref_coord", ref); PConvStringToPyObjAttr(atom, "name", ai->name); PConvStringToPyObjAttr(atom, "symbol", ai->elem); PConvStringToPyObjAttr(atom, "resn", ai->resn); PConvStringToPyObjAttr(atom, "resi", ai->resi); PConvStringToPyObjAttr(atom, "ss", ai->ssType); PConvIntToPyObjAttr(atom, "resi_number", ai->resv); PConvIntToPyObjAttr(atom, "stereo", ai->stereo); PConvStringToPyObjAttr(atom, "chain", ai->chain); if(ai->alt[0]) PConvStringToPyObjAttr(atom, "alt", ai->alt); PConvStringToPyObjAttr(atom, "segi", ai->segi); PConvFloatToPyObjAttr(atom, "q", ai->q); PConvFloatToPyObjAttr(atom, "b", ai->b); { { PyObject *tmp_obj = PConvFloatArrayToPyList(tmp_array, 6); if(tmp_obj) { PyObject_SetAttrString(atom, "u_aniso", tmp_obj); Py_XDECREF(tmp_obj); } } } PConvFloatToPyObjAttr(atom, "vdw", ai->vdw); PConvFloatToPyObjAttr(atom, "elec_radius", ai->elec_radius); PConvFloatToPyObjAttr(atom, "partial_charge", ai->partialCharge); PConvIntToPyObjAttr(atom, "formal_charge", ai->formalCharge); if(ai->customType != -9999) PConvIntToPyObjAttr(atom, "numeric_type", ai->customType); if(ai->textType) { char null_st[1] = ""; char *st = null_st; if(ai->textType) st = OVLexicon_FetchCString(G->Lexicon, ai->textType); PConvStringToPyObjAttr(atom, "text_type", st); } if(ai->custom) { char null_st[1] = ""; char *st = null_st; if(ai->custom) st = OVLexicon_FetchCString(G->Lexicon, ai->custom); PConvStringToPyObjAttr(atom, "custom", st); } PConvIntToPyObjAttr(atom, "hetatm", ai->hetatm); PConvIntToPyObjAttr(atom, "flags", ai->flags); PConvIntToPyObjAttr(atom, "id", ai->id); /* not necc. unique */ PConvIntToPyObjAttr(atom, "index", index + 1); /* fragile */ } if(PyErr_Occurred()) PyErr_Print(); return (atom); #endif } /*========================================================================*/ void CoordSetAtomToTERStrVLA(PyMOLGlobals * G, char **charVLA, int *c, AtomInfoType * ai, int cnt) { ResIdent resi; ResName resn; int rl; int retain_ids = SettingGetGlobal_b(G, cSetting_pdb_retain_ids); int ter_id; strcpy(resn, ai->resn); /* enforce 3-letter residue name in PDB files */ resn[3] = 0; strcpy(resi, ai->resi); rl = strlen(resi) - 1; if(rl >= 0) if((resi[rl] >= '0') && (resi[rl] <= '9')) { resi[rl + 1] = ' '; resi[rl + 2] = 0; } VLACheck(*charVLA, char, (*c) + 1000); if(retain_ids) { ter_id = ai->id + 1; } else { ter_id = cnt + 1; } (*c) += sprintf((*charVLA) + (*c), "%3s %5i %3s %1s%5s\n", "TER", ter_id, resn, ai->chain, resi); } /*========================================================================*/ void CoordSetInvalidateRep(CoordSet * I, int type, int level) { int a; if(level >= cRepInvVisib) { if (I->Obj) I->Obj->RepVisCacheValid = false; } /* graphical representations need redrawing */ if(level == cRepInvVisib) { /* cartoon_side_chain_helper */ if(SettingGet_b(I->State.G, I->Setting, I->Obj->Obj.Setting, cSetting_cartoon_side_chain_helper)) { if((type == cRepCyl) || (type == cRepLine) || (type == cRepSphere)) CoordSetInvalidateRep(I, cRepCartoon, cRepInvVisib2); else if(type == cRepCartoon) { CoordSetInvalidateRep(I, cRepLine, cRepInvVisib2); CoordSetInvalidateRep(I, cRepCyl, cRepInvVisib2); CoordSetInvalidateRep(I, cRepSphere, cRepInvVisib2); } } /* ribbon_side_chain_helper */ if(SettingGet_b(I->State.G, I->Setting, I->Obj->Obj.Setting, cSetting_ribbon_side_chain_helper)) { if((type == cRepCyl) || (type == cRepLine) || (type == cRepSphere)) CoordSetInvalidateRep(I, cRepRibbon, cRepInvVisib2); else if(type == cRepRibbon) { CoordSetInvalidateRep(I, cRepLine, cRepInvVisib2); CoordSetInvalidateRep(I, cRepCyl, cRepInvVisib2); CoordSetInvalidateRep(I, cRepSphere, cRepInvVisib2); } } /* line_stick helper */ if(SettingGet_b(I->State.G, I->Setting, I->Obj->Obj.Setting, cSetting_line_stick_helper)) { if(type == cRepCyl) CoordSetInvalidateRep(I, cRepLine, cRepInvVisib2); else if(type == cRepLine) { CoordSetInvalidateRep(I, cRepCyl, cRepInvVisib2); } } } if(I->Spheroid) if(I->NSpheroid != I->NAtIndex * I->SpheroidSphereSize) { FreeP(I->Spheroid); FreeP(I->SpheroidNormal); } if(level >= cRepInvColor) VLAFreeP(I->Color); /* invalidate basd on one representation, 'type' */ if(type >= 0) { /* representation specific */ if(type < cRepCnt) { int eff_level = level; a = type; if(level == cRepInvPick) { switch (a) { case cRepSurface: case cRepMesh: case cRepDot: /* skip the expensive to recompute, non-pickable representations */ break; default: /* default behavior is to blow away the representation */ eff_level = cRepInvRep; break; } } if(I->Rep[a]) { if(I->Rep[a]->fInvalidate && (eff_level < cRepInvPurge)) I->Rep[a]->fInvalidate(I->Rep[a], I, eff_level); else if(eff_level >= cRepInvExtColor) { I->Rep[a]->fFree(I->Rep[a]); I->Rep[a] = NULL; } } if(eff_level >= cRepInvVisib) /* make active if visibility has changed */ I->Active[type] = true; } } else { /* all representations are affected */ for(a = 0; a < cRepCnt; a++) { int eff_level = level; if(level == cRepInvPick) { switch (a) { case cRepSurface: case cRepMesh: case cRepDot: /* skip the expensive to recompute, non-pickable representations */ break; default: /* default behavior is to blow away the representation */ eff_level = cRepInvRep; break; } } if(eff_level >= cRepInvVisib) /* make active if visibility has changed */ I->Active[a] = true; if(I->Rep[a]) { if(I->Rep[a]->fInvalidate && (eff_level < cRepInvPurge)) I->Rep[a]->fInvalidate(I->Rep[a], I, eff_level); else if(eff_level >= cRepInvExtColor) { I->Rep[a]->fFree(I->Rep[a]); I->Rep[a] = NULL; } } } } if(level >= cRepInvCoord) { /* if coordinates change, then this map becomes invalid */ MapFree(I->Coord2Idx); I->Coord2Idx = NULL; /* invalidate distances */ } SceneChanged(I->State.G); } /*========================================================================*/ #define RepUpdateMacro(I,rep,new_fn,state) {\ if(I->Active[rep]&&(!G->Interrupt)) {\ if(!I->Rep[rep]) {\ I->Rep[rep]=new_fn(I,state);\ if(I->Rep[rep]){ \ I->Rep[rep]->fNew=(struct Rep *(*)(struct CoordSet *,int state))new_fn;\ } else { \ I->Active[rep] = false; \ } \ } else {\ if(I->Rep[rep]->fUpdate)\ I->Rep[rep] = I->Rep[rep]->fUpdate(I->Rep[rep],I,state,rep);\ }\ }\ OrthoBusyFast(I->State.G,rep,cRepCnt);\ } /*========================================================================*/ static void CoordSetUpdate(CoordSet * I, int state) { int a; int i; PyMOLGlobals *G = I->Obj->Obj.G; ObjectMolecule *obj; int ok = true; obj = I->Obj; PRINTFB(G, FB_CoordSet, FB_Blather) " CoordSetUpdate-Entered: object %s state %d cset %p\n", I->Obj->Obj.Name, state, (void *) I ENDFB(G); if(!I->Color) { /* colors invalidated */ I->Color = VLAlloc(int, I->NIndex); CHECKOK(ok, I->Color); if(ok && I->Color) { if(obj->DiscreteFlag) { for(a = 0; a < I->Obj->NAtom; a++) { if(obj->DiscreteCSet[a] == I) { i = obj->DiscreteAtmToIdx[a]; if(i >= 0) I->Color[i] = obj->AtomInfo[a].color; } } } else { for(a = 0; a < I->Obj->NAtom; a++) { i = I->AtmToIdx[a]; if(i >= 0){ I->Color[i] = obj->AtomInfo[a].color; } } } } if (!ok){ PRINTFB(G, FB_CoordSet, FB_Errors) " CoordSetUpdate: Color was not allocated properly I->NIndex=%d\n", I->NIndex ENDFB(G); } } OrthoBusyFast(G, 0, cRepCnt); RepUpdateMacro(I, cRepLine, RepWireBondNew, state); RepUpdateMacro(I, cRepCyl, RepCylBondNew, state); RepUpdateMacro(I, cRepDot, RepDotNew, state); RepUpdateMacro(I, cRepMesh, RepMeshNew, state); RepUpdateMacro(I, cRepSphere, RepSphereNew, state); RepUpdateMacro(I, cRepRibbon, RepRibbonNew, state); RepUpdateMacro(I, cRepCartoon, RepCartoonNew, state); RepUpdateMacro(I, cRepSurface, RepSurfaceNew, state); RepUpdateMacro(I, cRepLabel, RepLabelNew, state); RepUpdateMacro(I, cRepNonbonded, RepNonbondedNew, state); RepUpdateMacro(I, cRepNonbondedSphere, RepNonbondedSphereNew, state); RepUpdateMacro(I, cRepEllipsoid, RepEllipsoidNew, state); for(a = 0; a < cRepCnt; a++) if(!I->Rep[a]) I->Active[a] = false; SceneInvalidate(G); OrthoBusyFast(G, 1, 1); if(Feedback(G, FB_CoordSet, FB_Blather)) { printf(" CoordSetUpdate-Leaving: object %s state %d cset %p\n", I->Obj->Obj.Name, state, (void *) I); } } /*========================================================================*/ void CoordSetUpdateCoord2IdxMap(CoordSet * I, float cutoff) { if(cutoff < R_SMALL4) cutoff = R_SMALL4; if(I->NIndex > 10) { if(I->Coord2Idx) { if((I->Coord2IdxDiv < cutoff) || (((cutoff - I->Coord2IdxReq) / I->Coord2IdxReq) < -0.5F)) { MapFree(I->Coord2Idx); I->Coord2Idx = NULL; } } if(I->NIndex && (!I->Coord2Idx)) { /* NOTE: map based on stored coords */ I->Coord2IdxReq = cutoff; I->Coord2IdxDiv = cutoff * 1.25F; I->Coord2Idx = MapNew(I->State.G, I->Coord2IdxDiv, I->Coord, I->NIndex, NULL); if(I->Coord2IdxDiv < I->Coord2Idx->Div) I->Coord2IdxDiv = I->Coord2Idx->Div; } } } /*========================================================================*/ void CoordSetRender(CoordSet * I, RenderInfo * info) { PyMOLGlobals *G = I->State.G; PRINTFD(G, FB_CoordSet) " CoordSetRender: entered (%p).\n", (void *) I ENDFD; if(!(info->ray || info->pick) && (SettingGet_i(G, I->Setting, I->Obj->Obj.Setting, cSetting_defer_builds_mode) == 5)) { if(!info->pass) { ObjectUseColor((CObject *) I->Obj); if(I->Active[cRepLine]) RepWireBondRenderImmediate(I, info); if(I->Active[cRepNonbonded]) RepNonbondedRenderImmediate(I, info); if(I->Active[cRepSphere]) RepSphereRenderImmediate(I, info); if(I->Active[cRepCyl]) RepCylBondRenderImmediate(I, info); if(I->Active[cRepRibbon]) RepRibbonRenderImmediate(I, info); } } else { int pass = info->pass; CRay *ray = info->ray; Picking **pick = info->pick; int a, aa; Rep *r; int float_labels = SettingGet_i(G, I->Setting, I->Obj->Obj.Setting, cSetting_float_labels); int sculpt_vdw_vis_mode = SettingGet_i(G, I->Setting, I->Obj->Obj.Setting, cSetting_sculpt_vdw_vis_mode); if((!pass) && sculpt_vdw_vis_mode && I->SculptCGO && (I->Obj->Obj.RepVis[cRepCGO])) { if(ray) { int ok = CGORenderRay(I->SculptCGO, ray, ColorGet(G, I->Obj->Obj.Color), I->Setting, I->Obj->Obj.Setting); if (!ok){ CGOFree(I->SculptCGO); CGOFree(I->SculptShaderCGO); I->SculptShaderCGO = I->SculptCGO = NULL; } } else if(G->HaveGUI && G->ValidContext) { if(!pick) { int use_shader = SettingGetGlobal_b(G, cSetting_use_shaders); if (use_shader){ if (!I->SculptShaderCGO){ CGO *convertcgo = NULL; convertcgo = CGOCombineBeginEnd(I->SculptCGO, 0); if (convertcgo){ I->SculptShaderCGO = CGOOptimizeToVBONotIndexed(convertcgo, 0); I->SculptShaderCGO->use_shader = I->SculptShaderCGO->enable_shaders = true; CGOFree(convertcgo); } } } else if (I->SculptShaderCGO){ CGOFree(I->SculptShaderCGO); I->SculptShaderCGO = NULL; } if (I->SculptShaderCGO){ CGORenderGL(I->SculptShaderCGO, ColorGet(G, I->Obj->Obj.Color), I->Setting, I->Obj->Obj.Setting, info, NULL); } else { CGORenderGL(I->SculptCGO, ColorGet(G, I->Obj->Obj.Color), I->Setting, I->Obj->Obj.Setting, info, NULL); } } } } for(aa = 0; aa < cRepCnt; aa++) { if(aa == cRepSurface) { /* reorder */ a = cRepCell; } else if(aa == cRepCell) { a = cRepSurface; } else { a = aa; } if(I->Active[a] && I->Rep[a]) { r = I->Rep[a]; if(!ray) { ObjectUseColor((CObject *) I->Obj); } else { if(I->Obj) ray->fWobble(ray, SettingGet_i(G, I->Setting, I->Obj->Obj.Setting, cSetting_ray_texture), SettingGet_3fv(G, I->Setting, I->Obj->Obj.Setting, cSetting_ray_texture_settings)); else ray->fWobble(ray, SettingGet_i(G, I->Setting, NULL, cSetting_ray_texture), SettingGet_3fv(G, I->Setting, NULL, cSetting_ray_texture_settings)); ray->fColor3fv(ray, ColorGet(G, I->Obj->Obj.Color)); } if(r->fRender) { /* do OpenGL rendering in three passes */ if(ray || pick) { /* here we need to iterate through and apply coordinate set matrices */ r->fRender(r, info); } else { /* here we need to iterate through and apply coordinate set matrices */ switch (a) { case cRepLabel: if(float_labels && (pass == -1)) r->fRender(r, info); else if(pass == 1) r->fRender(r, info); break; case cRepNonbondedSphere: case cRepRibbon: case cRepDot: case cRepCGO: case cRepCallback: if(pass == 1) r->fRender(r, info); break; case cRepLine: case cRepMesh: case cRepDash: case cRepNonbonded: case cRepCell: case cRepExtent: if(!pass) r->fRender(r, info); break; case cRepCyl: /* render sticks differently depending on transparency */ if(SettingGet_f(G, r->cs->Setting, r->obj->Setting, cSetting_stick_transparency) > 0.0001) { if(pass == -1) r->fRender(r, info); } else if(pass == 1){ r->fRender(r, info); } break; case cRepSurface: if(info->alpha_cgo) { if(pass == 1) r->fRender(r, info); } else { if(SettingGet_f(G, r->cs->Setting, r->obj->Setting, cSetting_transparency) > 0.0001) { if(pass == -1) r->fRender(r, info); } else if(pass == 1) r->fRender(r, info); } break; case cRepSphere: /* render spheres differently depending on transparency */ if(SettingGet_f(G, r->cs->Setting, r->obj->Setting, cSetting_sphere_transparency) > 0.0001) { if(pass == -1) r->fRender(r, info); } else if(pass == 1) r->fRender(r, info); break; case cRepEllipsoid: /* render spheres differently depending on transparency */ if(SettingGet_f(G, r->cs->Setting, r->obj->Setting, cSetting_ellipsoid_transparency) > 0.0001) { if(pass == -1) r->fRender(r, info); } else if(pass == 1) r->fRender(r, info); break; case cRepCartoon: if(info->alpha_cgo) { if(pass == 1) r->fRender(r, info); } else { if(SettingGet_f(G, r->cs->Setting, r->obj->Setting, cSetting_cartoon_transparency) > 0.0001) { if(pass == -1) r->fRender(r, info); } else if(pass == 1) r->fRender(r, info); } break; } } } /* if(ray) ray->fWobble(ray,0,NULL); */ } } } PRINTFD(G, FB_CoordSet) " CoordSetRender: leaving...\n" ENDFD; } /*========================================================================*/ CoordSet *CoordSetNew(PyMOLGlobals * G) { OOCalloc(G, CoordSet); /* NULL-initializes all fields */ ObjectStateInit(G, &I->State); I->State.G = G; I->fFree = CoordSetFree; I->fRender = CoordSetRender; I->fUpdate = CoordSetUpdate; I->fEnumIndices = CoordSetEnumIndices; I->fExtendIndices = CoordSetExtendIndices; I->fAppendIndices = CoordSetAppendIndices; I->fInvalidateRep = CoordSetInvalidateRep; I->PeriodicBoxType = cCSet_NoPeriodicity; I->SpheroidSphereSize = I->State.G->Sphere->Sphere[1]->nDot; /* does this make any sense? */ I->noInvalidateMMStereoAndTextType = 0; return (I); } CoordSet *CoordSetCopyImpl(CoordSet * cs); CoordSet *CoordSetCopy(CoordSet * cs) { if (!cs) return NULL; return (CoordSetCopyImpl(cs)); } /*========================================================================*/ CoordSet *CoordSetCopyImpl(CoordSet * cs) { int nAtom; /* OOAlloc declares and defines, I: * I = ... */ OOCalloc(cs->State.G, CoordSet); /* shallow copy */ (*I) = (*cs); /* NOTE: must deep-copy all pointers in this struct */ /* deep copy state struct */ ObjectStateCopy(&cs->State, &I->State); /* deep copy & return ptr to new symmetry */ I->Symmetry = SymmetryCopy(cs->Symmetry); if(I->PeriodicBox) I->PeriodicBox = CrystalCopy(I->PeriodicBox); /* copy the coords */ I->Coord = VLACalloc(float, I->NIndex * 3); UtilCopyMem(I->Coord, cs->Coord, sizeof(float) * 3 * I->NIndex); /* copy label positions if present in source */ if(cs->LabPos) { I->LabPos = VLACalloc(LabPosType, I->NIndex); UtilCopyMem(I->LabPos, cs->LabPos, sizeof(LabPosType) * I->NIndex); } /* copy ref pos if in source */ if(cs->RefPos) { I->RefPos = VLACalloc(RefPosType, I->NIndex); UtilCopyMem(I->RefPos, cs->RefPos, sizeof(RefPosType) * I->NIndex); } /* copy atom to index mapping, if shallow copied from source */ if(I->AtmToIdx) { nAtom = cs->Obj->NAtom; I->AtmToIdx = VLACalloc(int, nAtom); UtilCopyMem(I->AtmToIdx, cs->AtmToIdx, sizeof(int) * nAtom); } if(cs->MatrixVLA) { /* not used yet */ I->MatrixVLA = VLAlloc(double, 16 * cs->NMatrix * sizeof(double)); if(I->MatrixVLA) { UtilCopyMem(I->MatrixVLA, cs->MatrixVLA, sizeof(double) * 16 * cs->NMatrix); } } I->IdxToAtm = VLACalloc(int, I->NIndex); UtilCopyMem(I->IdxToAtm, cs->IdxToAtm, sizeof(int) * I->NIndex); UtilZeroMem(I->Rep, sizeof(Rep *) * cRepCnt); I->TmpBond = NULL; I->Color = NULL; I->Spheroid = NULL; I->SpheroidNormal = NULL; I->Coord2Idx = NULL; return (I); } /*========================================================================*/ int CoordSetExtendIndices(CoordSet * I, int nAtom) { int a, b; ObjectMolecule *obj = I->Obj; int ok = true; if(obj->DiscreteFlag) { if(obj->NDiscrete < nAtom) { VLASize(obj->DiscreteAtmToIdx, int, nAtom); CHECKOK(ok, obj->DiscreteAtmToIdx); if (ok) VLASize(obj->DiscreteCSet, CoordSet *, nAtom); CHECKOK(ok, obj->DiscreteCSet); if (ok){ for(a = obj->NDiscrete; a < nAtom; a++) { obj->DiscreteAtmToIdx[a] = -1; obj->DiscreteCSet[a] = NULL; } obj->NDiscrete = nAtom; } } if(I->AtmToIdx) { /* convert to discrete if necessary */ VLAFree(I->AtmToIdx); I->AtmToIdx = NULL; if (ok){ for(a = 0; a < I->NIndex; a++) { b = I->IdxToAtm[a]; obj->DiscreteAtmToIdx[b] = a; obj->DiscreteCSet[b] = I; } } } } if(ok && I->NAtIndex < nAtom) { if(I->AtmToIdx) { VLASize(I->AtmToIdx, int, nAtom); CHECKOK(ok, I->AtmToIdx); if(ok && nAtom) { for(a = I->NAtIndex; a < nAtom; a++) I->AtmToIdx[a] = -1; } I->NAtIndex = nAtom; } else if(!obj->DiscreteFlag) { I->AtmToIdx = VLACalloc(int, nAtom); CHECKOK(ok, I->AtmToIdx); if (ok){ for(a = 0; a < nAtom; a++) I->AtmToIdx[a] = -1; I->NAtIndex = nAtom; } } } return ok; } /*========================================================================*/ void CoordSetAppendIndices(CoordSet * I, int offset) { int a, b; ObjectMolecule *obj = I->Obj; I->IdxToAtm = VLACalloc(int, I->NIndex); if(I->NIndex) { ErrChkPtr(I->State.G, I->IdxToAtm); for(a = 0; a < I->NIndex; a++) I->IdxToAtm[a] = a + offset; } if(obj->DiscreteFlag) { VLACheck(obj->DiscreteAtmToIdx, int, I->NIndex + offset); VLACheck(obj->DiscreteCSet, CoordSet *, I->NIndex + offset); for(a = 0; a < I->NIndex; a++) { b = a + offset; obj->DiscreteAtmToIdx[b] = a; obj->DiscreteCSet[b] = I; } } else { I->AtmToIdx = VLACalloc(int, I->NIndex + offset); if(I->NIndex + offset) { ErrChkPtr(I->State.G, I->AtmToIdx); for(a = 0; a < offset; a++) I->AtmToIdx[a] = -1; for(a = 0; a < I->NIndex; a++) I->AtmToIdx[a + offset] = a; } } I->NAtIndex = I->NIndex + offset; } /*========================================================================*/ void CoordSetEnumIndices(CoordSet * I) { /* set up for simple case where 1 = 1, etc. */ int a; I->AtmToIdx = VLACalloc(int, I->NIndex); I->IdxToAtm = VLACalloc(int, I->NIndex); if(I->NIndex) { ErrChkPtr(I->State.G, I->AtmToIdx); ErrChkPtr(I->State.G, I->IdxToAtm); for(a = 0; a < I->NIndex; a++) { I->AtmToIdx[a] = a; I->IdxToAtm[a] = a; } } I->NAtIndex = I->NIndex; } /*========================================================================*/ void CoordSetFree(CoordSet * I) { int a; ObjectMolecule *obj; if(I) { for(a = 0; a < cRepCnt; a++) if(I->Rep[a]) I->Rep[a]->fFree(I->Rep[a]); obj = I->Obj; if(obj) if(obj->DiscreteFlag) /* remove references to the atoms in discrete objects */ for(a = 0; a < I->NIndex; a++) { obj->DiscreteAtmToIdx[I->IdxToAtm[a]] = -1; obj->DiscreteCSet[I->IdxToAtm[a]] = NULL; } VLAFreeP(I->AtmToIdx); VLAFreeP(I->IdxToAtm); VLAFreeP(I->Color); MapFree(I->Coord2Idx); VLAFreeP(I->Coord); VLAFreeP(I->TmpBond); if(I->Symmetry) SymmetryFree(I->Symmetry); if(I->PeriodicBox) CrystalFree(I->PeriodicBox); FreeP(I->Spheroid); FreeP(I->SpheroidNormal); SettingFreeP(I->Setting); ObjectStatePurge(&I->State); CGOFree(I->SculptCGO); VLAFreeP(I->LabPos); VLAFreeP(I->RefPos); /* free and make null */ OOFreeP(I); } } void LabPosTypeCopy(LabPosType * src, LabPosType * dst){ dst->mode = src->mode; copy3f(src->pos, dst->pos); copy3f(src->offset, dst->offset); } void RefPosTypeCopy(RefPosType * src, RefPosType * dst){ copy3f(src->coord, dst->coord); dst->specified = dst->specified; }
29.385169
139
0.50758
[ "render", "object", "vector", "model" ]
eabda1925cb0b8141fed38dc0384db5476fdeff9
12,517
c
C
usb/umdf_filter_kmdf/kmdf_driver/bulkrwr.c
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,084
2015-03-18T04:40:32.000Z
2019-05-06T17:14:33.000Z
usb/umdf_filter_kmdf/kmdf_driver/bulkrwr.c
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
275
2015-03-19T18:44:41.000Z
2019-05-06T14:13:26.000Z
usb/umdf_filter_kmdf/kmdf_driver/bulkrwr.c
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,091
2015-03-19T00:08:54.000Z
2019-05-06T16:42:01.000Z
/*++ Copyright (c) Microsoft Corporation. All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Module Name: bulkrwr.c Abstract: This file has routines to perform reads and writes. The read and writes are targeted bulk to endpoints. Environment: Kernel mode --*/ #include <osrusbfx2.h> #if defined(EVENT_TRACING) #include "bulkrwr.tmh" #endif #pragma warning(disable:4267) VOID OsrFxEvtIoRead( _In_ WDFQUEUE Queue, _In_ WDFREQUEST Request, _In_ size_t Length ) /*++ Routine Description: Called by the framework when it receives Read or Write requests. Arguments: Queue - Default queue handle Request - Handle to the read/write request Lenght - Length of the data buffer associated with the request. The default property of the queue is to not dispatch zero lenght read & write requests to the driver and complete is with status success. So we will never get a zero length request. Return Value: --*/ { WDFUSBPIPE pipe; NTSTATUS status; WDFMEMORY reqMemory; PDEVICE_CONTEXT pDeviceContext; GUID activity = RequestToActivityId(Request); UNREFERENCED_PARAMETER(Queue); // // Log read start event, using IRP activity ID if available or request // handle otherwise. // EventWriteReadStart(&activity, WdfIoQueueGetDevice(Queue), (ULONG)Length); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "-->OsrFxEvtIoRead\n"); // // First validate input parameters. // if (Length > TEST_BOARD_TRANSFER_BUFFER_SIZE) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "Transfer exceeds %d\n", TEST_BOARD_TRANSFER_BUFFER_SIZE); status = STATUS_INVALID_PARAMETER; goto Exit; } pDeviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue)); pipe = pDeviceContext->BulkReadPipe; status = WdfRequestRetrieveOutputMemory(Request, &reqMemory); if(!NT_SUCCESS(status)){ TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestRetrieveOutputMemory failed %!STATUS!\n", status); goto Exit; } // // The format call validates to make sure that you are reading or // writing to the right pipe type, sets the appropriate transfer flags, // creates an URB and initializes the request. // status = WdfUsbTargetPipeFormatRequestForRead(pipe, Request, reqMemory, NULL // Offsets ); if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfUsbTargetPipeFormatRequestForRead failed 0x%x\n", status); goto Exit; } WdfRequestSetCompletionRoutine( Request, EvtRequestReadCompletionRoutine, pipe); // // Send the request asynchronously. // if (WdfRequestSend(Request, WdfUsbTargetPipeGetIoTarget(pipe), WDF_NO_SEND_OPTIONS) == FALSE) { // // Framework couldn't send the request for some reason. // TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "WdfRequestSend failed\n"); status = WdfRequestGetStatus(Request); goto Exit; } Exit: if (!NT_SUCCESS(status)) { // // log event read failed // EventWriteReadFail(&activity, WdfIoQueueGetDevice(Queue), status); WdfRequestCompleteWithInformation(Request, status, 0); } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "<-- OsrFxEvtIoRead\n"); return; } VOID EvtRequestReadCompletionRoutine( _In_ WDFREQUEST Request, _In_ WDFIOTARGET Target, _In_ PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, _In_ WDFCONTEXT Context ) /*++ Routine Description: This is the completion routine for reads If the irp completes with success, we check if we need to recirculate this irp for another stage of transfer. Arguments: Context - Driver supplied context Device - Device handle Request - Request handle Params - request completion params Return Value: None --*/ { NTSTATUS status; size_t bytesRead = 0; GUID activity = RequestToActivityId(Request); PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams; UNREFERENCED_PARAMETER(Target); UNREFERENCED_PARAMETER(Context); status = CompletionParams->IoStatus.Status; usbCompletionParams = CompletionParams->Parameters.Usb.Completion; bytesRead = usbCompletionParams->Parameters.PipeRead.Length; if (NT_SUCCESS(status)){ TraceEvents(TRACE_LEVEL_INFORMATION, DBG_READ, "Number of bytes read: %I64d\n", (INT64)bytesRead); } else { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "Read failed - request status 0x%x UsbdStatus 0x%x\n", status, usbCompletionParams->UsbdStatus); } // // Log read stop event, using IRP activity ID if available or request // handle otherwise. // EventWriteReadStop(&activity, WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)), bytesRead, status, usbCompletionParams->UsbdStatus); WdfRequestCompleteWithInformation(Request, status, bytesRead); return; } VOID OsrFxEvtIoWrite( _In_ WDFQUEUE Queue, _In_ WDFREQUEST Request, _In_ size_t Length ) /*++ Routine Description: Called by the framework when it receives Read or Write requests. Arguments: Queue - Default queue handle Request - Handle to the read/write request Lenght - Length of the data buffer associated with the request. The default property of the queue is to not dispatch zero lenght read & write requests to the driver and complete is with status success. So we will never get a zero length request. Return Value: --*/ { NTSTATUS status; WDFUSBPIPE pipe; WDFMEMORY reqMemory; PDEVICE_CONTEXT pDeviceContext; GUID activity = RequestToActivityId(Request); UNREFERENCED_PARAMETER(Queue); // // Log write start event, using IRP activity ID if available or request // handle otherwise. // EventWriteWriteStart(&activity, WdfIoQueueGetDevice(Queue), (ULONG)Length); TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "-->OsrFxEvtIoWrite\n"); // // First validate input parameters. // if (Length > TEST_BOARD_TRANSFER_BUFFER_SIZE) { TraceEvents(TRACE_LEVEL_ERROR, DBG_READ, "Transfer exceeds %d\n", TEST_BOARD_TRANSFER_BUFFER_SIZE); status = STATUS_INVALID_PARAMETER; goto Exit; } pDeviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue)); pipe = pDeviceContext->BulkWritePipe; status = WdfRequestRetrieveInputMemory(Request, &reqMemory); if(!NT_SUCCESS(status)){ TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfRequestRetrieveInputBuffer failed\n"); goto Exit; } status = WdfUsbTargetPipeFormatRequestForWrite(pipe, Request, reqMemory, NULL); // Offset if (!NT_SUCCESS(status)) { TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfUsbTargetPipeFormatRequestForWrite failed 0x%x\n", status); goto Exit; } WdfRequestSetCompletionRoutine( Request, EvtRequestWriteCompletionRoutine, pipe); // // Send the request asynchronously. // if (WdfRequestSend(Request, WdfUsbTargetPipeGetIoTarget(pipe), WDF_NO_SEND_OPTIONS) == FALSE) { // // Framework couldn't send the request for some reason. // TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "WdfRequestSend failed\n"); status = WdfRequestGetStatus(Request); goto Exit; } Exit: if (!NT_SUCCESS(status)) { // // log event write failed // EventWriteWriteFail(&activity, WdfIoQueueGetDevice(Queue), status); WdfRequestCompleteWithInformation(Request, status, 0); } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE, "<-- OsrFxEvtIoWrite\n"); return; } VOID EvtRequestWriteCompletionRoutine( _In_ WDFREQUEST Request, _In_ WDFIOTARGET Target, _In_ PWDF_REQUEST_COMPLETION_PARAMS CompletionParams, _In_ WDFCONTEXT Context ) /*++ Routine Description: This is the completion routine for writes If the irp completes with success, we check if we need to recirculate this irp for another stage of transfer. Arguments: Context - Driver supplied context Device - Device handle Request - Request handle Params - request completion params Return Value: None --*/ { NTSTATUS status; size_t bytesWritten = 0; GUID activity = RequestToActivityId(Request); PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams; UNREFERENCED_PARAMETER(Target); UNREFERENCED_PARAMETER(Context); status = CompletionParams->IoStatus.Status; // // For usb devices, we should look at the Usb.Completion param. // usbCompletionParams = CompletionParams->Parameters.Usb.Completion; bytesWritten = usbCompletionParams->Parameters.PipeWrite.Length; if (NT_SUCCESS(status)){ TraceEvents(TRACE_LEVEL_INFORMATION, DBG_WRITE, "Number of bytes written: %I64d\n", (INT64)bytesWritten); } else { TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "Write failed: request Status 0x%x UsbdStatus 0x%x\n", status, usbCompletionParams->UsbdStatus); } // // Log write stop event, using IRP activtiy ID if available or request // handle otherwise // EventWriteWriteStop(&activity, WdfIoQueueGetDevice(WdfRequestGetIoQueue(Request)), bytesWritten, status, usbCompletionParams->UsbdStatus); WdfRequestCompleteWithInformation(Request, status, bytesWritten); return; } VOID OsrFxEvtIoStop( _In_ WDFQUEUE Queue, _In_ WDFREQUEST Request, _In_ ULONG ActionFlags ) /*++ Routine Description: This callback is invoked on every inflight request when the device is suspended or removed. Since our inflight read and write requests are actually pending in the target device, we will just acknowledge its presence. Until we acknowledge, complete, or requeue the requests framework will wait before allowing the device suspend or remove to proceeed. When the underlying USB stack gets the request to suspend or remove, it will fail all the pending requests. Arguments: Queue - handle to queue object that is associated with the I/O request Request - handle to a request object ActionFlags - bitwise OR of one or more WDF_REQUEST_STOP_ACTION_FLAGS flags Return Value: None --*/ { UNREFERENCED_PARAMETER(Queue); UNREFERENCED_PARAMETER(ActionFlags); if (ActionFlags & WdfRequestStopActionSuspend ) { WdfRequestStopAcknowledge(Request, FALSE); // Don't requeue } else if(ActionFlags & WdfRequestStopActionPurge) { WdfRequestCancelSentRequest(Request); } return; }
28.643021
100
0.613725
[ "object" ]
eac11e9913c73d5c26de542353e424895b49ddd8
7,034
h
C
src/engine/src/randomnormals.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/src/randomnormals.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/src/randomnormals.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// // NOTE! These are in random order unlike anorms.h // Generated with genrandomnormals 162 Vector( 0.825743, 0.538446, -0.168001 ), Vector( -0.843591, -0.159277, 0.512821 ), Vector( -0.378488, 0.340066, 0.860873 ), Vector( 0.868755, 0.387944, 0.307838 ), Vector( -0.425671, -0.787714, 0.445321 ), Vector( -0.658362, -0.715675, -0.233169 ), Vector( -0.634003, -0.077732, 0.769414 ), Vector( 0.073132, 0.950169, 0.303037 ), Vector( 0.067374, -0.877352, -0.475094 ), Vector( 0.725601, -0.465560, 0.506712 ), Vector( -0.073840, 0.513963, -0.854628 ), Vector( -0.094480, 0.598792, 0.795313 ), Vector( -0.633522, 0.773038, 0.032584 ), Vector( -0.859486, 0.072985, -0.505922 ), Vector( 0.351452, -0.630203, 0.692334 ), Vector( 0.364808, -0.020565, -0.930856 ), Vector( 0.096574, -0.928485, 0.358593 ), Vector( -0.356142, 0.317409, -0.878871 ), Vector( 0.945683, -0.322026, -0.044536 ), Vector( 0.408082, -0.278635, 0.869386 ), Vector( -0.281426, -0.888709, -0.361934 ), Vector( -0.115877, 0.130874, -0.984604 ), Vector( 0.880770, -0.074097, -0.467711 ), Vector( -0.614617, -0.650750, -0.445836 ), Vector( -0.065073, -0.742223, -0.666986 ), Vector( 0.985924, -0.108532, -0.127177 ), Vector( 0.092889, 0.876449, 0.472449 ), Vector( -0.574226, -0.016323, -0.818534 ), Vector( 0.950824, 0.309496, -0.012047 ), Vector( -0.983225, -0.167966, -0.071108 ), Vector( -0.341141, 0.923420, -0.175838 ), Vector( 0.072349, -0.566845, 0.820642 ), Vector( -0.970934, -0.231836, 0.059495 ), Vector( -0.380726, -0.907403, 0.177953 ), Vector( 0.244299, 0.505310, 0.827635 ), Vector( 0.295587, -0.555585, 0.777144 ), Vector( -0.900350, -0.435164, 0.001414 ), Vector( -0.043291, 0.354923, -0.933892 ), Vector( -0.889510, -0.074359, 0.450824 ), Vector( -0.006693, -0.623901, 0.781475 ), Vector( 0.782377, 0.240500, -0.574497 ), Vector( -0.686929, -0.245283, 0.684079 ), Vector( 0.751860, 0.262505, 0.604811 ), Vector( -0.041248, -0.101297, -0.994001 ), Vector( 0.015833, 0.249425, -0.968265 ), Vector( -0.695925, -0.694609, 0.182227 ), Vector( -0.966318, 0.197473, -0.165028 ), Vector( -0.412081, -0.895297, -0.169211 ), Vector( 0.983433, 0.167668, 0.068900 ), Vector( 0.656830, 0.659853, -0.364921 ), Vector( 0.530682, -0.774831, -0.343532 ), Vector( 0.296475, -0.430515, -0.852502 ), Vector( 0.596458, 0.794751, 0.112292 ), Vector( -0.567820, -0.803183, 0.180217 ), Vector( -0.027603, 0.037487, 0.998916 ), Vector( 0.672726, -0.070827, 0.736494 ), Vector( 0.543673, -0.838983, -0.022971 ), Vector( -0.750056, 0.638774, -0.171413 ), Vector( 0.034069, -0.470091, 0.881960 ), Vector( 0.453427, 0.561039, -0.692560 ), Vector( -0.198669, -0.770141, 0.606146 ), Vector( 0.739780, -0.213109, -0.638208 ), Vector( -0.012734, 0.953062, 0.302508 ), Vector( 0.212163, 0.701395, -0.680465 ), Vector( -0.799101, 0.397737, -0.450824 ), Vector( 0.787438, -0.559552, 0.258538 ), Vector( 0.009133, 0.673484, -0.739146 ), Vector( 0.529952, 0.346560, 0.773981 ), Vector( 0.372382, 0.605097, -0.703697 ), Vector( 0.461331, 0.524002, -0.715958 ), Vector( -0.750470, 0.654832, -0.089385 ), Vector( -0.389443, 0.539406, -0.746576 ), Vector( -0.952948, 0.294475, -0.071939 ), Vector( 0.777650, -0.266321, -0.569503 ), Vector( -0.283490, -0.172956, -0.943250 ), Vector( -0.975421, 0.178065, 0.129797 ), Vector( 0.672237, -0.433030, -0.600486 ), Vector( -0.807557, -0.589782, -0.003040 ), Vector( 0.649936, -0.297525, -0.699330 ), Vector( -0.620238, -0.594543, 0.511687 ), Vector( -0.000339, 0.430197, 0.902735 ), Vector( 0.668070, 0.722155, -0.179374 ), Vector( 0.725786, -0.634631, 0.265477 ), Vector( -0.557978, -0.784937, -0.269322 ), Vector( -0.210115, 0.882214, -0.421368 ), Vector( 0.944975, -0.278312, -0.171943 ), Vector( -0.702174, 0.586004, 0.404413 ), Vector( -0.777660, 0.116008, 0.617889 ), Vector( -0.426873, -0.901153, -0.075510 ), Vector( 0.313319, -0.949648, -0.000518 ), Vector( -0.114497, -0.894921, 0.431285 ), Vector( -0.011049, 0.575085, -0.818019 ), Vector( 0.158271, 0.160335, 0.974291 ), Vector( 0.690489, -0.172232, 0.702539 ), Vector( -0.267767, -0.955991, -0.119923 ), Vector( -0.219646, -0.974299, 0.049975 ), Vector( -0.282229, -0.620376, 0.731765 ), Vector( -0.852240, 0.199951, 0.483432 ), Vector( -0.513184, 0.205686, 0.833268 ), Vector( 0.338712, -0.749391, -0.568936 ), Vector( 0.896016, -0.257823, -0.361501 ), Vector( -0.795943, -0.073521, -0.600891 ), Vector( -0.608512, -0.145791, 0.780037 ), Vector( 0.702042, -0.688363, -0.182467 ), Vector( 0.284623, -0.765575, -0.576962 ), Vector( -0.433638, -0.464626, 0.772062 ), Vector( -0.409506, -0.450829, -0.793132 ), Vector( 0.378719, -0.746784, 0.546704 ), Vector( 0.646379, 0.003570, 0.763008 ), Vector( 0.443908, 0.531100, 0.721720 ), Vector( -0.896615, 0.289165, 0.335358 ), Vector( -0.863742, 0.343704, -0.368535 ), Vector( -0.083053, -0.579258, -0.810902 ), Vector( -0.204682, 0.014243, 0.978725 ), Vector( 0.075927, 0.262957, -0.961815 ), Vector( -0.363801, -0.901942, 0.232701 ), Vector( 0.996114, -0.005529, 0.087897 ), Vector( 0.782871, -0.242676, -0.572906 ), Vector( 0.087696, -0.994029, -0.064936 ), Vector( 0.561553, 0.810913, -0.164553 ), Vector( -0.699494, 0.579756, 0.417841 ), Vector( 0.348371, -0.577248, 0.738527 ), Vector( 0.441881, -0.819466, 0.364988 ), Vector( 0.774830, 0.370952, -0.511891 ), Vector( -0.397590, -0.292740, -0.869612 ), Vector( 0.074910, -0.439548, 0.895090 ), Vector( -0.198242, 0.967807, -0.155080 ), Vector( -0.987467, -0.036970, 0.153433 ), Vector( -0.958991, -0.087216, -0.269684 ), Vector( -0.663899, 0.494284, -0.561179 ), Vector( -0.167119, 0.769533, -0.616352 ), Vector( 0.234918, -0.812980, -0.532802 ), Vector( -0.037349, 0.031365, -0.998810 ), Vector( 0.917434, 0.065342, 0.392486 ), Vector( 0.463460, -0.864071, 0.196433 ), Vector( 0.236744, 0.644432, -0.727090 ), Vector( 0.860127, -0.065318, 0.505881 ), Vector( -0.386651, 0.838323, 0.384338 ), Vector( 0.242969, 0.491113, -0.836525 ), Vector( 0.772910, 0.286194, 0.566306 ), Vector( 0.264418, 0.403815, 0.875795 ), Vector( 0.872700, 0.487374, -0.029350 ), Vector( -0.050866, -0.734569, -0.676625 ), Vector( -0.773449, -0.272497, -0.572296 ), Vector( -0.202088, -0.863778, -0.461571 ), Vector( -0.050750, 0.912472, 0.405979 ), Vector( -0.044594, 0.989385, -0.138304 ), Vector( 0.140629, 0.966666, -0.213965 ), Vector( -0.405827, 0.874122, 0.266860 ), Vector( -0.690827, -0.114420, -0.713910 ), Vector( -0.630708, 0.669725, 0.392015 ), Vector( 0.848912, 0.454701, 0.269435 ), Vector( -0.016859, 0.683948, -0.729336 ), Vector( -0.402480, 0.914158, -0.048208 ), Vector( -0.961770, -0.084433, -0.260516 ), Vector( 0.398398, -0.850435, 0.343568 ), Vector( -0.724240, -0.446881, 0.525141 ), Vector( -0.414884, -0.439432, -0.796725 ), Vector( -0.331229, 0.825373, 0.457217 ), Vector( -0.497307, -0.798584, 0.339041 ), Vector( -0.993168, -0.107407, 0.045615 ), Vector( -0.075242, -0.230753, -0.970099 ),
40.895349
81
0.640176
[ "vector" ]
eacb744d29b9f1864590870db98ab40b7f3d02d7
7,554
h
C
FeatureGenerator/src/saliency/saliencyfilters/superpixel.h
langenhagen/Master-Thesis
72885bcfa2f7b76b85dabf70f060f60d53e20e51
[ "BSD-3-Clause" ]
1
2019-02-22T01:17:49.000Z
2019-02-22T01:17:49.000Z
FeatureGenerator/src/saliency/saliencyfilters/superpixel.h
langenhagen/Master-Thesis
72885bcfa2f7b76b85dabf70f060f60d53e20e51
[ "BSD-3-Clause" ]
null
null
null
FeatureGenerator/src/saliency/saliencyfilters/superpixel.h
langenhagen/Master-Thesis
72885bcfa2f7b76b85dabf70f060f60d53e20e51
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2012, Philipp Krähenbühl All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Philipp Krähenbühl ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Philipp Krähenbühl BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #pragma warning(push) #pragma warning(disable:4244) #include <opencv2/opencv.hpp> #include <random> // for geodesic segmentation aka cpu-slic struct SuperpixelStatistic { cv::Vec3f mean_color_; cv::Vec3f mean_rgb_; cv::Vec2f mean_position_; int size_; SuperpixelStatistic() : mean_color_( 0.f, 0.f, 0.f ), mean_position_( 0.f, 0.f ) {} }; class Superpixel { protected: int K_, n_iter_; float col_w_; bool geodesic_; public: Superpixel( int K, float col_w, int n_iter, bool geodesic=false ) : K_( K ), col_w_( col_w ), n_iter_(n_iter), geodesic_(geodesic) {} cv::Mat_<int> geodesicSegmentation( const cv::Mat_<cv::Vec3f> & im ) const; std::vector<SuperpixelStatistic> stat( const cv::Mat_< cv::Vec3f >& im, const cv::Mat_< cv::Vec3b >& rgb, const cv::Mat_< int >& segmentation ) const { using namespace cv; int K = nLabels( segmentation ); std::vector< SuperpixelStatistic > stat( K ); std::vector< double > cnt( K, 1e-10 ); for( int j=0; j<im.rows; j++ ) for( int i=0; i<im.cols; i++ ) { int l = segmentation( j, i ); if ( l >=0 ) { stat[ l ].mean_color_ += im(j,i); stat[ l ].mean_rgb_ += rgb(j,i); stat[ l ].mean_position_ += Vec2f( i, j ); cnt[ l ] += 1; } } for( int i=0; i<K; i++ ) { stat[ i ].mean_color_ *= 1.0 / cnt[ i ]; stat[ i ].mean_rgb_ *= 1.0 / cnt[ i ]; stat[ i ].mean_position_ *= 1.0 / cnt[ i ]; stat[ i ].size_ = cnt[ i ]; } // Rescale the position parameter for( int i=0; i<K; i++ ) stat[ i ].mean_position_ *= 1.0 / std::max( im.cols, im.rows ); return stat; } template< typename T > static cv::Mat_<T> assign( const std::vector<T> & val, const cv::Mat_<int> & segmentation ); int nLabels( const cv::Mat_< int >& segmentation ) const { int ret(0); for( int j=0; j<segmentation.rows; j++ ) for( int i=0; i<segmentation.cols; i++ ) if ( ret <= segmentation(j,i) ) ret = segmentation(j,i) + 1; return ret; } }; template< typename T > cv::Mat_<T> Superpixel::assign( const std::vector<T> & val, const cv::Mat_<int> & segmentation ) { cv::Mat_<T> r( segmentation.size() ); for( int j=0; j<segmentation.rows; j++ ) for( int i=0; i<segmentation.cols; i++ ) r(j,i) = val[ segmentation(j,i) ]; return r; } cv::Mat_< int > Superpixel::geodesicSegmentation( const cv::Mat_< cv::Vec3f >& im ) const { std::uniform_int_distribution<int> distribution(-2, 2); std::mt19937 engine; // Mersenne twister MT19937 auto randint = std::bind(distribution, engine); // Compute the spacing and grid size of the superpixels double sp_area = 1.0 * im.cols * im.rows / K_; int Kx = 0.5 + im.cols / sqrt( sp_area ), Ky = 0.5 + im.rows / sqrt( sp_area ); int K = Kx*Ky; int win_sz = 1.0 * sqrt(sp_area) + 1; // Initialize the seeds on a regular grid std::vector< int64_t > cnt( K ); std::vector< cv::Point2d > seedsd( K ); std::vector< cv::Point > seeds( K ); for( int i=0,k=0; i<Kx; i++ ) for( int j=0; j<Ky; j++, k++ ) seeds[k] = cv::Point( (i+0.5)*(im.cols-1)/Kx, (j+0.5)*(im.rows-1)/Ky ) + cv::Point( randint(), randint() ); cv::Mat_<float> dx( im.size() ), dy( im.size() ); for( int j=0; j<im.rows; j++ ) for( int i=0; i<im.cols; i++ ) { if (i) dx(j,i-1) = col_w_*sqrt( (im(j,i)-im(j,i-1)).dot(im(j,i)-im(j,i-1)) ) + 1; if (j) dy(j-1,i) = col_w_*sqrt( (im(j-1,i)-im(j,i)).dot(im(j-1,i)-im(j,i)) ) + 1; } // Run k-means cv::Mat_<float> dist( im.size() ); cv::Mat_<int> label( im.size() ); for( int it=0; it<n_iter_; it++ ) { // Assignment step dist = std::numeric_limits<float>::max(); label = -1; for( int k=0; k<K; k++ ) { dist( seeds[k] ) = 0; label( seeds[k] ) = k; } for( int IT=0; IT<2; IT++ ){ for( int j=0; j<im.rows; j++ ) for( int i=0; i<im.cols; i++ ) { if (i && dist(j,i-1) + dx(j,i-1) < dist(j,i)) { dist(j,i) = dist(j,i-1) + dx(j,i-1); label(j,i) = label(j,i-1); } if (j && dist(j-1,i) + dx(j-1,i) < dist(j,i)) { dist(j,i) = dist(j-1,i) + dy(j-1,i); label(j,i) = label(j-1,i); } } for( int j=im.rows-1; j>=0; j-- ) for( int i=im.cols-1; i>=0; i-- ) { if (i && dist(j,i) + dx(j,i-1) < dist(j,i-1)) { dist(j,i-1) = dist(j,i) + dx(j,i-1); label(j,i-1) = label(j,i); } if (j && dist(j,i) + dx(j-1,i) < dist(j-1,i)) { dist(j-1,i) = dist(j,i) + dy(j-1,i); label(j-1,i) = label(j,i); } } } for( int k=0; k<K; k++ ) { cv::Vec3f c = im( seeds[k] ); for( int j=std::max(0,seeds[k].y-win_sz); j<im.rows && j<=seeds[k].y+win_sz; j++ ) for( int i=std::max(0,seeds[k].x-win_sz); i<im.cols && i<=seeds[k].x+win_sz; i++ ){ double d = (i-seeds[k].x) * (i-seeds[k].x) + (j-seeds[k].y) * (j-seeds[k].y); double cd = ( im( j, i ) - c ).dot( im( j, i ) - c ); d += col_w_ * col_w_ * cd; if( d < dist( j, i ) ) { dist( j, i ) = d; label( j, i ) = k; } } } // Update for( int k=0; k<K; k++ ) { seedsd[k] = cv::Point2d(0,0); cnt[k] = 0; } for( int j=0; j<im.rows; j++ ) for( int i=0; i<im.cols; i++ ) { // Fix all the pixels we messed up! if ( label( j, i ) < 0 ) { // printf("Oops that wasn't very slick :(\n"); for( int k=0; k<K; k++ ){ cv::Vec3f c = im( seeds[k] ); double d = (i-seeds[k].x) * (i-seeds[k].x) + (j-seeds[k].y) * (j-seeds[k].y); double cd = ( im( j, i ) - c ).dot( im( j, i ) - c ); d += col_w_ * col_w_ * cd; if( d < dist( j, i ) ) { dist( j, i ) = d; label( j, i ) = k; } } } seedsd[ label( j, i ) ] += cv::Point2d( i, j ); cnt[ label( j, i ) ] += 1; } for( int k=0; k<K; k++ ) if (cnt[k] > 0) seeds[k] = cv::Point( 0.5 + seedsd[k].x / cnt[k], 0.5 + seedsd[k].y / cnt[k] ); } return label; } #pragma warning(pop)
32.701299
152
0.567514
[ "vector" ]
eace238221161499b69b83076222d8b1d810b63c
4,152
h
C
jni/WiEngine/include/grid/wyGrid3D.h
zchajax/WiEngine
ea2fa297f00aa5367bb5b819d6714ac84a8a8e25
[ "MIT" ]
39
2015-01-23T10:01:31.000Z
2021-06-10T03:01:18.000Z
jni/WiEngine/include/grid/wyGrid3D.h
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
1
2015-04-15T08:07:47.000Z
2015-04-15T08:07:47.000Z
jni/WiEngine/include/grid/wyGrid3D.h
luckypen/WiEngine
7e80641fe15a77a2fc43db90f15dad6aa2c2860a
[ "MIT" ]
20
2015-01-20T07:36:10.000Z
2019-09-15T01:02:19.000Z
/* * Copyright (c) 2010 WiYun Inc. * Author: luma(stubma@gmail.com) * * For all entities this program is free software; you can redistribute * it and/or modify it under the terms of the 'WiEngine' license with * the additional provision that 'WiEngine' must be credited in a manner * that can be be observed by end users, for example, in the credits or during * start up. (please find WiEngine logo in sdk's logo folder) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef __wyGrid3D_h__ #define __wyGrid3D_h__ #include "wyBaseGrid.h" #include "wyTypes.h" /** * @class wyBaseGrid * \if English * Grid3D is a type of grid which is operated in pixels. For example, the grid size is 2x2, * the total pixels would be 9 with 3 per row(column). Visually, the effect of this type of * grid is consistent, quit different from TileGrid3D whose effect is not consistent. * \else * Grid3D是以点为操作单位的一种网格,比如说网格的大小设置成2行2列,那么从点的角度看应该是每行每列都有 * 3个点,因此实际总共有9个点。而Grid3D的主要操作就针对这9个点来进行。因为操作是针对点进行的,因此 * 产生的效果具有视觉上的连续性,虽然图象可能出现扭曲变形,但是并不会分裂开,这是和TileGrid3D的主要区别。 * \endif */ class WIENGINE_API wyGrid3D : public wyBaseGrid { private: void calculateVertexPoints(); protected: /** * constructor * * @param w pixel width of grid * @param h pixel height of grid * @param c row count of the grid * @param r column count of the grid */ wyGrid3D(float w, float h, int c, int r); public: /** * \if English * Create a 3d grid * * @param w pixel width of grid * @param h pixel height of grid * @param c row count of the grid * @param r column count of the grid * \else * 创建一个3d网格 * * @param w 网格总宽度 * @param h 网格总高度 * @param c 网格列数 * @param r 网格行数 * \endif */ static wyGrid3D* make(float w, float h, int c, int r); /** * \if English * destructor * \else * 析构函数 * \endif */ virtual ~wyGrid3D(); /// @see wyBaseGrid::blit virtual void blit(); /// @see wyBaseGrid::reuse virtual void reuse(); /** * \if English * set vertex of a grid unit * * @param pos unit coordinates, \link wyDimension wyDimension\endlink * @param vertex the new vertex value of unit, \link wyVertex3D wyVertex3D \endlink * \else * 设置某位置的顶点坐标 * * @param pos 点的行列坐标\link wyDimension wyDimension结构\endlink * @param vertex \link wyVertex3D wyVertex3D结构\endlink * \endif */ void setVertex(wyDimension pos, wyVertex3D vertex); /** * \if English * get vertex of a grid unit * * @param pos unit coordinates, \link wyDimension wyDimension\endlink * \else * 获取某位置的顶点坐标 * * @param pos 点的行列坐标\link wyDimension wyDimension结构\endlink * \endif */ wyVertex3D getVertex(wyDimension pos); /** * \if English * get the initial vertex of a grid unit * * @param pos unit coordinates, \link wyDimension wyDimension\endlink * \else * 获取某位置的初始顶点坐标 * * @param pos 点的行列坐标\link wyDimension wyDimension结构\endlink * \endif */ wyVertex3D getOriginalVertex(wyDimension pos); }; #endif // __wyGrid3D_h__
29.446809
92
0.690511
[ "3d" ]
ead2b67032f7e578c16609b287d74c57dd60653e
6,919
h
C
include/vector.h
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
include/vector.h
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
include/vector.h
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef GESTURES_VECTOR_H__ #define GESTURES_VECTOR_H__ #include <algorithm> #include "gestures/include/logging.h" namespace gestures { // This class allows range-based for loops to iterate over a subset of // array elements, by only yielding those elements for which the // AcceptMethod returns true. // This class wraps around a pair of iterators, all changes to the // yielded elements will modify the original array. template <typename ValueType> class FilteredRange { public: typedef bool (*AcceptMethod)(const ValueType&); // This class defineds a basic forward iterator that iterates over // an array but skips elements for which the AcceptMethod yields false. class RangeIterator { public: // creates a new iterator and advances to the first accepted // element in the array. RangeIterator(ValueType* i, ValueType* end, AcceptMethod accept) : iter_(i), end_(end), accept_(accept) { NextAcceptedIter(); } // operator++ is required by the STL for forward iterators. // Instead of advancing to the next array element, this iterator // will advance to the next accepted array element ValueType* operator++ () { ++iter_; NextAcceptedIter(); return iter_; } // operator* is required by the STL for forward iterators. ValueType& operator*() { return *iter_; } // operator-> is required by the STL for forward iterators. ValueType& operator->() { return *iter_; } // operator!= is required by the STL for forward iterators. bool operator!= (const RangeIterator& o) { return iter_ != o.iter_; } // operator== is required by the STL for forward iterators. bool operator== (const RangeIterator& o) { return iter_ == o.iter_; } private: void NextAcceptedIter() { while (!accept_(*iter_) && iter_ != end_) ++iter_; } ValueType* iter_; ValueType* end_; AcceptMethod accept_; }; // Create a new filtered range from begin/end pointer to an array. FilteredRange(ValueType* begin, ValueType* end, AcceptMethod accept) : begin_(begin), end_(end), accept_(accept) {} // Returns a forward iterator to the first accepted element of the array. RangeIterator begin() { return RangeIterator(begin_, end_, accept_); } // Returns an iterator to the element after the last element of the array. RangeIterator end() { return RangeIterator(end_, end_, accept_); } private: ValueType* begin_; ValueType* end_; AcceptMethod accept_; }; // The vector class mimicks a subset of the std::vector functionality // while using a fixed size of memory to avoid calls to malloc/free. // The limitations of this class are: // - All insert operations might invalidate existing iterators // - Currently, the ValueType type should be a POD type or aggregate of PODs, // since ctors/dtors aren't called propertly on ValueType objects. // - Out of range element access will always return the end() iterator // and print an error, instead of throwing an exception. // This class includes a non-standard extension to return a // FilteredRange object iterating over the underlying array. template<typename ValueType, size_t kMaxSize> class vector { public: typedef ValueType value_type; typedef ValueType* iterator; typedef const ValueType* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef bool (*AcceptMethod)(const ValueType&); vector() : size_(0) {} vector(const vector<ValueType, kMaxSize>& that) { *this = that; } template<size_t kThatSize> vector(const vector<ValueType, kThatSize>& that) { *this = that; } size_t size() const { return size_; } bool empty() const { return size() == 0; } // methods for const element access const_iterator begin() const { return buffer_; } const_iterator end() const { return &buffer_[size_]; } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } const_iterator find(const ValueType& value) const { for (size_t i = 0; i < size_; ++i) if (buffer_[i] == value) return const_iterator(&buffer_[i]); return end(); } const ValueType& at(size_t idx) const { if (idx >= size()) { Err("vector::at: index out of range"); idx = size() - 1; } return buffer_[idx]; } const ValueType& operator[](size_t idx) const { return buffer_[idx]; } // methods for non-const element access: iterator begin() { return buffer_; } iterator end() { return &buffer_[size_]; } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } iterator find(const ValueType& value) { return const_cast<iterator>( const_cast<const vector<ValueType, kMaxSize>*>(this)->find(value)); } ValueType& at(size_t idx) { return const_cast<ValueType&>( const_cast<const vector<ValueType, kMaxSize>*>(this)->at(idx)); } ValueType& operator[](size_t idx) { return buffer_[idx]; } // methods for inserting elements // note that all these methods might invalidate existing iterators void push_back(const ValueType& value) { insert(end(), value); } iterator insert(iterator position, const ValueType& value) { return insert(position, &value, (&value) + 1); } iterator insert(iterator position, const_iterator first, const_iterator last) { size_t count = last - first; if (size_ + count > kMaxSize) { Err("vector::insert: out of space!"); return end(); } std::copy(rbegin(), reverse_iterator(position), reverse_iterator(end() + count)); size_ = size_ + count; std::copy(first, last, position); return position; } // methods for erasing elements // note that all these methods might invalidate existing iterators iterator erase(iterator it) { return erase(it, it + 1); } iterator erase(iterator first, iterator last) { size_t count = last - first; std::copy(last, end(), first); for (iterator it = end() - count, e = end(); it != e; ++it) (*it).~ValueType(); size_ = size_ - count; return first; } void clear() { erase(begin(), end()); } template<size_t kThatSize> vector<ValueType, kMaxSize>& operator=( const vector<ValueType, kThatSize>& that) { clear(); insert(begin(), that.begin(), that.end()); return *this; } private: ValueType buffer_[kMaxSize]; size_t size_; }; } // namespace gestures #endif // GESTURES_VECTOR_H__
30.082609
77
0.679578
[ "object", "vector" ]
ead672002718baf76a8f482ff7f5fafb8e2dfc47
51,448
c
C
openbsd/sys/kern/subr_pool.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
1
2019-10-15T06:29:32.000Z
2019-10-15T06:29:32.000Z
openbsd/sys/kern/subr_pool.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
null
null
null
openbsd/sys/kern/subr_pool.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
3
2017-01-09T02:15:36.000Z
2019-10-15T06:30:25.000Z
/* $OpenBSD: subr_pool.c,v 1.39 2003/11/18 06:08:18 tedu Exp $ */ /* $NetBSD: subr_pool.c,v 1.61 2001/09/26 07:14:56 chs Exp $ */ /*- * Copyright (c) 1997, 1999, 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Paul Kranenburg; by Jason R. Thorpe of the Numerical Aerospace * Simulation Facility, NASA Ames Research Center. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/proc.h> #include <sys/errno.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/lock.h> #include <sys/pool.h> #include <sys/syslog.h> #include <sys/sysctl.h> #include <uvm/uvm.h> /* * XXX - for now. */ #define SIMPLELOCK_INITIALIZER { SLOCK_UNLOCKED } #ifdef LOCKDEBUG #define simple_lock_freecheck(a, s) do { /* nothing */ } while (0) #define simple_lock_only_held(lkp, str) do { /* nothing */ } while (0) #endif /* * Pool resource management utility. * * Memory is allocated in pages which are split into pieces according to * the pool item size. Each page is kept on one of three lists in the * pool structure: `pr_emptypages', `pr_fullpages' and `pr_partpages', * for empty, full and partially-full pages respectively. The individual * pool items are on a linked list headed by `ph_itemlist' in each page * header. The memory for building the page list is either taken from * the allocated pages themselves (for small pool items) or taken from * an internal pool of page headers (`phpool'). */ /* List of all pools */ TAILQ_HEAD(,pool) pool_head = TAILQ_HEAD_INITIALIZER(pool_head); /* Private pool for page header structures */ static struct pool phpool; /* # of seconds to retain page after last use */ int pool_inactive_time = 10; /* Next candidate for drainage (see pool_drain()) */ static struct pool *drainpp; /* This spin lock protects both pool_head and drainpp. */ struct simplelock pool_head_slock = SIMPLELOCK_INITIALIZER; struct pool_item_header { /* Page headers */ LIST_ENTRY(pool_item_header) ph_pagelist; /* pool page list */ TAILQ_HEAD(,pool_item) ph_itemlist; /* chunk list for this page */ SPLAY_ENTRY(pool_item_header) ph_node; /* Off-page page headers */ int ph_nmissing; /* # of chunks in use */ caddr_t ph_page; /* this page's address */ struct timeval ph_time; /* last referenced */ }; struct pool_item { #ifdef DIAGNOSTIC int pi_magic; #endif #define PI_MAGIC 0xdeafbeef /* Other entries use only this list entry */ TAILQ_ENTRY(pool_item) pi_list; }; #define POOL_NEEDS_CATCHUP(pp) \ ((pp)->pr_nitems < (pp)->pr_minitems) /* * Every pool get a unique serial number assigned to it. If this counter * wraps, we're screwed, but we shouldn't create so many pools anyway. */ unsigned int pool_serial; /* * Pool cache management. * * Pool caches provide a way for constructed objects to be cached by the * pool subsystem. This can lead to performance improvements by avoiding * needless object construction/destruction; it is deferred until absolutely * necessary. * * Caches are grouped into cache groups. Each cache group references * up to 16 constructed objects. When a cache allocates an object * from the pool, it calls the object's constructor and places it into * a cache group. When a cache group frees an object back to the pool, * it first calls the object's destructor. This allows the object to * persist in constructed form while freed to the cache. * * Multiple caches may exist for each pool. This allows a single * object type to have multiple constructed forms. The pool references * each cache, so that when a pool is drained by the pagedaemon, it can * drain each individual cache as well. Each time a cache is drained, * the most idle cache group is freed to the pool in its entirety. * * Pool caches are layed on top of pools. By layering them, we can avoid * the complexity of cache management for pools which would not benefit * from it. */ /* The cache group pool. */ static struct pool pcgpool; /* The pool cache group. */ #define PCG_NOBJECTS 16 struct pool_cache_group { TAILQ_ENTRY(pool_cache_group) pcg_list; /* link in the pool cache's group list */ u_int pcg_avail; /* # available objects */ /* pointers to the objects */ void *pcg_objects[PCG_NOBJECTS]; }; void pool_cache_reclaim(struct pool_cache *); void pool_cache_do_invalidate(struct pool_cache *, int, void (*)(struct pool *, void *)); int pool_catchup(struct pool *); void pool_prime_page(struct pool *, caddr_t, struct pool_item_header *); void pool_update_curpage(struct pool *); void pool_do_put(struct pool *, void *); void pr_rmpage(struct pool *, struct pool_item_header *, struct pool_pagelist *); int pool_chk_page(struct pool *, const char *, struct pool_item_header *); void *pool_allocator_alloc(struct pool *, int); void pool_allocator_free(struct pool *, void *); void pool_print_pagelist(struct pool_pagelist *, int (*)(const char *, ...)); void pool_print1(struct pool *, const char *, int (*)(const char *, ...)); /* * Pool log entry. An array of these is allocated in pool_init(). */ struct pool_log { const char *pl_file; long pl_line; int pl_action; #define PRLOG_GET 1 #define PRLOG_PUT 2 void *pl_addr; }; /* Number of entries in pool log buffers */ #ifndef POOL_LOGSIZE #define POOL_LOGSIZE 10 #endif int pool_logsize = POOL_LOGSIZE; #ifdef POOL_DIAGNOSTIC static __inline void pr_log(struct pool *pp, void *v, int action, const char *file, long line) { int n = pp->pr_curlogentry; struct pool_log *pl; if ((pp->pr_roflags & PR_LOGGING) == 0) return; /* * Fill in the current entry. Wrap around and overwrite * the oldest entry if necessary. */ pl = &pp->pr_log[n]; pl->pl_file = file; pl->pl_line = line; pl->pl_action = action; pl->pl_addr = v; if (++n >= pp->pr_logsize) n = 0; pp->pr_curlogentry = n; } static void pr_printlog(struct pool *pp, struct pool_item *pi, int (*pr)(const char *, ...)) { int i = pp->pr_logsize; int n = pp->pr_curlogentry; if ((pp->pr_roflags & PR_LOGGING) == 0) return; /* * Print all entries in this pool's log. */ while (i-- > 0) { struct pool_log *pl = &pp->pr_log[n]; if (pl->pl_action != 0) { if (pi == NULL || pi == pl->pl_addr) { (*pr)("\tlog entry %d:\n", i); (*pr)("\t\taction = %s, addr = %p\n", pl->pl_action == PRLOG_GET ? "get" : "put", pl->pl_addr); (*pr)("\t\tfile: %s at line %lu\n", pl->pl_file, pl->pl_line); } } if (++n >= pp->pr_logsize) n = 0; } } static __inline void pr_enter(struct pool *pp, const char *file, long line) { if (__predict_false(pp->pr_entered_file != NULL)) { printf("pool %s: reentrancy at file %s line %ld\n", pp->pr_wchan, file, line); printf(" previous entry at file %s line %ld\n", pp->pr_entered_file, pp->pr_entered_line); panic("pr_enter"); } pp->pr_entered_file = file; pp->pr_entered_line = line; } static __inline void pr_leave(struct pool *pp) { if (__predict_false(pp->pr_entered_file == NULL)) { printf("pool %s not entered?\n", pp->pr_wchan); panic("pr_leave"); } pp->pr_entered_file = NULL; pp->pr_entered_line = 0; } static __inline void pr_enter_check(struct pool *pp, int (*pr)(const char *, ...)) { if (pp->pr_entered_file != NULL) (*pr)("\n\tcurrently entered from file %s line %ld\n", pp->pr_entered_file, pp->pr_entered_line); } #else #define pr_log(pp, v, action, file, line) #define pr_printlog(pp, pi, pr) #define pr_enter(pp, file, line) #define pr_leave(pp) #define pr_enter_check(pp, pr) #endif /* POOL_DIAGNOSTIC */ static __inline int phtree_compare(struct pool_item_header *a, struct pool_item_header *b) { if (a->ph_page < b->ph_page) return (-1); else if (a->ph_page > b->ph_page) return (1); else return (0); } SPLAY_PROTOTYPE(phtree, pool_item_header, ph_node, phtree_compare); SPLAY_GENERATE(phtree, pool_item_header, ph_node, phtree_compare); /* * Return the pool page header based on page address. */ static __inline struct pool_item_header * pr_find_pagehead(struct pool *pp, caddr_t page) { struct pool_item_header *ph, tmp; if ((pp->pr_roflags & PR_PHINPAGE) != 0) return ((struct pool_item_header *)(page + pp->pr_phoffset)); tmp.ph_page = page; ph = SPLAY_FIND(phtree, &pp->pr_phtree, &tmp); return ph; } /* * Remove a page from the pool. */ void pr_rmpage(struct pool *pp, struct pool_item_header *ph, struct pool_pagelist *pq) { int s; /* * If the page was idle, decrement the idle page count. */ if (ph->ph_nmissing == 0) { #ifdef DIAGNOSTIC if (pp->pr_nidle == 0) panic("pr_rmpage: nidle inconsistent"); if (pp->pr_nitems < pp->pr_itemsperpage) panic("pr_rmpage: nitems inconsistent"); #endif pp->pr_nidle--; } pp->pr_nitems -= pp->pr_itemsperpage; /* * Unlink a page from the pool and release it (or queue it for release). */ LIST_REMOVE(ph, ph_pagelist); if (pq) { LIST_INSERT_HEAD(pq, ph, ph_pagelist); } else { pool_allocator_free(pp, ph->ph_page); if ((pp->pr_roflags & PR_PHINPAGE) == 0) { SPLAY_REMOVE(phtree, &pp->pr_phtree, ph); s = splhigh(); pool_put(&phpool, ph); splx(s); } } pp->pr_npages--; pp->pr_npagefree++; pool_update_curpage(pp); } /* * Initialize the given pool resource structure. * * We export this routine to allow other kernel parts to declare * static pools that must be initialized before malloc() is available. */ void pool_init(struct pool *pp, size_t size, u_int align, u_int ioff, int flags, const char *wchan, struct pool_allocator *palloc) { int off, slack; #ifdef POOL_DIAGNOSTIC /* * Always log if POOL_DIAGNOSTIC is defined. */ if (pool_logsize != 0) flags |= PR_LOGGING; #endif #ifdef MALLOC_DEBUG if ((flags & PR_DEBUG) && (ioff != 0 || align != 0)) flags &= ~PR_DEBUG; #endif /* * Check arguments and construct default values. */ if (palloc == NULL) palloc = &pool_allocator_kmem; if ((palloc->pa_flags & PA_INITIALIZED) == 0) { if (palloc->pa_pagesz == 0) palloc->pa_pagesz = PAGE_SIZE; TAILQ_INIT(&palloc->pa_list); simple_lock_init(&palloc->pa_slock); palloc->pa_pagemask = ~(palloc->pa_pagesz - 1); palloc->pa_pageshift = ffs(palloc->pa_pagesz) - 1; palloc->pa_flags |= PA_INITIALIZED; } if (align == 0) align = ALIGN(1); if (size < sizeof(struct pool_item)) size = sizeof(struct pool_item); size = roundup(size, align); #ifdef DIAGNOSTIC if (size > palloc->pa_pagesz) panic("pool_init: pool item size (%lu) too large", (u_long)size); #endif /* * Initialize the pool structure. */ LIST_INIT(&pp->pr_emptypages); LIST_INIT(&pp->pr_fullpages); LIST_INIT(&pp->pr_partpages); TAILQ_INIT(&pp->pr_cachelist); pp->pr_curpage = NULL; pp->pr_npages = 0; pp->pr_minitems = 0; pp->pr_minpages = 0; pp->pr_maxpages = UINT_MAX; pp->pr_roflags = flags; pp->pr_flags = 0; pp->pr_size = size; pp->pr_align = align; pp->pr_wchan = wchan; pp->pr_alloc = palloc; pp->pr_nitems = 0; pp->pr_nout = 0; pp->pr_hardlimit = UINT_MAX; pp->pr_hardlimit_warning = NULL; pp->pr_hardlimit_ratecap.tv_sec = 0; pp->pr_hardlimit_ratecap.tv_usec = 0; pp->pr_hardlimit_warning_last.tv_sec = 0; pp->pr_hardlimit_warning_last.tv_usec = 0; pp->pr_drain_hook = NULL; pp->pr_drain_hook_arg = NULL; pp->pr_serial = ++pool_serial; if (pool_serial == 0) panic("pool_init: too much uptime"); /* * Decide whether to put the page header off page to avoid * wasting too large a part of the page. Off-page page headers * go on a hash table, so we can match a returned item * with its header based on the page address. * We use 1/16 of the page size as the threshold (XXX: tune) */ if (pp->pr_size < palloc->pa_pagesz/16) { /* Use the end of the page for the page header */ pp->pr_roflags |= PR_PHINPAGE; pp->pr_phoffset = off = palloc->pa_pagesz - ALIGN(sizeof(struct pool_item_header)); } else { /* The page header will be taken from our page header pool */ pp->pr_phoffset = 0; off = palloc->pa_pagesz; SPLAY_INIT(&pp->pr_phtree); } /* * Alignment is to take place at `ioff' within the item. This means * we must reserve up to `align - 1' bytes on the page to allow * appropriate positioning of each item. * * Silently enforce `0 <= ioff < align'. */ pp->pr_itemoffset = ioff = ioff % align; pp->pr_itemsperpage = (off - ((align - ioff) % align)) / pp->pr_size; KASSERT(pp->pr_itemsperpage != 0); /* * Use the slack between the chunks and the page header * for "cache coloring". */ slack = off - pp->pr_itemsperpage * pp->pr_size; pp->pr_maxcolor = (slack / align) * align; pp->pr_curcolor = 0; pp->pr_nget = 0; pp->pr_nfail = 0; pp->pr_nput = 0; pp->pr_npagealloc = 0; pp->pr_npagefree = 0; pp->pr_hiwat = 0; pp->pr_nidle = 0; #ifdef POOL_DIAGNOSTIC if (flags & PR_LOGGING) { if (kmem_map == NULL || (pp->pr_log = malloc(pool_logsize * sizeof(struct pool_log), M_TEMP, M_NOWAIT)) == NULL) pp->pr_roflags &= ~PR_LOGGING; pp->pr_curlogentry = 0; pp->pr_logsize = pool_logsize; } #endif pp->pr_entered_file = NULL; pp->pr_entered_line = 0; simple_lock_init(&pp->pr_slock); /* * Initialize private page header pool and cache magazine pool if we * haven't done so yet. * XXX LOCKING. */ if (phpool.pr_size == 0) { pool_init(&phpool, sizeof(struct pool_item_header), 0, 0, 0, "phpool", NULL); pool_init(&pcgpool, sizeof(struct pool_cache_group), 0, 0, 0, "pcgpool", NULL); } /* Insert this into the list of all pools. */ simple_lock(&pool_head_slock); TAILQ_INSERT_TAIL(&pool_head, pp, pr_poollist); simple_unlock(&pool_head_slock); /* Insert into the list of pools using this allocator. */ simple_lock(&palloc->pa_slock); TAILQ_INSERT_TAIL(&palloc->pa_list, pp, pr_alloc_list); simple_unlock(&palloc->pa_slock); } /* * De-commision a pool resource. */ void pool_destroy(struct pool *pp) { struct pool_item_header *ph; struct pool_cache *pc; /* Locking order: pool_allocator -> pool */ simple_lock(&pp->pr_alloc->pa_slock); TAILQ_REMOVE(&pp->pr_alloc->pa_list, pp, pr_alloc_list); simple_unlock(&pp->pr_alloc->pa_slock); /* Destroy all caches for this pool. */ while ((pc = TAILQ_FIRST(&pp->pr_cachelist)) != NULL) pool_cache_destroy(pc); #ifdef DIAGNOSTIC if (pp->pr_nout != 0) { pr_printlog(pp, NULL, printf); panic("pool_destroy: pool busy: still out: %u", pp->pr_nout); } #endif /* Remove all pages */ while ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL) pr_rmpage(pp, ph, NULL); KASSERT(LIST_EMPTY(&pp->pr_fullpages)); KASSERT(LIST_EMPTY(&pp->pr_partpages)); /* Remove from global pool list */ simple_lock(&pool_head_slock); TAILQ_REMOVE(&pool_head, pp, pr_poollist); if (drainpp == pp) { drainpp = NULL; } simple_unlock(&pool_head_slock); #ifdef POOL_DIAGNOSTIC if ((pp->pr_roflags & PR_LOGGING) != 0) free(pp->pr_log, M_TEMP); #endif } void pool_set_drain_hook(struct pool *pp, void (*fn)(void *, int), void *arg) { /* XXX no locking -- must be used just after pool_init() */ #ifdef DIAGNOSTIC if (pp->pr_drain_hook != NULL) panic("pool_set_drain_hook(%s): already set", pp->pr_wchan); #endif pp->pr_drain_hook = fn; pp->pr_drain_hook_arg = arg; } static struct pool_item_header * pool_alloc_item_header(struct pool *pp, caddr_t storage, int flags) { struct pool_item_header *ph; int s; LOCK_ASSERT(simple_lock_held(&pp->pr_slock) == 0); if ((pp->pr_roflags & PR_PHINPAGE) != 0) ph = (struct pool_item_header *) (storage + pp->pr_phoffset); else { s = splhigh(); ph = pool_get(&phpool, flags); splx(s); } return (ph); } /* * Grab an item from the pool; must be called at appropriate spl level */ void * #ifdef POOL_DIAGNOSTIC _pool_get(struct pool *pp, int flags, const char *file, long line) #else pool_get(struct pool *pp, int flags) #endif { struct pool_item *pi; struct pool_item_header *ph; void *v; #ifdef DIAGNOSTIC if ((flags & PR_WAITOK) != 0) splassert(IPL_NONE); if (__predict_false(curproc == NULL && /* doing_shutdown == 0 && XXX*/ (flags & PR_WAITOK) != 0)) panic("pool_get: %s:must have NOWAIT", pp->pr_wchan); #ifdef LOCKDEBUG if (flags & PR_WAITOK) simple_lock_only_held(NULL, "pool_get(PR_WAITOK)"); #endif #endif /* DIAGNOSTIC */ #ifdef MALLOC_DEBUG if (pp->pr_roflags & PR_DEBUG) { void *addr; addr = NULL; debug_malloc(pp->pr_size, M_DEBUG, (flags & PR_WAITOK) ? M_WAITOK : M_NOWAIT, &addr); return (addr); } #endif simple_lock(&pp->pr_slock); pr_enter(pp, file, line); startover: /* * Check to see if we've reached the hard limit. If we have, * and we can wait, then wait until an item has been returned to * the pool. */ #ifdef DIAGNOSTIC if (__predict_false(pp->pr_nout > pp->pr_hardlimit)) { pr_leave(pp); simple_unlock(&pp->pr_slock); panic("pool_get: %s: crossed hard limit", pp->pr_wchan); } #endif if (__predict_false(pp->pr_nout == pp->pr_hardlimit)) { if (pp->pr_drain_hook != NULL) { /* * Since the drain hook is going to free things * back to the pool, unlock, call hook, re-lock * and check hardlimit condition again. */ pr_leave(pp); simple_unlock(&pp->pr_slock); (*pp->pr_drain_hook)(pp->pr_drain_hook_arg, flags); simple_lock(&pp->pr_slock); pr_enter(pp, file, line); if (pp->pr_nout < pp->pr_hardlimit) goto startover; } if ((flags & PR_WAITOK) && !(flags & PR_LIMITFAIL)) { /* * XXX: A warning isn't logged in this case. Should * it be? */ pp->pr_flags |= PR_WANTED; pr_leave(pp); ltsleep(pp, PSWP, pp->pr_wchan, 0, &pp->pr_slock); pr_enter(pp, file, line); goto startover; } /* * Log a message that the hard limit has been hit. */ if (pp->pr_hardlimit_warning != NULL && ratecheck(&pp->pr_hardlimit_warning_last, &pp->pr_hardlimit_ratecap)) log(LOG_ERR, "%s\n", pp->pr_hardlimit_warning); pp->pr_nfail++; pr_leave(pp); simple_unlock(&pp->pr_slock); return (NULL); } /* * The convention we use is that if `curpage' is not NULL, then * it points at a non-empty bucket. In particular, `curpage' * never points at a page header which has PR_PHINPAGE set and * has no items in its bucket. */ if ((ph = pp->pr_curpage) == NULL) { #ifdef DIAGNOSTIC if (pp->pr_nitems != 0) { simple_unlock(&pp->pr_slock); printf("pool_get: %s: curpage NULL, nitems %u\n", pp->pr_wchan, pp->pr_nitems); panic("pool_get: nitems inconsistent"); } #endif /* * Call the back-end page allocator for more memory. * Release the pool lock, as the back-end page allocator * may block. */ pr_leave(pp); simple_unlock(&pp->pr_slock); v = pool_allocator_alloc(pp, flags); if (__predict_true(v != NULL)) ph = pool_alloc_item_header(pp, v, flags); simple_lock(&pp->pr_slock); pr_enter(pp, file, line); if (__predict_false(v == NULL || ph == NULL)) { if (v != NULL) pool_allocator_free(pp, v); /* * We were unable to allocate a page or item * header, but we released the lock during * allocation, so perhaps items were freed * back to the pool. Check for this case. */ if (pp->pr_curpage != NULL) goto startover; if ((flags & PR_WAITOK) == 0) { pp->pr_nfail++; pr_leave(pp); simple_unlock(&pp->pr_slock); return (NULL); } /* * Wait for items to be returned to this pool. * * XXX: maybe we should wake up once a second and * try again? */ pp->pr_flags |= PR_WANTED; /* PA_WANTED is already set on the allocator. */ pr_leave(pp); ltsleep(pp, PSWP, pp->pr_wchan, 0, &pp->pr_slock); pr_enter(pp, file, line); goto startover; } /* We have more memory; add it to the pool */ pool_prime_page(pp, v, ph); pp->pr_npagealloc++; /* Start the allocation process over. */ goto startover; } if (__predict_false((v = pi = TAILQ_FIRST(&ph->ph_itemlist)) == NULL)) { pr_leave(pp); simple_unlock(&pp->pr_slock); panic("pool_get: %s: page empty", pp->pr_wchan); } #ifdef DIAGNOSTIC if (__predict_false(pp->pr_nitems == 0)) { pr_leave(pp); simple_unlock(&pp->pr_slock); printf("pool_get: %s: items on itemlist, nitems %u\n", pp->pr_wchan, pp->pr_nitems); panic("pool_get: nitems inconsistent"); } #endif #ifdef POOL_DIAGNOSTIC pr_log(pp, v, PRLOG_GET, file, line); #endif #ifdef DIAGNOSTIC if (__predict_false(pi->pi_magic != PI_MAGIC)) { pr_printlog(pp, pi, printf); panic("pool_get(%s): free list modified: magic=%x; page %p;" " item addr %p", pp->pr_wchan, pi->pi_magic, ph->ph_page, pi); } #endif /* * Remove from item list. */ TAILQ_REMOVE(&ph->ph_itemlist, pi, pi_list); pp->pr_nitems--; pp->pr_nout++; if (ph->ph_nmissing == 0) { #ifdef DIAGNOSTIC if (__predict_false(pp->pr_nidle == 0)) panic("pool_get: nidle inconsistent"); #endif pp->pr_nidle--; /* * This page was previously empty. Move it to the list of * partially-full pages. This page is already curpage. */ LIST_REMOVE(ph, ph_pagelist); LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist); } ph->ph_nmissing++; if (TAILQ_EMPTY(&ph->ph_itemlist)) { #ifdef DIAGNOSTIC if (__predict_false(ph->ph_nmissing != pp->pr_itemsperpage)) { pr_leave(pp); simple_unlock(&pp->pr_slock); panic("pool_get: %s: nmissing inconsistent", pp->pr_wchan); } #endif /* * This page is now full. Move it to the full list * and select a new current page. */ LIST_REMOVE(ph, ph_pagelist); LIST_INSERT_HEAD(&pp->pr_fullpages, ph, ph_pagelist); pool_update_curpage(pp); } pp->pr_nget++; /* * If we have a low water mark and we are now below that low * water mark, add more items to the pool. */ if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) { /* * XXX: Should we log a warning? Should we set up a timeout * to try again in a second or so? The latter could break * a caller's assumptions about interrupt protection, etc. */ } pr_leave(pp); simple_unlock(&pp->pr_slock); return (v); } /* * Internal version of pool_put(). Pool is already locked/entered. */ void pool_do_put(struct pool *pp, void *v) { struct pool_item *pi = v; struct pool_item_header *ph; caddr_t page; int s; #ifdef MALLOC_DEBUG if (pp->pr_roflags & PR_DEBUG) { debug_free(v, M_DEBUG); return; } #endif LOCK_ASSERT(simple_lock_held(&pp->pr_slock)); page = (caddr_t)((vaddr_t)v & pp->pr_alloc->pa_pagemask); #ifdef DIAGNOSTIC if (__predict_false(pp->pr_nout == 0)) { printf("pool %s: putting with none out\n", pp->pr_wchan); panic("pool_put"); } #endif if (__predict_false((ph = pr_find_pagehead(pp, page)) == NULL)) { pr_printlog(pp, NULL, printf); panic("pool_put: %s: page header missing", pp->pr_wchan); } #ifdef LOCKDEBUG /* * Check if we're freeing a locked simple lock. */ simple_lock_freecheck((caddr_t)pi, ((caddr_t)pi) + pp->pr_size); #endif /* * Return to item list. */ #ifdef DIAGNOSTIC pi->pi_magic = PI_MAGIC; #endif #ifdef DEBUG { int i, *ip = v; for (i = 0; i < pp->pr_size / sizeof(int); i++) { *ip++ = PI_MAGIC; } } #endif TAILQ_INSERT_HEAD(&ph->ph_itemlist, pi, pi_list); ph->ph_nmissing--; pp->pr_nput++; pp->pr_nitems++; pp->pr_nout--; /* Cancel "pool empty" condition if it exists */ if (pp->pr_curpage == NULL) pp->pr_curpage = ph; if (pp->pr_flags & PR_WANTED) { pp->pr_flags &= ~PR_WANTED; if (ph->ph_nmissing == 0) pp->pr_nidle++; wakeup((caddr_t)pp); return; } /* * If this page is now empty, do one of two things: * * (1) If we have more pages than the page high water mark, * free the page back to the system. * * (2) Otherwise, move the page to the empty page list. * * Either way, select a new current page (so we use a partially-full * page if one is available). */ if (ph->ph_nmissing == 0) { pp->pr_nidle++; if (pp->pr_npages > pp->pr_maxpages || (pp->pr_alloc->pa_flags & PA_WANT) != 0) { pr_rmpage(pp, ph, NULL); } else { LIST_REMOVE(ph, ph_pagelist); LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist); /* * Update the timestamp on the page. A page must * be idle for some period of time before it can * be reclaimed by the pagedaemon. This minimizes * ping-pong'ing for memory. */ s = splclock(); ph->ph_time = mono_time; splx(s); } pool_update_curpage(pp); } /* * If the page was previously completely full, move it to the * partially-full list and make it the current page. The next * allocation will get the item from this page, instead of * further fragmenting the pool. */ else if (ph->ph_nmissing == (pp->pr_itemsperpage - 1)) { LIST_REMOVE(ph, ph_pagelist); LIST_INSERT_HEAD(&pp->pr_partpages, ph, ph_pagelist); pp->pr_curpage = ph; } } /* * Return resource to the pool; must be called at appropriate spl level */ #ifdef POOL_DIAGNOSTIC void _pool_put(struct pool *pp, void *v, const char *file, long line) { simple_lock(&pp->pr_slock); pr_enter(pp, file, line); pr_log(pp, v, PRLOG_PUT, file, line); pool_do_put(pp, v); pr_leave(pp); simple_unlock(&pp->pr_slock); } #undef pool_put #endif /* POOL_DIAGNOSTIC */ void pool_put(struct pool *pp, void *v) { simple_lock(&pp->pr_slock); pool_do_put(pp, v); simple_unlock(&pp->pr_slock); } #ifdef POOL_DIAGNOSTIC #define pool_put(h, v) _pool_put((h), (v), __FILE__, __LINE__) #endif /* * Add N items to the pool. */ int pool_prime(struct pool *pp, int n) { struct pool_item_header *ph; caddr_t cp; int newpages; simple_lock(&pp->pr_slock); newpages = roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage; while (newpages-- > 0) { simple_unlock(&pp->pr_slock); cp = pool_allocator_alloc(pp, PR_NOWAIT); if (__predict_true(cp != NULL)) ph = pool_alloc_item_header(pp, cp, PR_NOWAIT); simple_lock(&pp->pr_slock); if (__predict_false(cp == NULL || ph == NULL)) { if (cp != NULL) pool_allocator_free(pp, cp); break; } pool_prime_page(pp, cp, ph); pp->pr_npagealloc++; pp->pr_minpages++; } if (pp->pr_minpages >= pp->pr_maxpages) pp->pr_maxpages = pp->pr_minpages + 1; /* XXX */ simple_unlock(&pp->pr_slock); return (0); } /* * Add a page worth of items to the pool. * * Note, we must be called with the pool descriptor LOCKED. */ void pool_prime_page(struct pool *pp, caddr_t storage, struct pool_item_header *ph) { struct pool_item *pi; caddr_t cp = storage; unsigned int align = pp->pr_align; unsigned int ioff = pp->pr_itemoffset; int n; #ifdef DIAGNOSTIC if (((u_long)cp & (pp->pr_alloc->pa_pagesz - 1)) != 0) panic("pool_prime_page: %s: unaligned page", pp->pr_wchan); #endif /* * Insert page header. */ LIST_INSERT_HEAD(&pp->pr_emptypages, ph, ph_pagelist); TAILQ_INIT(&ph->ph_itemlist); ph->ph_page = storage; ph->ph_nmissing = 0; memset(&ph->ph_time, 0, sizeof(ph->ph_time)); if ((pp->pr_roflags & PR_PHINPAGE) == 0) SPLAY_INSERT(phtree, &pp->pr_phtree, ph); pp->pr_nidle++; /* * Color this page. */ cp = (caddr_t)(cp + pp->pr_curcolor); if ((pp->pr_curcolor += align) > pp->pr_maxcolor) pp->pr_curcolor = 0; /* * Adjust storage to apply aligment to `pr_itemoffset' in each item. */ if (ioff != 0) cp = (caddr_t)(cp + (align - ioff)); /* * Insert remaining chunks on the bucket list. */ n = pp->pr_itemsperpage; pp->pr_nitems += n; while (n--) { pi = (struct pool_item *)cp; KASSERT(((((vaddr_t)pi) + ioff) & (align - 1)) == 0); /* Insert on page list */ TAILQ_INSERT_TAIL(&ph->ph_itemlist, pi, pi_list); #ifdef DIAGNOSTIC pi->pi_magic = PI_MAGIC; #endif cp = (caddr_t)(cp + pp->pr_size); } /* * If the pool was depleted, point at the new page. */ if (pp->pr_curpage == NULL) pp->pr_curpage = ph; if (++pp->pr_npages > pp->pr_hiwat) pp->pr_hiwat = pp->pr_npages; } /* * Used by pool_get() when nitems drops below the low water mark. This * is used to catch up pr_nitems with the low water mark. * * Note 1, we never wait for memory here, we let the caller decide what to do. * * Note 2, we must be called with the pool already locked, and we return * with it locked. */ int pool_catchup(struct pool *pp) { struct pool_item_header *ph; caddr_t cp; int error = 0; while (POOL_NEEDS_CATCHUP(pp)) { /* * Call the page back-end allocator for more memory. * * XXX: We never wait, so should we bother unlocking * the pool descriptor? */ simple_unlock(&pp->pr_slock); cp = pool_allocator_alloc(pp, PR_NOWAIT); if (__predict_true(cp != NULL)) ph = pool_alloc_item_header(pp, cp, PR_NOWAIT); simple_lock(&pp->pr_slock); if (__predict_false(cp == NULL || ph == NULL)) { if (cp != NULL) pool_allocator_free(pp, cp); error = ENOMEM; break; } pool_prime_page(pp, cp, ph); pp->pr_npagealloc++; } return (error); } void pool_update_curpage(struct pool *pp) { pp->pr_curpage = LIST_FIRST(&pp->pr_partpages); if (pp->pr_curpage == NULL) { pp->pr_curpage = LIST_FIRST(&pp->pr_emptypages); } } void pool_setlowat(struct pool *pp, int n) { simple_lock(&pp->pr_slock); pp->pr_minitems = n; pp->pr_minpages = (n == 0) ? 0 : roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage; /* Make sure we're caught up with the newly-set low water mark. */ if (POOL_NEEDS_CATCHUP(pp) && pool_catchup(pp) != 0) { /* * XXX: Should we log a warning? Should we set up a timeout * to try again in a second or so? The latter could break * a caller's assumptions about interrupt protection, etc. */ } simple_unlock(&pp->pr_slock); } void pool_sethiwat(struct pool *pp, int n) { simple_lock(&pp->pr_slock); pp->pr_maxpages = (n == 0) ? 0 : roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage; simple_unlock(&pp->pr_slock); } int pool_sethardlimit(struct pool *pp, unsigned n, const char *warnmess, int ratecap) { int error = 0; simple_lock(&pp->pr_slock); if (n < pp->pr_nout) { error = EINVAL; goto done; } pp->pr_hardlimit = n; pp->pr_hardlimit_warning = warnmess; pp->pr_hardlimit_ratecap.tv_sec = ratecap; pp->pr_hardlimit_warning_last.tv_sec = 0; pp->pr_hardlimit_warning_last.tv_usec = 0; /* * In-line version of pool_sethiwat(), because we don't want to * release the lock. */ pp->pr_maxpages = (n == 0 || n == UINT_MAX) ? n : roundup(n, pp->pr_itemsperpage) / pp->pr_itemsperpage; done: simple_unlock(&pp->pr_slock); return (error); } /* * Release all complete pages that have not been used recently. * * Returns non-zero if any pages have been reclaimed. */ int #ifdef POOL_DIAGNOSTIC _pool_reclaim(struct pool *pp, const char *file, long line) #else pool_reclaim(struct pool *pp) #endif { struct pool_item_header *ph, *phnext; struct pool_cache *pc; struct timeval curtime; struct pool_pagelist pq; struct timeval diff; int s; if (pp->pr_drain_hook != NULL) { /* * The drain hook must be called with the pool unlocked. */ (*pp->pr_drain_hook)(pp->pr_drain_hook_arg, PR_NOWAIT); } if (simple_lock_try(&pp->pr_slock) == 0) return (0); pr_enter(pp, file, line); LIST_INIT(&pq); /* * Reclaim items from the pool's caches. */ TAILQ_FOREACH(pc, &pp->pr_cachelist, pc_poollist) pool_cache_reclaim(pc); s = splclock(); curtime = mono_time; splx(s); for (ph = LIST_FIRST(&pp->pr_emptypages); ph != NULL; ph = phnext) { phnext = LIST_NEXT(ph, ph_pagelist); /* Check our minimum page claim */ if (pp->pr_npages <= pp->pr_minpages) break; KASSERT(ph->ph_nmissing == 0); timersub(&curtime, &ph->ph_time, &diff); if (diff.tv_sec < pool_inactive_time) continue; /* * If freeing this page would put us below * the low water mark, stop now. */ if ((pp->pr_nitems - pp->pr_itemsperpage) < pp->pr_minitems) break; pr_rmpage(pp, ph, &pq); } pr_leave(pp); simple_unlock(&pp->pr_slock); if (LIST_EMPTY(&pq)) return (0); while ((ph = LIST_FIRST(&pq)) != NULL) { LIST_REMOVE(ph, ph_pagelist); pool_allocator_free(pp, ph->ph_page); if (pp->pr_roflags & PR_PHINPAGE) { continue; } SPLAY_REMOVE(phtree, &pp->pr_phtree, ph); s = splhigh(); pool_put(&phpool, ph); splx(s); } return (1); } /* * Drain pools, one at a time. * * Note, we must never be called from an interrupt context. */ void pool_drain(void *arg) { struct pool *pp; int s; pp = NULL; s = splvm(); simple_lock(&pool_head_slock); if (drainpp == NULL) { drainpp = TAILQ_FIRST(&pool_head); } if (drainpp) { pp = drainpp; drainpp = TAILQ_NEXT(pp, pr_poollist); } simple_unlock(&pool_head_slock); pool_reclaim(pp); splx(s); } /* * Diagnostic helpers. */ void pool_printit(struct pool *pp, const char *modif, int (*pr)(const char *, ...)) { int s; s = splvm(); if (simple_lock_try(&pp->pr_slock) == 0) { pr("pool %s is locked; try again later\n", pp->pr_wchan); splx(s); return; } pool_print1(pp, modif, pr); simple_unlock(&pp->pr_slock); splx(s); } void pool_print_pagelist(struct pool_pagelist *pl, int (*pr)(const char *, ...)) { struct pool_item_header *ph; #ifdef DIAGNOSTIC struct pool_item *pi; #endif LIST_FOREACH(ph, pl, ph_pagelist) { (*pr)("\t\tpage %p, nmissing %d, time %lu,%lu\n", ph->ph_page, ph->ph_nmissing, (u_long)ph->ph_time.tv_sec, (u_long)ph->ph_time.tv_usec); #ifdef DIAGNOSTIC TAILQ_FOREACH(pi, &ph->ph_itemlist, pi_list) { if (pi->pi_magic != PI_MAGIC) { (*pr)("\t\t\titem %p, magic 0x%x\n", pi, pi->pi_magic); } } #endif } } void pool_print1(struct pool *pp, const char *modif, int (*pr)(const char *, ...)) { struct pool_item_header *ph; struct pool_cache *pc; struct pool_cache_group *pcg; int i, print_log = 0, print_pagelist = 0, print_cache = 0; char c; while ((c = *modif++) != '\0') { if (c == 'l') print_log = 1; if (c == 'p') print_pagelist = 1; if (c == 'c') print_cache = 1; modif++; } (*pr)("POOL %s: size %u, align %u, ioff %u, roflags 0x%08x\n", pp->pr_wchan, pp->pr_size, pp->pr_align, pp->pr_itemoffset, pp->pr_roflags); (*pr)("\talloc %p\n", pp->pr_alloc); (*pr)("\tminitems %u, minpages %u, maxpages %u, npages %u\n", pp->pr_minitems, pp->pr_minpages, pp->pr_maxpages, pp->pr_npages); (*pr)("\titemsperpage %u, nitems %u, nout %u, hardlimit %u\n", pp->pr_itemsperpage, pp->pr_nitems, pp->pr_nout, pp->pr_hardlimit); (*pr)("\n\tnget %lu, nfail %lu, nput %lu\n", pp->pr_nget, pp->pr_nfail, pp->pr_nput); (*pr)("\tnpagealloc %lu, npagefree %lu, hiwat %u, nidle %lu\n", pp->pr_npagealloc, pp->pr_npagefree, pp->pr_hiwat, pp->pr_nidle); if (print_pagelist == 0) goto skip_pagelist; if ((ph = LIST_FIRST(&pp->pr_emptypages)) != NULL) (*pr)("\n\tempty page list:\n"); pool_print_pagelist(&pp->pr_emptypages, pr); if ((ph = LIST_FIRST(&pp->pr_fullpages)) != NULL) (*pr)("\n\tfull page list:\n"); pool_print_pagelist(&pp->pr_fullpages, pr); if ((ph = LIST_FIRST(&pp->pr_partpages)) != NULL) (*pr)("\n\tpartial-page list:\n"); pool_print_pagelist(&pp->pr_partpages, pr); if (pp->pr_curpage == NULL) (*pr)("\tno current page\n"); else (*pr)("\tcurpage %p\n", pp->pr_curpage->ph_page); skip_pagelist: if (print_log == 0) goto skip_log; (*pr)("\n"); if ((pp->pr_roflags & PR_LOGGING) == 0) (*pr)("\tno log\n"); else pr_printlog(pp, NULL, pr); skip_log: if (print_cache == 0) goto skip_cache; TAILQ_FOREACH(pc, &pp->pr_cachelist, pc_poollist) { (*pr)("\tcache %p: allocfrom %p freeto %p\n", pc, pc->pc_allocfrom, pc->pc_freeto); (*pr)("\t hits %lu misses %lu ngroups %lu nitems %lu\n", pc->pc_hits, pc->pc_misses, pc->pc_ngroups, pc->pc_nitems); TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) { (*pr)("\t\tgroup %p: avail %d\n", pcg, pcg->pcg_avail); for (i = 0; i < PCG_NOBJECTS; i++) (*pr)("\t\t\t%p\n", pcg->pcg_objects[i]); } } skip_cache: pr_enter_check(pp, pr); } int pool_chk_page(struct pool *pp, const char *label, struct pool_item_header *ph) { struct pool_item *pi; caddr_t page; int n; page = (caddr_t)((u_long)ph & pp->pr_alloc->pa_pagemask); if (page != ph->ph_page && (pp->pr_roflags & PR_PHINPAGE) != 0) { if (label != NULL) printf("%s: ", label); printf("pool(%p:%s): page inconsistency: page %p;" " at page head addr %p (p %p)\n", pp, pp->pr_wchan, ph->ph_page, ph, page); return 1; } for (pi = TAILQ_FIRST(&ph->ph_itemlist), n = 0; pi != NULL; pi = TAILQ_NEXT(pi,pi_list), n++) { #ifdef DIAGNOSTIC if (pi->pi_magic != PI_MAGIC) { if (label != NULL) printf("%s: ", label); printf("pool(%s): free list modified: magic=%x;" " page %p; item ordinal %d;" " addr %p (p %p)\n", pp->pr_wchan, pi->pi_magic, ph->ph_page, n, pi, page); panic("pool"); } #endif page = (caddr_t)((u_long)pi & pp->pr_alloc->pa_pagemask); if (page == ph->ph_page) continue; if (label != NULL) printf("%s: ", label); printf("pool(%p:%s): page inconsistency: page %p;" " item ordinal %d; addr %p (p %p)\n", pp, pp->pr_wchan, ph->ph_page, n, pi, page); return 1; } return 0; } int pool_chk(struct pool *pp, const char *label) { struct pool_item_header *ph; int r = 0; simple_lock(&pp->pr_slock); LIST_FOREACH(ph, &pp->pr_emptypages, ph_pagelist) { r = pool_chk_page(pp, label, ph); if (r) { goto out; } } LIST_FOREACH(ph, &pp->pr_fullpages, ph_pagelist) { r = pool_chk_page(pp, label, ph); if (r) { goto out; } } LIST_FOREACH(ph, &pp->pr_partpages, ph_pagelist) { r = pool_chk_page(pp, label, ph); if (r) { goto out; } } out: simple_unlock(&pp->pr_slock); return (r); } /* * pool_cache_init: * * Initialize a pool cache. * * NOTE: If the pool must be protected from interrupts, we expect * to be called at the appropriate interrupt priority level. */ void pool_cache_init(struct pool_cache *pc, struct pool *pp, int (*ctor)(void *, void *, int), void (*dtor)(void *, void *), void *arg) { TAILQ_INIT(&pc->pc_grouplist); simple_lock_init(&pc->pc_slock); pc->pc_allocfrom = NULL; pc->pc_freeto = NULL; pc->pc_pool = pp; pc->pc_ctor = ctor; pc->pc_dtor = dtor; pc->pc_arg = arg; pc->pc_hits = 0; pc->pc_misses = 0; pc->pc_ngroups = 0; pc->pc_nitems = 0; simple_lock(&pp->pr_slock); TAILQ_INSERT_TAIL(&pp->pr_cachelist, pc, pc_poollist); simple_unlock(&pp->pr_slock); } /* * pool_cache_destroy: * * Destroy a pool cache. */ void pool_cache_destroy(struct pool_cache *pc) { struct pool *pp = pc->pc_pool; /* First, invalidate the entire cache. */ pool_cache_invalidate(pc); /* ...and remove it from the pool's cache list. */ simple_lock(&pp->pr_slock); TAILQ_REMOVE(&pp->pr_cachelist, pc, pc_poollist); simple_unlock(&pp->pr_slock); } static __inline void * pcg_get(struct pool_cache_group *pcg) { void *object; u_int idx; KASSERT(pcg->pcg_avail <= PCG_NOBJECTS); KASSERT(pcg->pcg_avail != 0); idx = --pcg->pcg_avail; KASSERT(pcg->pcg_objects[idx] != NULL); object = pcg->pcg_objects[idx]; pcg->pcg_objects[idx] = NULL; return (object); } static __inline void pcg_put(struct pool_cache_group *pcg, void *object) { u_int idx; KASSERT(pcg->pcg_avail < PCG_NOBJECTS); idx = pcg->pcg_avail++; KASSERT(pcg->pcg_objects[idx] == NULL); pcg->pcg_objects[idx] = object; } /* * pool_cache_get: * * Get an object from a pool cache. */ void * pool_cache_get(struct pool_cache *pc, int flags) { struct pool_cache_group *pcg; void *object; #ifdef LOCKDEBUG if (flags & PR_WAITOK) simple_lock_only_held(NULL, "pool_cache_get(PR_WAITOK)"); #endif simple_lock(&pc->pc_slock); if ((pcg = pc->pc_allocfrom) == NULL) { TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) { if (pcg->pcg_avail != 0) { pc->pc_allocfrom = pcg; goto have_group; } } /* * No groups with any available objects. Allocate * a new object, construct it, and return it to * the caller. We will allocate a group, if necessary, * when the object is freed back to the cache. */ pc->pc_misses++; simple_unlock(&pc->pc_slock); object = pool_get(pc->pc_pool, flags); if (object != NULL && pc->pc_ctor != NULL) { if ((*pc->pc_ctor)(pc->pc_arg, object, flags) != 0) { pool_put(pc->pc_pool, object); return (NULL); } } return (object); } have_group: pc->pc_hits++; pc->pc_nitems--; object = pcg_get(pcg); if (pcg->pcg_avail == 0) pc->pc_allocfrom = NULL; simple_unlock(&pc->pc_slock); return (object); } /* * pool_cache_put: * * Put an object back to the pool cache. */ void pool_cache_put(struct pool_cache *pc, void *object) { struct pool_cache_group *pcg; int s; simple_lock(&pc->pc_slock); if ((pcg = pc->pc_freeto) == NULL) { TAILQ_FOREACH(pcg, &pc->pc_grouplist, pcg_list) { if (pcg->pcg_avail != PCG_NOBJECTS) { pc->pc_freeto = pcg; goto have_group; } } /* * No empty groups to free the object to. Attempt to * allocate one. */ simple_unlock(&pc->pc_slock); s = splvm(); pcg = pool_get(&pcgpool, PR_NOWAIT); splx(s); if (pcg != NULL) { memset(pcg, 0, sizeof(*pcg)); simple_lock(&pc->pc_slock); pc->pc_ngroups++; TAILQ_INSERT_TAIL(&pc->pc_grouplist, pcg, pcg_list); if (pc->pc_freeto == NULL) pc->pc_freeto = pcg; goto have_group; } /* * Unable to allocate a cache group; destruct the object * and free it back to the pool. */ pool_cache_destruct_object(pc, object); return; } have_group: pc->pc_nitems++; pcg_put(pcg, object); if (pcg->pcg_avail == PCG_NOBJECTS) pc->pc_freeto = NULL; simple_unlock(&pc->pc_slock); } /* * pool_cache_destruct_object: * * Force destruction of an object and its release back into * the pool. */ void pool_cache_destruct_object(struct pool_cache *pc, void *object) { if (pc->pc_dtor != NULL) (*pc->pc_dtor)(pc->pc_arg, object); pool_put(pc->pc_pool, object); } /* * pool_cache_do_invalidate: * * This internal function implements pool_cache_invalidate() and * pool_cache_reclaim(). */ void pool_cache_do_invalidate(struct pool_cache *pc, int free_groups, void (*putit)(struct pool *, void *)) { struct pool_cache_group *pcg, *npcg; void *object; int s; for (pcg = TAILQ_FIRST(&pc->pc_grouplist); pcg != NULL; pcg = npcg) { npcg = TAILQ_NEXT(pcg, pcg_list); while (pcg->pcg_avail != 0) { pc->pc_nitems--; object = pcg_get(pcg); if (pcg->pcg_avail == 0 && pc->pc_allocfrom == pcg) pc->pc_allocfrom = NULL; if (pc->pc_dtor != NULL) (*pc->pc_dtor)(pc->pc_arg, object); (*putit)(pc->pc_pool, object); } if (free_groups) { pc->pc_ngroups--; TAILQ_REMOVE(&pc->pc_grouplist, pcg, pcg_list); if (pc->pc_freeto == pcg) pc->pc_freeto = NULL; s = splvm(); pool_put(&pcgpool, pcg); splx(s); } } } /* * pool_cache_invalidate: * * Invalidate a pool cache (destruct and release all of the * cached objects). */ void pool_cache_invalidate(struct pool_cache *pc) { simple_lock(&pc->pc_slock); pool_cache_do_invalidate(pc, 0, pool_put); simple_unlock(&pc->pc_slock); } /* * pool_cache_reclaim: * * Reclaim a pool cache for pool_reclaim(). */ void pool_cache_reclaim(struct pool_cache *pc) { simple_lock(&pc->pc_slock); pool_cache_do_invalidate(pc, 1, pool_do_put); simple_unlock(&pc->pc_slock); } /* * We have three different sysctls. * kern.pool.npools - the number of pools. * kern.pool.pool.<pool#> - the pool struct for the pool#. * kern.pool.name.<pool#> - the name for pool#.[6~ */ int sysctl_dopool(int *name, u_int namelen, char *where, size_t *sizep) { struct pool *pp, *foundpool = NULL; size_t buflen = where != NULL ? *sizep : 0; int npools = 0, s; unsigned int lookfor; size_t len; switch (*name) { case KERN_POOL_NPOOLS: if (namelen != 1 || buflen != sizeof(int)) return (EINVAL); lookfor = 0; break; case KERN_POOL_NAME: if (namelen != 2 || buflen < 1) return (EINVAL); lookfor = name[1]; break; case KERN_POOL_POOL: if (namelen != 2 || buflen != sizeof(struct pool)) return (EINVAL); lookfor = name[1]; break; default: return (EINVAL); } s = splvm(); simple_lock(&pool_head_slock); TAILQ_FOREACH(pp, &pool_head, pr_poollist) { npools++; if (lookfor == pp->pr_serial) { foundpool = pp; break; } } simple_unlock(&pool_head_slock); splx(s); if (lookfor != 0 && foundpool == NULL) return (ENOENT); switch (*name) { case KERN_POOL_NPOOLS: return copyout(&npools, where, buflen); case KERN_POOL_NAME: len = strlen(foundpool->pr_wchan) + 1; if (*sizep < len) return (ENOMEM); *sizep = len; return copyout(foundpool->pr_wchan, where, len); case KERN_POOL_POOL: return copyout(foundpool, where, buflen); } /* NOTREACHED */ return (0); /* XXX - Stupid gcc */ } /* * Pool backend allocators. * * Each pool has a backend allocator that handles allocation, deallocation * and any additional draining that might be needed. * * We provide two standard allocators. * pool_alloc_kmem - the default used when no allocator is specified. * pool_alloc_nointr - used for pools that will not be accessed in * interrupt context. */ void *pool_page_alloc(struct pool *, int); void pool_page_free(struct pool *, void *); void *pool_page_alloc_nointr(struct pool *, int); void pool_page_free_nointr(struct pool *, void *); struct pool_allocator pool_allocator_kmem = { pool_page_alloc, pool_page_free, 0, }; struct pool_allocator pool_allocator_nointr = { pool_page_alloc_nointr, pool_page_free_nointr, 0, }; /* * XXX - we have at least three different resources for the same allocation * and each resource can be depleted. First we have the ready elements in * the pool. Then we have the resource (typically a vm_map) for this * allocator, then we have physical memory. Waiting for any of these can * be unnecessary when any other is freed, but the kernel doesn't support * sleeping on multiple addresses, so we have to fake. The caller sleeps on * the pool (so that we can be awakened when an item is returned to the pool), * but we set PA_WANT on the allocator. When a page is returned to * the allocator and PA_WANT is set pool_allocator_free will wakeup all * sleeping pools belonging to this allocator. (XXX - thundering herd). * We also wake up the allocator in case someone without a pool (malloc) * is sleeping waiting for this allocator. */ void * pool_allocator_alloc(struct pool *org, int flags) { struct pool_allocator *pa = org->pr_alloc; int freed; void *res; int s; do { if ((res = (*pa->pa_alloc)(org, flags)) != NULL) return (res); if ((flags & PR_WAITOK) == 0) { /* * We only run the drain hook here if PR_NOWAIT. * In other cases the hook will be run in * pool_reclaim. */ if (org->pr_drain_hook != NULL) { (*org->pr_drain_hook)(org->pr_drain_hook_arg, flags); if ((res = (*pa->pa_alloc)(org, flags)) != NULL) return (res); } break; } s = splvm(); simple_lock(&pa->pa_slock); freed = pool_allocator_drain(pa, org, 1); simple_unlock(&pa->pa_slock); splx(s); } while (freed); return (NULL); } void pool_allocator_free(struct pool *pp, void *v) { struct pool_allocator *pa = pp->pr_alloc; int s; (*pa->pa_free)(pp, v); s = splvm(); simple_lock(&pa->pa_slock); if ((pa->pa_flags & PA_WANT) == 0) { simple_unlock(&pa->pa_slock); splx(s); return; } TAILQ_FOREACH(pp, &pa->pa_list, pr_alloc_list) { simple_lock(&pp->pr_slock); if ((pp->pr_flags & PR_WANTED) != 0) { pp->pr_flags &= ~PR_WANTED; wakeup(pp); } simple_unlock(&pp->pr_slock); } pa->pa_flags &= ~PA_WANT; simple_unlock(&pa->pa_slock); splx(s); } /* * Drain all pools, except 'org', that use this allocator. * * Must be called at appropriate spl level and with the allocator locked. * * We do this to reclaim va space. pa_alloc is responsible * for waiting for physical memory. * XXX - we risk looping forever if start if someone calls * pool_destroy on 'start'. But there is no other way to * have potentially sleeping pool_reclaim, non-sleeping * locks on pool_allocator and some stirring of drained * pools in the allocator. * XXX - maybe we should use pool_head_slock for locking * the allocators? */ int pool_allocator_drain(struct pool_allocator *pa, struct pool *org, int need) { struct pool *pp, *start; int freed; freed = 0; pp = start = TAILQ_FIRST(&pa->pa_list); do { TAILQ_REMOVE(&pa->pa_list, pp, pr_alloc_list); TAILQ_INSERT_TAIL(&pa->pa_list, pp, pr_alloc_list); if (pp == org) continue; simple_unlock(&pa->pa_list); freed = pool_reclaim(pp) simple_lock(&pa->pa_list); } while ((pp = TAILQ_FIRST(&pa->pa_list)) != start && (freed < need)); if (!freed) { /* * We set PA_WANT here, the caller will most likely * sleep waiting for pages (if not, this won't hurt * that much) and there is no way to set this in the * caller without violating locking order. */ pa->pa_flags |= PA_WANT; } return (freed); } void * pool_page_alloc(struct pool *pp, int flags) { boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE; return ((void *)uvm_km_alloc_poolpage1(kmem_map, uvmexp.kmem_object, waitok)); } void pool_page_free(struct pool *pp, void *v) { uvm_km_free_poolpage1(kmem_map, (vaddr_t)v); } void * pool_page_alloc_nointr(struct pool *pp, int flags) { boolean_t waitok = (flags & PR_WAITOK) ? TRUE : FALSE; splassert(IPL_NONE); return ((void *)uvm_km_alloc_poolpage1(kernel_map, uvm.kernel_object, waitok)); } void pool_page_free_nointr(struct pool *pp, void *v) { splassert(IPL_NONE); uvm_km_free_poolpage1(kernel_map, (vaddr_t)v); }
24.34832
81
0.668209
[ "object" ]
ead97bb939eabe1ac00f9678651e775bcd7898fb
2,863
h
C
ObcUITask.h
cosmosm3/openOBC
8215defb2c0c072afe4f80a350bc58be8e3103f9
[ "MIT" ]
null
null
null
ObcUITask.h
cosmosm3/openOBC
8215defb2c0c072afe4f80a350bc58be8e3103f9
[ "MIT" ]
null
null
null
ObcUITask.h
cosmosm3/openOBC
8215defb2c0c072afe4f80a350bc58be8e3103f9
[ "MIT" ]
null
null
null
/* Copyright (c) 2013 <benemorius@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef OBCUITASK_H #define OBCUITASK_H #include <stdint.h> #include <vector> #include "OpenOBC.h" #include <stdarg.h> class OpenOBC; namespace ObcUITaskFocus { enum type {active, background}; } class ObcUITask { public: ObcUITask(OpenOBC& obc); ~ObcUITask(); //required methods virtual void runTask() = 0; //mainloop code goes here virtual void buttonHandler(ObcUITaskFocus::type focus, uint32_t buttonMask) = 0; //this is called once for each button press //optional methods virtual void wake() {}; //run once on startup before entering main loop virtual void sleep() {}; //run once just before switching to sleep state char* getDisplay() {return displayBuffer;} char* getDisplayClock() {return displayClockBuffer;} float getDisplayRefreshPeriod() {return displayRefreshPeriod;} void setActive(bool isActive) {_isActive = isActive;} void runButtonEvents(); void createButtonEvent(ObcUITaskFocus::type focus, uint32_t buttonMask); void setActiveTaskTimeout(float seconds) {activeTaskTimeout = seconds;} float getActiveTaskTimeout() {return activeTaskTimeout;} protected: void registerButton(ObcUITaskFocus::type focus, uint32_t buttonMask); void unregisterButton(ObcUITaskFocus::type focus, uint32_t buttonMask); void setDisplay(char* format, ...); void setDisplayClock(char* format, ...); bool isActive() {return _isActive;} void setDisplayRefreshPeriod(float seconds) {displayRefreshPeriod = seconds;} OpenOBC& obc; private: std::vector<uint32_t> buttonEventsActive; std::vector<uint32_t> buttonEventsBackground; char displayBuffer[21]; char displayClockBuffer[5]; bool _isActive; float displayRefreshPeriod; float activeTaskTimeout; }; #endif // OBCUITASK_H
33.290698
125
0.760042
[ "vector" ]
eadd515c6956d822d9f6d3df50a799ebe97d7557
3,264
h
C
src/nbl/asset/CGraphicsPipelineLoaderMTL.h
Erfan-Ahmadi/Nabla
1ea023d3333f4fade4268b20ac878546fb4d5c82
[ "Apache-2.0" ]
2
2021-02-08T23:33:54.000Z
2021-02-09T18:21:16.000Z
src/nbl/asset/CGraphicsPipelineLoaderMTL.h
Erfan-Ahmadi/Nabla
1ea023d3333f4fade4268b20ac878546fb4d5c82
[ "Apache-2.0" ]
null
null
null
src/nbl/asset/CGraphicsPipelineLoaderMTL.h
Erfan-Ahmadi/Nabla
1ea023d3333f4fade4268b20ac878546fb4d5c82
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O. // This file is part of the "Nabla Engine". // For conditions of distribution and use, see copyright notice in nabla.h #ifndef __NBL_ASSET_C_GRAPHICS_PIPELINE_LOADER_MTL_H_INCLUDED__ #define __NBL_ASSET_C_GRAPHICS_PIPELINE_LOADER_MTL_H_INCLUDED__ #include "nbl/asset/IAssetLoader.h" #include "nbl/asset/CMTLPipelineMetadata.h" namespace nbl { namespace asset { class CGraphicsPipelineLoaderMTL final : public asset::IAssetLoader { struct SMtl { CMTLPipelineMetadata::SMTLMaterialParameters params; std::string name; //paths to image files, note that they're relative to the mtl file std::string maps[CMTLPipelineMetadata::EMP_COUNT]; //-clamp uint32_t clamp; static_assert(sizeof(clamp) * 8ull >= CMTLPipelineMetadata::EMP_COUNT, "SMtl::clamp is too small!"); }; struct SContext { SContext(const IAssetLoader::SAssetLoadContext& _innerCtx, uint32_t _topHierarchyLevel, IAssetLoader::IAssetLoaderOverride* _override) : inner(_innerCtx), topHierarchyLevel(_topHierarchyLevel), loaderOverride(_override) {} IAssetLoader::SAssetLoadContext inner; uint32_t topHierarchyLevel; IAssetLoader::IAssetLoaderOverride* loaderOverride; static inline uint32_t layoutCacheKey(uint32_t clamps, bool no_ds3) { return clamps | (static_cast<uint32_t>(no_ds3) << 31); } core::unordered_map<uint32_t, core::smart_refctd_ptr<ICPUPipelineLayout>> layoutCache; }; public: CGraphicsPipelineLoaderMTL(IAssetManager* _am); void initialize(); bool isALoadableFileFormat(io::IReadFile* _file) const override; const char** getAssociatedFileExtensions() const override { static const char* extensions[]{ "mtl", nullptr }; return extensions; } uint64_t getSupportedAssetTypesBitfield() const override { return asset::IAsset::ET_RENDERPASS_INDEPENDENT_PIPELINE; } asset::SAssetBundle loadAsset(io::IReadFile* _file, const asset::IAssetLoader::SAssetLoadParams& _params, asset::IAssetLoader::IAssetLoaderOverride* _override = nullptr, uint32_t _hierarchyLevel = 0u) override; private: core::smart_refctd_ptr<ICPUPipelineLayout> makePipelineLayoutFromMtl(SContext& ctx, const SMtl& _mtl, bool _noDS3); core::vector<SMtl> readMaterials(io::IReadFile* _file) const; const char* readTexture(const char* _bufPtr, const char* const _bufEnd, SMtl* _currMaterial, const char* _mapType) const; std::pair<core::smart_refctd_ptr<ICPUSpecializedShader>, core::smart_refctd_ptr<ICPUSpecializedShader>> getShaders(bool _hasUV); using images_set_t = std::array<core::smart_refctd_ptr<ICPUImage>, CMTLPipelineMetadata::EMP_COUNT>; using image_views_set_t = std::array<core::smart_refctd_ptr<ICPUImageView>, CMTLPipelineMetadata::EMP_REFL_POSX + 1u>; image_views_set_t loadImages(const char* _relDir, const SMtl& _mtl, SContext& _ctx); core::smart_refctd_ptr<ICPUDescriptorSet> makeDescSet(image_views_set_t&& _views, ICPUDescriptorSetLayout* _dsLayout); IAssetManager* m_assetMgr; }; } } #endif
42.947368
212
0.727022
[ "vector" ]
eadf502eb43de78cb159dd4d650f6da8b783b9a8
4,055
h
C
include/core/music_note.h
kshitijavis/synther
05f2e12b3aa41b2631d15e2565bd147106792a47
[ "MIT" ]
2
2020-12-26T06:50:38.000Z
2021-02-15T00:38:27.000Z
include/core/music_note.h
kshitijavis/synther
05f2e12b3aa41b2631d15e2565bd147106792a47
[ "MIT" ]
1
2020-12-26T06:09:22.000Z
2020-12-26T06:09:22.000Z
include/core/music_note.h
kshitijavis/synther
05f2e12b3aa41b2631d15e2565bd147106792a47
[ "MIT" ]
1
2021-05-03T20:48:56.000Z
2021-05-03T20:48:56.000Z
// // Created by Kshitij Sinha on 11/18/20. // #ifndef SYNTHER_MUSIC_NOTE_H #define SYNTHER_MUSIC_NOTE_H #include <map> namespace synther { namespace music { enum class Accidental { Sharp, Flat, Natural }; /** * Represents a musical note, defined by the main parameters: octave, letter, * and accidental. These three parameters are used to define where the note * is on the standard Western musical scale. * * Alternatively, a Note can also be defined by its semitone-index with respect * to some base note. In this implementation, the base note, C0, has the * semitone-index of 0. All other notes on the scale can be defined by their * semitone distance from C0 * * Regardless of the method of construction, a Note will keep track of its * octave, letter, accidental, and semitone-index, each of which can be * accessed but not changed */ class Note { public: /** * Constructs a note using standard musical notation: octave, letter, * accidental * @param octave and int representing the octave of the note. Indexes the * octave, given that the first octave in a keyboard is 0-indexed * @param letter a char representing the letter of the note. Options include * A, B, C, D, E, F, G * @param accidental an enum representing the note's accidental * (Sharp, Flat, Natural) */ Note(int octave, char letter, Accidental accidental); /** * Constructs a note using its semitone-index, which is the Note's semitone * distance from C0 * @param semitone_index the semitone-index of the note with respect to C0 * @param priority the Accidental that will be given priority, if the note's * semitone requires an accidental. Must be Sharp or Flat * Since any note can have multiple names, (B-flat is the same as A-sharp), * this constructor will prioritize the Accidental specified (If * Accidental::Sharp is passed, the constructor will choose A-sharp instead * of B-flat) If a note does not require an accidental, none will be * assigned. */ Note(int semitone_index, Accidental priority); /** * Checks if two notes are equal. Two notes are equal if all of their * parameters (octave, letter, accidental, semitone-index) are equal * @param rhs the note to compare to * @return true if the two notes are equal */ bool operator==(const Note& rhs) const; /** * Compares two notes, enabling Note object to be used as key in std::map * @param rhs the Note to compare to * @return true if the semitone of the current object is less than the * semitone of rhs */ bool operator<(const Note& rhs) const; /** * Compares two notes by their semitone index. The semitone index acts as a * unique ID for any note. Bear in mind that this comparison allows two * seemingly-different notes to be equal (e.g. C-sharp and D-flat) * @param rhs * @return */ bool SemitoneEquals(const Note& other) const; /** * Get the octave in which the note lies * @return the octave of the note */ int GetOctave() const; /** * Get the note's letter name (A, B, C, etc.) in upper-case * @return a char representing the note's letter name */ char GetLetter() const; /** * Get the note's accidental * @return an enum representing the note's accidental */ Accidental GetAccidental() const; /** * Get the note's semitone index, which defines the semitone ID of the note, * such that the index of C0 = 0 * @return a size_t representing the note's semitone index */ int GetSemitoneIndex() const; private: int octave_; char letter_; Accidental accidental_; // A numerical 'code' that represents note's semitone. // 0-index starts from the note C0. // Every increase in a semitone increases the note's index by 1 int semitone_index_; // Static fields static const std::map<char, int> kWholetoneIndices; static constexpr size_t kNotesPerOctave = 12; }; } // namespace music } // namespace synther #endif // SYNTHER_MUSIC_NOTE_H
31.679688
79
0.695438
[ "object" ]
eae0279fc03318898b133975a24723b47797f939
26,597
c
C
sdk/vorbis/lib/floor1.c
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
2
2020-11-11T16:19:04.000Z
2021-01-19T01:53:29.000Z
sdk/vorbis/lib/floor1.c
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2020-07-27T09:00:21.000Z
2020-07-27T10:58:10.000Z
sdk/vorbis/lib/floor1.c
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2021-04-04T01:39:55.000Z
2021-04-04T01:39:55.000Z
/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009 * * by the Xiph.Org Foundation http://www.xiph.org/ * * * ******************************************************************** function: floor backend 1 implementation last mod: $Id: floor1.c 17688 2010-11-29 23:53:30Z tterribe $ ********************************************************************/ #include <stdlib.h> #include <string.h> #include <math.h> #include <ogg/ogg.h> #include "vorbis/codec.h" #include "codec_internal.h" #include "registry.h" #include "codebook.h" #include "misc.h" #include "scales.h" #include <stdio.h> #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */ typedef struct lsfit_acc{ int x0; int x1; int xa; int ya; int x2a; int y2a; int xya; int an; int xb; int yb; int x2b; int y2b; int xyb; int bn; } lsfit_acc; /***********************************************/ static void floor1_free_info(vorbis_info_floor *i){ vorbis_info_floor1 *info=(vorbis_info_floor1 *)i; if(info){ memset(info,0,sizeof(*info)); _ogg_free(info); } } static void floor1_free_look(vorbis_look_floor *i){ vorbis_look_floor1 *look=(vorbis_look_floor1 *)i; if(look){ /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n", (float)look->phrasebits/look->frames, (float)look->postbits/look->frames, (float)(look->postbits+look->phrasebits)/look->frames);*/ memset(look,0,sizeof(*look)); _ogg_free(look); } } static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){ vorbis_info_floor1 *info=(vorbis_info_floor1 *)i; int j,k; int count=0; int rangebits; int maxposit=info->postlist[1]; int maxclass=-1; /* save out partitions */ oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */ for(j=0;j<info->partitions;j++){ oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */ if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j]; } /* save out partition classes */ for(j=0;j<maxclass+1;j++){ oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */ oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */ if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8); for(k=0;k<(1<<info->class_subs[j]);k++) oggpack_write(opb,info->class_subbook[j][k]+1,8); } /* save out the post list */ oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */ oggpack_write(opb,ilog2(maxposit),4); rangebits=ilog2(maxposit); for(j=0,k=0;j<info->partitions;j++){ count+=info->class_dim[info->partitionclass[j]]; for(;k<count;k++) oggpack_write(opb,info->postlist[k+2],rangebits); } } static int _cdecl icomp(const void *a,const void *b){ return(**(int **)a-**(int **)b); } static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){ codec_setup_info *ci=vi->codec_setup; int j,k,count=0,maxclass=-1,rangebits; vorbis_info_floor1 *info=_ogg_calloc(1,sizeof(*info)); /* read partitions */ info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */ for(j=0;j<info->partitions;j++){ info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */ if(info->partitionclass[j]<0)goto err_out; if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j]; } /* read partition classes */ for(j=0;j<maxclass+1;j++){ info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */ info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */ if(info->class_subs[j]<0) goto err_out; if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8); if(info->class_book[j]<0 || info->class_book[j]>=ci->books) goto err_out; for(k=0;k<(1<<info->class_subs[j]);k++){ info->class_subbook[j][k]=oggpack_read(opb,8)-1; if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books) goto err_out; } } /* read the post list */ info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */ rangebits=oggpack_read(opb,4); if(rangebits<0)goto err_out; for(j=0,k=0;j<info->partitions;j++){ count+=info->class_dim[info->partitionclass[j]]; for(;k<count;k++){ int t=info->postlist[k+2]=oggpack_read(opb,rangebits); if(t<0 || t>=(1<<rangebits)) goto err_out; } } info->postlist[0]=0; info->postlist[1]=1<<rangebits; /* don't allow repeated values in post list as they'd result in zero-length segments */ { int *sortpointer[VIF_POSIT+2]; for(j=0;j<count+2;j++)sortpointer[j]=info->postlist+j; qsort(sortpointer,count+2,sizeof(*sortpointer),icomp); for(j=1;j<count+2;j++) if(*sortpointer[j-1]==*sortpointer[j])goto err_out; } return(info); err_out: floor1_free_info(info); return(NULL); } static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd, vorbis_info_floor *in){ int *sortpointer[VIF_POSIT+2]; vorbis_info_floor1 *info=(vorbis_info_floor1 *)in; vorbis_look_floor1 *look=_ogg_calloc(1,sizeof(*look)); int i,j,n=0; look->vi=info; look->n=info->postlist[1]; /* we drop each position value in-between already decoded values, and use linear interpolation to predict each new value past the edges. The positions are read in the order of the position list... we precompute the bounding positions in the lookup. Of course, the neighbors can change (if a position is declined), but this is an initial mapping */ for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]]; n+=2; look->posts=n; /* also store a sorted position index */ for(i=0;i<n;i++)sortpointer[i]=info->postlist+i; qsort(sortpointer,n,sizeof(*sortpointer),icomp); /* points from sort order back to range number */ for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist; /* points from range order to sorted position */ for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i; /* we actually need the post values too */ for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]]; /* quantize values to multiplier spec */ switch(info->mult){ case 1: /* 1024 -> 256 */ look->quant_q=256; break; case 2: /* 1024 -> 128 */ look->quant_q=128; break; case 3: /* 1024 -> 86 */ look->quant_q=86; break; case 4: /* 1024 -> 64 */ look->quant_q=64; break; } /* discover our neighbors for decode where we don't use fit flags (that would push the neighbors outward) */ for(i=0;i<n-2;i++){ int lo=0; int hi=1; int lx=0; int hx=look->n; int currentx=info->postlist[i+2]; for(j=0;j<i+2;j++){ int x=info->postlist[j]; if(x>lx && x<currentx){ lo=j; lx=x; } if(x<hx && x>currentx){ hi=j; hx=x; } } look->loneighbor[i]=lo; look->hineighbor[i]=hi; } return(look); } static int render_point(int x0,int x1,int y0,int y1,int x){ y0&=0x7fff; /* mask off flag */ y1&=0x7fff; { int dy=y1-y0; int adx=x1-x0; int ady=abs(dy); int err=ady*(x-x0); int off=err/adx; if(dy<0)return(y0-off); return(y0+off); } } static int vorbis_dBquant(const float *x){ int i= *x*7.3142857f+1023.5f; if(i>1023)return(1023); if(i<0)return(0); return i; } static void render_line(int n, int x0,int x1,int y0,int y1,float *d){ int dy=y1-y0; int adx=x1-x0; int ady=abs(dy); int base=dy/adx; int sy=(dy<0?base-1:base+1); int x=x0; int y=y0; int err=0; ady-=abs(base*adx); if(n>x1)n=x1; if(x<n) d[x]*=FLOOR1_fromdB_LOOKUP[y]; while(++x<n){ err=err+ady; if(err>=adx){ err-=adx; y+=sy; }else{ y+=base; } d[x]*=FLOOR1_fromdB_LOOKUP[y]; } } static void render_line0(int n, int x0,int x1,int y0,int y1,int *d){ int dy=y1-y0; int adx=x1-x0; int ady=abs(dy); int base=dy/adx; int sy=(dy<0?base-1:base+1); int x=x0; int y=y0; int err=0; ady-=abs(base*adx); if(n>x1)n=x1; if(x<n) d[x]=y; while(++x<n){ err=err+ady; if(err>=adx){ err-=adx; y+=sy; }else{ y+=base; } d[x]=y; } } /* the floor has already been filtered to only include relevant sections */ static int accumulate_fit(const float *flr,const float *mdct, int x0, int x1,lsfit_acc *a, int n,vorbis_info_floor1 *info){ long i; int xa=0,ya=0,x2a=0,y2a=0,xya=0,na=0, xb=0,yb=0,x2b=0,y2b=0,xyb=0,nb=0; memset(a,0,sizeof(*a)); a->x0=x0; a->x1=x1; if(x1>=n)x1=n-1; for(i=x0;i<=x1;i++){ int quantized=vorbis_dBquant(flr+i); if(quantized){ if(mdct[i]+info->twofitatten>=flr[i]){ xa += i; ya += quantized; x2a += i*i; y2a += quantized*quantized; xya += i*quantized; na++; }else{ xb += i; yb += quantized; x2b += i*i; y2b += quantized*quantized; xyb += i*quantized; nb++; } } } a->xa=xa; a->ya=ya; a->x2a=x2a; a->y2a=y2a; a->xya=xya; a->an=na; a->xb=xb; a->yb=yb; a->x2b=x2b; a->y2b=y2b; a->xyb=xyb; a->bn=nb; return(na); } static int fit_line(lsfit_acc *a,int fits,int *y0,int *y1, vorbis_info_floor1 *info){ double xb=0,yb=0,x2b=0,y2b=0,xyb=0,bn=0; int i; int x0=a[0].x0; int x1=a[fits-1].x1; for(i=0;i<fits;i++){ double weight = (a[i].bn+a[i].an)*info->twofitweight/(a[i].an+1)+1.; xb+=a[i].xb + a[i].xa * weight; yb+=a[i].yb + a[i].ya * weight; x2b+=a[i].x2b + a[i].x2a * weight; y2b+=a[i].y2b + a[i].y2a * weight; xyb+=a[i].xyb + a[i].xya * weight; bn+=a[i].bn + a[i].an * weight; } if(*y0>=0){ xb+= x0; yb+= *y0; x2b+= x0 * x0; y2b+= *y0 * *y0; xyb+= *y0 * x0; bn++; } if(*y1>=0){ xb+= x1; yb+= *y1; x2b+= x1 * x1; y2b+= *y1 * *y1; xyb+= *y1 * x1; bn++; } { double denom=(bn*x2b-xb*xb); if(denom>0.){ double a=(yb*x2b-xyb*xb)/denom; double b=(bn*xyb-xb*yb)/denom; *y0=rint(a+b*x0); *y1=rint(a+b*x1); /* limit to our range! */ if(*y0>1023)*y0=1023; if(*y1>1023)*y1=1023; if(*y0<0)*y0=0; if(*y1<0)*y1=0; return 0; }else{ *y0=0; *y1=0; return 1; } } } static int inspect_error(int x0,int x1,int y0,int y1,const float *mask, const float *mdct, vorbis_info_floor1 *info){ int dy=y1-y0; int adx=x1-x0; int ady=abs(dy); int base=dy/adx; int sy=(dy<0?base-1:base+1); int x=x0; int y=y0; int err=0; int val=vorbis_dBquant(mask+x); int mse=0; int n=0; ady-=abs(base*adx); mse=(y-val); mse*=mse; n++; if(mdct[x]+info->twofitatten>=mask[x]){ if(y+info->maxover<val)return(1); if(y-info->maxunder>val)return(1); } while(++x<x1){ err=err+ady; if(err>=adx){ err-=adx; y+=sy; }else{ y+=base; } val=vorbis_dBquant(mask+x); mse+=((y-val)*(y-val)); n++; if(mdct[x]+info->twofitatten>=mask[x]){ if(val){ if(y+info->maxover<val)return(1); if(y-info->maxunder>val)return(1); } } } if(info->maxover*info->maxover/n>info->maxerr)return(0); if(info->maxunder*info->maxunder/n>info->maxerr)return(0); if(mse/n>info->maxerr)return(1); return(0); } static int post_Y(int *A,int *B,int pos){ if(A[pos]<0) return B[pos]; if(B[pos]<0) return A[pos]; return (A[pos]+B[pos])>>1; } int *floor1_fit(vorbis_block *vb,vorbis_look_floor1 *look, const float *logmdct, /* in */ const float *logmask){ long i,j; vorbis_info_floor1 *info=look->vi; long n=look->n; long posts=look->posts; long nonzero=0; lsfit_acc fits[VIF_POSIT+1]; int fit_valueA[VIF_POSIT+2]; /* index by range list position */ int fit_valueB[VIF_POSIT+2]; /* index by range list position */ int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */ int hineighbor[VIF_POSIT+2]; int *output=NULL; int memo[VIF_POSIT+2]; for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */ for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */ for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */ for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */ for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */ /* quantize the relevant floor points and collect them into line fit structures (one per minimal division) at the same time */ if(posts==0){ nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info); }else{ for(i=0;i<posts-1;i++) nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i], look->sorted_index[i+1],fits+i, n,info); } if(nonzero){ /* start by fitting the implicit base case.... */ int y0=-200; int y1=-200; fit_line(fits,posts-1,&y0,&y1,info); fit_valueA[0]=y0; fit_valueB[0]=y0; fit_valueB[1]=y1; fit_valueA[1]=y1; /* Non degenerate case */ /* start progressive splitting. This is a greedy, non-optimal algorithm, but simple and close enough to the best answer. */ for(i=2;i<posts;i++){ int sortpos=look->reverse_index[i]; int ln=loneighbor[sortpos]; int hn=hineighbor[sortpos]; /* eliminate repeat searches of a particular range with a memo */ if(memo[ln]!=hn){ /* haven't performed this error search yet */ int lsortpos=look->reverse_index[ln]; int hsortpos=look->reverse_index[hn]; memo[ln]=hn; { /* A note: we want to bound/minimize *local*, not global, error */ int lx=info->postlist[ln]; int hx=info->postlist[hn]; int ly=post_Y(fit_valueA,fit_valueB,ln); int hy=post_Y(fit_valueA,fit_valueB,hn); if(ly==-1 || hy==-1){ exit(1); } if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){ /* outside error bounds/begin search area. Split it. */ int ly0=-200; int ly1=-200; int hy0=-200; int hy1=-200; int ret0=fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1,info); int ret1=fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1,info); if(ret0){ ly0=ly; ly1=hy0; } if(ret1){ hy0=ly1; hy1=hy; } if(ret0 && ret1){ fit_valueA[i]=-200; fit_valueB[i]=-200; }else{ /* store new edge values */ fit_valueB[ln]=ly0; if(ln==0)fit_valueA[ln]=ly0; fit_valueA[i]=ly1; fit_valueB[i]=hy0; fit_valueA[hn]=hy1; if(hn==1)fit_valueB[hn]=hy1; if(ly1>=0 || hy0>=0){ /* store new neighbor values */ for(j=sortpos-1;j>=0;j--) if(hineighbor[j]==hn) hineighbor[j]=i; else break; for(j=sortpos+1;j<posts;j++) if(loneighbor[j]==ln) loneighbor[j]=i; else break; } } }else{ fit_valueA[i]=-200; fit_valueB[i]=-200; } } } } output=_vorbis_block_alloc(vb,sizeof(*output)*posts); output[0]=post_Y(fit_valueA,fit_valueB,0); output[1]=post_Y(fit_valueA,fit_valueB,1); /* fill in posts marked as not using a fit; we will zero back out to 'unused' when encoding them so long as curve interpolation doesn't force them into use */ for(i=2;i<posts;i++){ int ln=look->loneighbor[i-2]; int hn=look->hineighbor[i-2]; int x0=info->postlist[ln]; int x1=info->postlist[hn]; int y0=output[ln]; int y1=output[hn]; int predicted=render_point(x0,x1,y0,y1,info->postlist[i]); int vx=post_Y(fit_valueA,fit_valueB,i); if(vx>=0 && predicted!=vx){ output[i]=vx; }else{ output[i]= predicted|0x8000; } } } return(output); } int *floor1_interpolate_fit(vorbis_block *vb,vorbis_look_floor1 *look, int *A,int *B, int del){ long i; long posts=look->posts; int *output=NULL; if(A && B){ output=_vorbis_block_alloc(vb,sizeof(*output)*posts); /* overly simpleminded--- look again post 1.2 */ for(i=0;i<posts;i++){ output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16; if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000; } } return(output); } int floor1_encode(oggpack_buffer *opb,vorbis_block *vb, vorbis_look_floor1 *look, int *post,int *ilogmask){ long i,j; vorbis_info_floor1 *info=look->vi; long posts=look->posts; codec_setup_info *ci=vb->vd->vi->codec_setup; int out[VIF_POSIT+2]; static_codebook **sbooks=ci->book_param; codebook *books=ci->fullbooks; /* quantize values to multiplier spec */ if(post){ for(i=0;i<posts;i++){ int val=post[i]&0x7fff; switch(info->mult){ case 1: /* 1024 -> 256 */ val>>=2; break; case 2: /* 1024 -> 128 */ val>>=3; break; case 3: /* 1024 -> 86 */ val/=12; break; case 4: /* 1024 -> 64 */ val>>=4; break; } post[i]=val | (post[i]&0x8000); } out[0]=post[0]; out[1]=post[1]; /* find prediction values for each post and subtract them */ for(i=2;i<posts;i++){ int ln=look->loneighbor[i-2]; int hn=look->hineighbor[i-2]; int x0=info->postlist[ln]; int x1=info->postlist[hn]; int y0=post[ln]; int y1=post[hn]; int predicted=render_point(x0,x1,y0,y1,info->postlist[i]); if((post[i]&0x8000) || (predicted==post[i])){ post[i]=predicted|0x8000; /* in case there was roundoff jitter in interpolation */ out[i]=0; }else{ int headroom=(look->quant_q-predicted<predicted? look->quant_q-predicted:predicted); int val=post[i]-predicted; /* at this point the 'deviation' value is in the range +/- max range, but the real, unique range can always be mapped to only [0-maxrange). So we want to wrap the deviation into this limited range, but do it in the way that least screws an essentially gaussian probability distribution. */ if(val<0) if(val<-headroom) val=headroom-val-1; else val=-1-(val<<1); else if(val>=headroom) val= val+headroom; else val<<=1; out[i]=val; post[ln]&=0x7fff; post[hn]&=0x7fff; } } /* we have everything we need. pack it out */ /* mark nontrivial floor */ oggpack_write(opb,1,1); /* beginning/end post */ look->frames++; look->postbits+=ilog(look->quant_q-1)*2; oggpack_write(opb,out[0],ilog(look->quant_q-1)); oggpack_write(opb,out[1],ilog(look->quant_q-1)); /* partition by partition */ for(i=0,j=2;i<info->partitions;i++){ int class=info->partitionclass[i]; int cdim=info->class_dim[class]; int csubbits=info->class_subs[class]; int csub=1<<csubbits; int bookas[8]={0,0,0,0,0,0,0,0}; int cval=0; int cshift=0; int k,l; /* generate the partition's first stage cascade value */ if(csubbits){ int maxval[8]; for(k=0;k<csub;k++){ int booknum=info->class_subbook[class][k]; if(booknum<0){ maxval[k]=1; }else{ maxval[k]=sbooks[info->class_subbook[class][k]]->entries; } } for(k=0;k<cdim;k++){ for(l=0;l<csub;l++){ int val=out[j+k]; if(val<maxval[l]){ bookas[k]=l; break; } } cval|= bookas[k]<<cshift; cshift+=csubbits; } /* write it */ look->phrasebits+= vorbis_book_encode(books+info->class_book[class],cval,opb); #ifdef TRAIN_FLOOR1 { FILE *of; char buffer[80]; sprintf(buffer,"line_%dx%ld_class%d.vqd", vb->pcmend/2,posts-2,class); of=fopen(buffer,"a"); fprintf(of,"%d\n",cval); fclose(of); } #endif } /* write post values */ for(k=0;k<cdim;k++){ int book=info->class_subbook[class][bookas[k]]; if(book>=0){ /* hack to allow training with 'bad' books */ if(out[j+k]<(books+book)->entries) look->postbits+=vorbis_book_encode(books+book, out[j+k],opb); /*else fprintf(stderr,"+!");*/ #ifdef TRAIN_FLOOR1 { FILE *of; char buffer[80]; sprintf(buffer,"line_%dx%ld_%dsub%d.vqd", vb->pcmend/2,posts-2,class,bookas[k]); of=fopen(buffer,"a"); fprintf(of,"%d\n",out[j+k]); fclose(of); } #endif } } j+=cdim; } { /* generate quantized floor equivalent to what we'd unpack in decode */ /* render the lines */ int hx=0; int lx=0; int ly=post[0]*info->mult; int n=ci->blocksizes[vb->W]/2; for(j=1;j<look->posts;j++){ int current=look->forward_index[j]; int hy=post[current]&0x7fff; if(hy==post[current]){ hy*=info->mult; hx=info->postlist[current]; render_line0(n,lx,hx,ly,hy,ilogmask); lx=hx; ly=hy; } } for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */ return(1); } }else{ oggpack_write(opb,0,1); memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask)); return(0); } } static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){ vorbis_look_floor1 *look=(vorbis_look_floor1 *)in; vorbis_info_floor1 *info=look->vi; codec_setup_info *ci=vb->vd->vi->codec_setup; int i,j,k; codebook *books=ci->fullbooks; /* unpack wrapped/predicted values from stream */ if(oggpack_read(&vb->opb,1)==1){ int *fit_value=_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value)); fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); /* partition by partition */ for(i=0,j=2;i<info->partitions;i++){ int class=info->partitionclass[i]; int cdim=info->class_dim[class]; int csubbits=info->class_subs[class]; int csub=1<<csubbits; int cval=0; /* decode the partition's first stage cascade value */ if(csubbits){ cval=vorbis_book_decode(books+info->class_book[class],&vb->opb); if(cval==-1)goto eop; } for(k=0;k<cdim;k++){ int book=info->class_subbook[class][cval&(csub-1)]; cval>>=csubbits; if(book>=0){ if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1) goto eop; }else{ fit_value[j+k]=0; } } j+=cdim; } /* unwrap positive values and reconsitute via linear interpolation */ for(i=2;i<look->posts;i++){ int predicted=render_point(info->postlist[look->loneighbor[i-2]], info->postlist[look->hineighbor[i-2]], fit_value[look->loneighbor[i-2]], fit_value[look->hineighbor[i-2]], info->postlist[i]); int hiroom=look->quant_q-predicted; int loroom=predicted; int room=(hiroom<loroom?hiroom:loroom)<<1; int val=fit_value[i]; if(val){ if(val>=room){ if(hiroom>loroom){ val = val-loroom; }else{ val = -1-(val-hiroom); } }else{ if(val&1){ val= -((val+1)>>1); }else{ val>>=1; } } fit_value[i]=(val+predicted)&0x7fff; fit_value[look->loneighbor[i-2]]&=0x7fff; fit_value[look->hineighbor[i-2]]&=0x7fff; }else{ fit_value[i]=predicted|0x8000; } } return(fit_value); } eop: return(NULL); } static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo, float *out){ vorbis_look_floor1 *look=(vorbis_look_floor1 *)in; vorbis_info_floor1 *info=look->vi; codec_setup_info *ci=vb->vd->vi->codec_setup; int n=ci->blocksizes[vb->W]/2; int j; if(memo){ /* render the lines */ int *fit_value=(int *)memo; int hx=0; int lx=0; int ly=fit_value[0]*info->mult; /* guard lookup against out-of-range values */ ly=(ly<0?0:ly>255?255:ly); for(j=1;j<look->posts;j++){ int current=look->forward_index[j]; int hy=fit_value[current]&0x7fff; if(hy==fit_value[current]){ hx=info->postlist[current]; hy*=info->mult; /* guard lookup against out-of-range values */ hy=(hy<0?0:hy>255?255:hy); render_line(n,lx,hx,ly,hy,out); lx=hx; ly=hy; } } for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */ return(1); } memset(out,0,sizeof(*out)*n); return(0); } /* export hooks */ const vorbis_func_floor floor1_exportbundle={ &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info, &floor1_free_look,&floor1_inverse1,&floor1_inverse2 };
26.229783
79
0.548069
[ "render" ]
d805e07b6ea6cc8686d472a397e4edbf922a7f40
8,818
c
C
vm_state.c
meghanto/tiny_vm
da19e9f4bff3b48349bf13f8dc725d387d01e1f5
[ "CC-BY-3.0" ]
2
2022-01-12T03:16:07.000Z
2022-01-15T07:52:48.000Z
vm_state.c
meghanto/tiny_vm
da19e9f4bff3b48349bf13f8dc725d387d01e1f5
[ "CC-BY-3.0" ]
2
2022-01-25T20:52:54.000Z
2022-01-31T02:46:45.000Z
vm_state.c
meghanto/tiny_vm
da19e9f4bff3b48349bf13f8dc725d387d01e1f5
[ "CC-BY-3.0" ]
10
2022-01-04T04:36:07.000Z
2022-01-15T00:55:27.000Z
/* The core state of the virtual machine * including the code page and the stack * (but not the heap, for now). */ #include "vm_state.h" #include "vm_code_table.h" #include "logger.h" #include "builtins.h" // For debugging only #include <assert.h> #include <stdio.h> #include <string.h> /* The concrete data structures live here */ vm_Word vm_code_block[CODE_CAPACITY]; vm_addr vm_pc = &vm_code_block[0]; int vm_run_state = VM_RUNNING; enum LOG_LEVEL vm_logging = INFO; char *guess_description(vm_Word w); /* --------- Program code -------------- */ /* Fetch next word from code block, * advancing the program counter. */ vm_Word vm_fetch_next(void) { vm_Word cur = (*vm_pc); if (vm_pc >= vm_code_block && vm_pc < vm_code_block + CODE_CAPACITY) { // Looks like we are executing an instruction in the main // code memory int word_number = vm_pc - vm_code_block; log_debug("Fetched [%d] (%p : %s)", word_number, cur.native, guess_description(cur)); } else { log_debug("Fetched %p (%s)", cur.native, guess_description(cur)); } vm_pc ++; return cur; } /* A jump is an adjustment (+/- n instruction words) * to program counter. A jump of 0 would continue * to next instruction. A jump of -2 would repeat * the jump instruction. */ extern void vm_relative_jump(int n) { log_debug("vm_state, Jumping (adjusted) %d from %p", n, vm_pc); vm_pc += n; log_debug("New program counter is %p", vm_pc); } /* ----------Activation records (frames) ----------- * * Upward growing stack (real stacks grow downward). */ vm_Word vm_frame_stack[FRAME_CAPACITY]; vm_Word *vm_fp = vm_frame_stack; // Frame pointer, points to "this" object vm_Word *vm_sp = vm_frame_stack; // Stack pointer, points to top item /* Evaluation stack is at end of activation record. */ /* Push a single word on the frame stack */ void vm_frame_push_word(vm_Word val) { ++ vm_sp; *vm_sp = val; } /* Pop a single word from the frame stack */ vm_Word vm_frame_pop_word() { vm_Word value = *vm_sp; -- vm_sp; return value; } /* Get top word without removing it */ vm_Word vm_frame_top_word() { vm_Word value = *vm_sp; return value; } /* While many higher level VMs (e.g., the Java virtual machine) keep * a separate stack for expression evaluation, we will integrate the * evaluation stack with the procedure call stack. This is closer to * how a stack would be used in native code, although native code would * typically be register-oriented and make less use of an evaluation stack. */ void vm_eval_push(obj_ref v) { assert(v->header.tag == GOOD_OBJ_TAG); vm_frame_push_word((vm_Word) {.obj = v}); } obj_ref vm_eval_pop() { vm_Word w = vm_frame_pop_word(); assert(w.obj->header.tag == GOOD_OBJ_TAG); return w.obj; } /* Roll the stack: * roll 2: [ob x y] -> [x y ob] * roll 1: [ob x] -> [x ob] * (used to put the receiver object at the * stack pointer in preparation for method call) */ void vm_roll(int n) { vm_Word ob = *(vm_sp - n); for (int i=n; i > 0; --i) { *(vm_sp - i) = *(vm_sp + 1 - i); } *(vm_sp) = ob; } /* --------------------- Constant pool --------------- */ struct constant_pool_entry { char* name; obj_ref const_object; }; /* There is a GLOBAL constant pool in the VM, shared by * all loaded modules. Each module has its own LOCAL * constants, because it doesn't know about the others. * Local constants are consolidated into the global pool * when a module is loaded into the VM, and constant * indexes are remapped while the module is loaded. */ /* The global pool */ static struct constant_pool_entry vm_constant_pool[CONST_POOL_CAPACITY]; static int vm_next_const = 1; // Skip index 0 so that it can be failure signal /* lookup_const_index("literal string") returns index * OR zero to indicate not present */ extern int lookup_const_index(char *literal) { // We start with index 1, not 0, so that we can use 0 as failure for (int i=1; i < vm_next_const; ++i) { if (strcmp(literal, vm_constant_pool[i].name) == 0) { return i; } } // Not present in constant table return 0; } /* create_const_value returns a positive index of the * entry the new constant object will have in the constant pool. */ extern int create_const_value(char *literal, obj_ref value) { int const_index = vm_next_const; vm_next_const += 1; vm_constant_pool[const_index].name = strdup(literal); vm_constant_pool[const_index].const_object = value; return const_index; } /* get_const_value returns an object reference corresponding * to the provided index. */ extern obj_ref get_const_value(int index) { assert(index > 0 && index < vm_next_const); return vm_constant_pool[index].const_object; } /* Debugging support */ extern void dump_constants(void) { for (int i=1; i < vm_next_const; ++i) { obj_ref thing = vm_constant_pool[i].const_object; class_ref clazz = thing->header.clazz; log_debug("Constant %d: %s", i, clazz->header.class_name); if (clazz == the_class_String) { struct obj_String_struct *s = (struct obj_String_struct *) thing; log_debug("Value: |%s|", s->text); } else if (clazz == the_class_Int) { struct obj_Int_struct *v = (struct obj_Int_struct *) thing; log_debug("Value: %d", v->value); } else if (thing == lit_true) { log_debug("the literal true"); } else if (thing == lit_false) { log_debug("the literal false"); } else if (thing == nothing) { log_debug("the value nothing"); } else { log_debug("Maybe a user-defined value"); } } } /* Does execution belong here? * Maybe for now. */ /* Debugging/tracing support */ char *op_name(vm_Instr op) { static char buff[100]; /* Is it an instruction? */ for (int i=0; vm_op_bytecodes[i].name; ++i) { if (vm_op_bytecodes[i].instr == op) { char *name = vm_op_bytecodes[i].name; return name; } } // Not an instruction ... what else could it be? sprintf(buff, "%p", op); return buff; } char *guess_description(vm_Word w) { static char buff[500]; /* Is it an instruction? */ for (int i=0; vm_op_bytecodes[i].name; ++i) { if (vm_op_bytecodes[i].instr == w.instr) { char *name = vm_op_bytecodes[i].name; return name; } } /* A small integer constant? */ if (w.intval >= -1000 && w.intval <= 1000) { sprintf(buff, "(int) %d", w.intval); return buff; } /* The remaining checks all assume it is * a valid (readable) memory address. * I really need exception handling for the * cases when it is not. */ /* An object? */ if (w.obj->header.tag == GOOD_OBJ_TAG) { sprintf(buff, "(%s object) %p", w.obj->header.clazz->header.class_name, w.obj); return buff; } /* An address on the stack? */ long stack_base = (long) &vm_frame_stack[0]; long stack_limit = (long) &vm_frame_stack[FRAME_CAPACITY]; long as_frame = (long) w.frame_addr; if (stack_base <= as_frame && as_frame < stack_limit) { int frame_num = w.frame_addr - vm_frame_stack; sprintf(buff, "(stack ptr) %d", frame_num); return buff; } /* We can't currently distinguish class objects * from other things. */ sprintf(buff, "Unknown thing: %p", w.instr); return buff; } void stack_dump(int n_words) { const char* fp_ind = "-fp->"; const char* not_fp = " "; log_debug("==="); vm_addr top = vm_sp; int depth = top - vm_frame_stack; /* Start up to n_words below the top */ vm_addr cur_cell; if (depth > n_words) { cur_cell = top - n_words; } else { cur_cell = vm_frame_stack; } while (cur_cell <= top) { const char *indic; if (vm_fp == cur_cell) { indic = fp_ind; } else { indic = not_fp; } int frame_num = cur_cell - vm_frame_stack; log_debug("%s %d : %s", indic, frame_num, guess_description(*cur_cell)); cur_cell += 1; } log_debug("==="); } /* One execution step, at current PC */ void vm_step() { vm_Instr instr = vm_fetch_next().instr; char *name = guess_description((vm_Word) instr); log_debug("Step: %s",name ); (*instr)(); health_check_builtins(); stack_dump(8); } void vm_run() { vm_run_state = VM_RUNNING; // push_log_level(DEBUG); while (vm_run_state == VM_RUNNING) { vm_step(); } // pop_log_level(); }
29.198675
78
0.617714
[ "object" ]
d809b588c0e54d538136aca02f0c3eb82d8ddf43
2,164
h
C
ni/src/lib/hlu/CnTriMeshRendererP.h
tenomoto/ncl
a87114a689a1566e9aa03d85bcf6dc7325b47633
[ "Apache-2.0" ]
210
2016-11-24T09:05:08.000Z
2022-03-24T19:15:32.000Z
ni/src/lib/hlu/CnTriMeshRendererP.h
tenomoto/ncl
a87114a689a1566e9aa03d85bcf6dc7325b47633
[ "Apache-2.0" ]
156
2017-09-22T09:56:48.000Z
2022-03-30T07:02:21.000Z
ni/src/lib/hlu/CnTriMeshRendererP.h
tenomoto/ncl
a87114a689a1566e9aa03d85bcf6dc7325b47633
[ "Apache-2.0" ]
58
2016-12-14T00:15:22.000Z
2022-03-15T09:13:00.000Z
/* * $Id: CnTriMeshRendererP.h,v 1.4 2010-03-27 18:58:25 dbrown Exp $ */ /************************************************************************ * * * Copyright (C) 1992 * * University Corporation for Atmospheric Research * * All Rights Reserved * * * ************************************************************************/ /* * File: CnTriMeshRendererP.h * * Author: David Brown * National Center for Atmospheric Research * PO 3000, Boulder, Colorado * * Date: Fri Oct 2 15:01:59 MDT 1992 * * Description: CnTriMeshRenderer plot object private header file */ #ifndef _NCNTRIMESHRENDERERERP_h #define _NCNTRIMESHRENDERERERP_h #include <ncarg/hlu/CnTriMeshRenderer.h> #include <ncarg/hlu/CnRendererP.h> #define Nhlcn1DMESHMAPVAL 98 #define NhlcnTRIMESHMAPVAL 90 extern void _NhlSetCnl( #if NhlNeedProto NhlContourPlotLayer cnl #endif ); typedef struct _triblock { float *rpnt; int *iedg; int *itri; int npnt; int nedg; int ntri; float xs,xe,ys,ye; /* these values overlap */ float xsr,ysr,xer,yer; /* these represent the actual boundaries */ double *points; float *dat; int ixmn,ixmx,iymn,iymx; int npnt_alloc; } TriBlock; typedef struct _NhlCnTriMeshRendererLayerPart { TriBlock *tri_block; int nblocks; int nblocks_alloced; NhlBoolean ezmap; int update_mode; int trans_change_count; } NhlCnTriMeshRendererLayerPart; typedef struct _NhlCnTriMeshRendererLayerRec { NhlObjLayerPart base; NhlCnRendererLayerPart cnrenderer; NhlCnTriMeshRendererLayerPart cntrimeshrenderer; } NhlCnTriMeshRendererLayerRec; typedef struct NhlCnTriMeshRendererClassPart{ int foo; } NhlCnTriMeshRendererClassPart; typedef struct _NhlCnTriMeshRendererClassRec{ NhlObjClassPart base_class; NhlCnRendererClassPart cnrenderer_class; NhlCnTriMeshRendererClassPart cntrimeshrenderer_class; } NhlCnTriMeshRendererClassRec; typedef struct _NhlCnTriMeshRendererClassRec *NhlCnTriMeshRendererClass; typedef struct _NhlCnTriMeshRendererLayerRec *NhlCnTriMeshRendererLayer; extern NhlCnTriMeshRendererClassRec NhlcnTriMeshRendererClassRec; #endif /* _NCNTRIMESHRENDERERP_h */
24.590909
73
0.718115
[ "object" ]
2377ac523985707f12570349d650f3c539a7e8bd
5,641
h
C
aws-cpp-sdk-devicefarm/include/aws/devicefarm/model/CreateRemoteAccessSessionConfiguration.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-10-10T20:58:44.000Z
2019-10-10T20:58:44.000Z
aws-cpp-sdk-devicefarm/include/aws/devicefarm/model/CreateRemoteAccessSessionConfiguration.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-devicefarm/include/aws/devicefarm/model/CreateRemoteAccessSessionConfiguration.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/devicefarm/DeviceFarm_EXPORTS.h> #include <aws/devicefarm/model/BillingMethod.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace DeviceFarm { namespace Model { /** * <p>Configuration settings for a remote access session, including billing * method.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/CreateRemoteAccessSessionConfiguration">AWS * API Reference</a></p> */ class AWS_DEVICEFARM_API CreateRemoteAccessSessionConfiguration { public: CreateRemoteAccessSessionConfiguration(); CreateRemoteAccessSessionConfiguration(Aws::Utils::Json::JsonView jsonValue); CreateRemoteAccessSessionConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The billing method for the remote access session.</p> */ inline const BillingMethod& GetBillingMethod() const{ return m_billingMethod; } /** * <p>The billing method for the remote access session.</p> */ inline bool BillingMethodHasBeenSet() const { return m_billingMethodHasBeenSet; } /** * <p>The billing method for the remote access session.</p> */ inline void SetBillingMethod(const BillingMethod& value) { m_billingMethodHasBeenSet = true; m_billingMethod = value; } /** * <p>The billing method for the remote access session.</p> */ inline void SetBillingMethod(BillingMethod&& value) { m_billingMethodHasBeenSet = true; m_billingMethod = std::move(value); } /** * <p>The billing method for the remote access session.</p> */ inline CreateRemoteAccessSessionConfiguration& WithBillingMethod(const BillingMethod& value) { SetBillingMethod(value); return *this;} /** * <p>The billing method for the remote access session.</p> */ inline CreateRemoteAccessSessionConfiguration& WithBillingMethod(BillingMethod&& value) { SetBillingMethod(std::move(value)); return *this;} /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline const Aws::Vector<Aws::String>& GetVpceConfigurationArns() const{ return m_vpceConfigurationArns; } /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline bool VpceConfigurationArnsHasBeenSet() const { return m_vpceConfigurationArnsHasBeenSet; } /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline void SetVpceConfigurationArns(const Aws::Vector<Aws::String>& value) { m_vpceConfigurationArnsHasBeenSet = true; m_vpceConfigurationArns = value; } /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline void SetVpceConfigurationArns(Aws::Vector<Aws::String>&& value) { m_vpceConfigurationArnsHasBeenSet = true; m_vpceConfigurationArns = std::move(value); } /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline CreateRemoteAccessSessionConfiguration& WithVpceConfigurationArns(const Aws::Vector<Aws::String>& value) { SetVpceConfigurationArns(value); return *this;} /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline CreateRemoteAccessSessionConfiguration& WithVpceConfigurationArns(Aws::Vector<Aws::String>&& value) { SetVpceConfigurationArns(std::move(value)); return *this;} /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline CreateRemoteAccessSessionConfiguration& AddVpceConfigurationArns(const Aws::String& value) { m_vpceConfigurationArnsHasBeenSet = true; m_vpceConfigurationArns.push_back(value); return *this; } /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline CreateRemoteAccessSessionConfiguration& AddVpceConfigurationArns(Aws::String&& value) { m_vpceConfigurationArnsHasBeenSet = true; m_vpceConfigurationArns.push_back(std::move(value)); return *this; } /** * <p>An array of Amazon Resource Names (ARNs) included in the VPC endpoint * configuration.</p> */ inline CreateRemoteAccessSessionConfiguration& AddVpceConfigurationArns(const char* value) { m_vpceConfigurationArnsHasBeenSet = true; m_vpceConfigurationArns.push_back(value); return *this; } private: BillingMethod m_billingMethod; bool m_billingMethodHasBeenSet; Aws::Vector<Aws::String> m_vpceConfigurationArns; bool m_vpceConfigurationArnsHasBeenSet; }; } // namespace Model } // namespace DeviceFarm } // namespace Aws
37.606667
209
0.720085
[ "vector", "model" ]
2377df52fecb9ab5a4e7c5dcd8c94ae5326dd795
15,473
h
C
src/libtsduck/dtv/dvbsimulcrypt/tstlvMessageFactory.h
cedinu/tsduck
dc693912b1fda85bcac3fcb830d7753bd8112552
[ "BSD-2-Clause" ]
542
2017-06-21T07:40:10.000Z
2022-03-29T13:44:39.000Z
src/libtsduck/dtv/dvbsimulcrypt/tstlvMessageFactory.h
cedinu/tsduck
dc693912b1fda85bcac3fcb830d7753bd8112552
[ "BSD-2-Clause" ]
939
2017-09-01T21:00:42.000Z
2022-03-31T14:39:27.000Z
src/libtsduck/dtv/dvbsimulcrypt/tstlvMessageFactory.h
cedinu/tsduck
dc693912b1fda85bcac3fcb830d7753bd8112552
[ "BSD-2-Clause" ]
167
2017-10-30T12:07:29.000Z
2022-03-23T11:36:10.000Z
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2021, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- //! //! @file //! Factory class for TLV messages //! //---------------------------------------------------------------------------- #pragma once #include "tstlvProtocol.h" namespace ts { namespace tlv { class MessageFactory; //! //! Safe pointer for MessageFactory (not thread-safe). //! typedef SafePtr <MessageFactory, NullMutex> MessageFactoryPtr; //! //! Factory class for TLV messages //! @ingroup tlv //! //! The following methods should be used by the application //! to deserialize messages: //! - Constructors //! - errorStatus() //! - errorInformation() //! - commandTag() //! - protocolVersion() //! - factory() //! - buildErrorResponse() //! //! The following types and methods should be used by the //! constructors of the ts::tlv::Message subclasses. //! - Parameter //! - count() //! - get() //! - getCompound() //! //! The get() and getCompound() methods retrieve the value of parameters. //! For each parameter type, two versions are available. //! - The first version returns the first occurence of a //! parameter and is typically used when the cardinality //! of a parameter is 1 or 0 to 1. In the later case, //! the message deserialization routine should first check //! the availability of the parameter using count(). //! - The second version returns all occurences of the //! parameter in a vector. //! //! An exception is thrown when the parameter is not present //! (first version) or when the actual size of the parameter //! does not match the expected size of the type. In both //! cases, this should not happen in properly written message //! classes since the validity of the parameters were checked //! by the constructor of the MessageFactory. //! class TSDUCKDLL MessageFactory { TS_NOBUILD_NOCOPY(MessageFactory); public: //! //! Constructor: Analyze a TLV message in memory. //! @param [in] addr Address of a binary TLV message. //! @param [in] size Size in bytes of the message. //! @param [in] protocol The message is validated according to this protocol. //! MessageFactory(const void* addr, size_t size, const Protocol* protocol); //! //! Constructor: Analyze a TLV message in memory. //! @param [in] bb Binary TLV message. //! @param [in] protocol The message is validated according to this protocol. //! MessageFactory(const ByteBlock &bb, const Protocol* protocol); //! //! Get the "error status" resulting from the analysis of the message. //! @return The error status. If not OK, there is no valid message. //! tlv::Error errorStatus() const { return _error_status; } //! //! Get the "error information" resulting from the analysis of the message. //! @return The error information. //! uint16_t errorInformation() const { return _error_info; } //! //! Get the message tag. //! @return The message tag. //! TAG commandTag() const {return _command_tag;} //! //! Get the protocol version number. //! @return The protocol version number. //! VERSION protocolVersion() const { return _protocol_version; } //! //! Return the fully rebuilt message. //! Valid only when errorStatus() == OK. //! @param [out] msg Safe pointer to the rebuilt message. //! Set a null pointer on error. //! void factory(MessagePtr& msg) const; //! //! Return the fully rebuilt message. //! Valid only when errorStatus() == OK. //! @return Safe pointer to the rebuilt message or null pointer on error. //! MessagePtr factory() const; //! //! Return the error response for the peer. //! Valid only when errorStatus() != OK. //! @param [out] msg Safe pointer to the error response message. //! Set a null pointer without error. //! void buildErrorResponse(MessagePtr& msg) const; //! //! Return the error response for the peer. //! Valid only when errorStatus() != OK. //! @return Safe pointer to the error response message or null pointer without error. //! MessagePtr errorResponse() const; //! //! Location of one parameter value inside the message block. //! Address and size point into the original message buffer, use with care! //! struct Parameter { // Public fields: const void* tlv_addr; //!< Address of parameter TLV structure. size_t tlv_size; //!< Size of parameter TLV structure. const void* addr; //!< Address of parameter value. LENGTH length; //!< Length of parameter value. //! //! Constructor. //! @param [in] tlv_addr_ Address of parameter TLV structure. //! @param [in] tlv_size_ Size of parameter TLV structure. //! @param [in] addr_ Address of parameter value. //! @param [in] length_ Length of parameter value. //! Parameter(const void* tlv_addr_ = nullptr, size_t tlv_size_ = 0, const void* addr_ = nullptr, LENGTH length_ = 0) : tlv_addr(tlv_addr_), tlv_size(tlv_size_), addr(addr_), length(length_) { } }; //! //! Get actual number of occurences of a parameter. //! @param [in] tag Parameter tag to search. //! @return The actual number of occurences of a parameter. //! size_t count(TAG tag) const { return _params.count(tag); } //! //! Get the location of a parameter. //! Address and size point into the original message buffer, use with care! //! @param [in] tag Parameter tag to search. //! @param [out] param Description of the parameter value. //! void get(TAG tag, Parameter& param) const; //! //! Get the location of all occurences of a parameter. //! Address and size point into the original message buffer, use with care! //! @param [in] tag Parameter tag to search. //! @param [out] param Vector of descriptions of the parameter values. //! void get(TAG tag, std::vector<Parameter>& param) const; //! //! Get an integer parameter. //! @tparam INT Integer type for the value. //! The size of INT must match the parameter size. //! @param [in] tag Parameter tag to search. //! @return The parameter value. //! template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type* = nullptr> INT get(TAG tag) const; //! //! Get an integer parameter. //! @tparam INT Integer type for the value. //! The size of INT must match the parameter size. //! @param [in] tag Parameter tag to search. //! @param [out] param All parameter values. //! template <typename INT, typename std::enable_if<std::is_integral<INT>::value>::type* = nullptr> void get(TAG tag, std::vector<INT>& param) const; //! //! Get a boolean parameter. //! This method returns a vector of booleans. //! For one single boolean value, use the template version. //! @param [in] tag Parameter tag to search. //! @param [out] param All parameter values. //! void get(TAG tag, std::vector<bool>& param) const; //! //! Get a string parameter. //! @param [in] tag Parameter tag to search. //! @param [out] param Parameter value. //! void get(TAG tag, std::string& param) const { Parameter p; get(tag, p); param.assign(static_cast<const char*>(p.addr), p.length); } //! //! Get a string parameter. //! @param [in] tag Parameter tag to search. //! @param [out] param All parameter values. //! void get(TAG tag, std::vector<std::string>& param) const; //! //! Get an opaque byte block parameter. //! @param [in] tag Parameter tag to search. //! @param [out] param Parameter value. //! void get(TAG tag, ByteBlock& param) const { Parameter p; get(tag, p); param.copy(static_cast<const uint8_t*>(p.addr), p.length); } //! //! Get a compound TLV parameter. //! @param [in] tag Parameter tag to search. //! @param [out] param Safe pointer to the parameter value. //! void getCompound(TAG tag, MessagePtr& param) const; //! //! Get a compound TLV parameter. //! @param [in] tag Parameter tag to search. //! @param [out] param Vector of safe pointers to all parameter values. //! void getCompound(TAG tag, std::vector<MessagePtr>& param) const; //! //! Get a compound TLV parameter (template version). //! @tparam MSG Expected class of parameter value, a subclass of ts::tlv::Message. //! @param [in] tag Parameter tag to search. //! @param [out] param Parameter value. //! template <class MSG> void getCompound(TAG tag, MSG& param) const; //! //! Get a compound TLV parameter (template version). //! @tparam MSG Expected class of parameter value, a subclass of ts::tlv::Message. //! @param [in] tag Parameter tag to search. //! @param [out] param Vector of all parameter values. //! template <class MSG> void getCompound(TAG tag, std::vector<MSG>& param) const; private: // Internal description of a parameter. // Include the description of compound TLV parameter. // When compound.isNull(), this is not a compound TLV parameter. struct ExtParameter : public Parameter { // Public fields: MessageFactoryPtr compound; // for compound TLV parameter // Constructor: ExtParameter(const void* tlv_addr_ = nullptr, size_t tlv_size_ = 0, const void* addr_ = nullptr, LENGTH length_ = 0, MessageFactory* compound_ = nullptr) : Parameter(tlv_addr_, tlv_size_, addr_, length_), compound(compound_) { } }; // MessageFactory private members: const uint8_t* _msg_base; // Addresse of raw TLV message size_t _msg_length; // Size of raw TLV message const Protocol* _protocol; // Associated protocol definition tlv::Error _error_status; // Error status or OK uint16_t _error_info; // Associated error information bool _error_info_is_offset; // Error info is an offset in message VERSION _protocol_version; TAG _command_tag; // Location of actual parameters. Point into the message block. typedef std::multimap <TAG, ExtParameter> ParameterMultimap; ParameterMultimap _params; // Analyze the TLV message, called by constructors. void analyzeMessage(); // Expected size of a type: default is sizeof(). // Specializations can be provided. template <typename T> size_t dataSize() const {return sizeof(T);} // Internal method: Check the size of a parameter. // Should never throw an exception, except bug in the // constructor of the Message subclasses. template <typename T> void checkParamSize(TAG, const ParameterMultimap::const_iterator&) const; }; // Template specializations for performance. //! @cond nodoxygen template<> inline bool MessageFactory::get<bool>(TAG tag) const {return get<uint8_t>(tag) != 0;} template<> inline size_t MessageFactory::dataSize<bool>() const {return 1;} //! @endcond } } #include "tstlvMessageFactoryTemplate.h"
41.261333
107
0.53267
[ "vector" ]
237f5553d7612bde7f75de91328c5b10bdef5e5d
7,098
h
C
btrack/include/tracker.h
chisyliu/BayesianTracker
6eb5261c706b8fd15d22ce4ad1782af4513a7d32
[ "MIT" ]
1
2019-03-20T21:24:18.000Z
2019-03-20T21:24:18.000Z
btrack/include/tracker.h
chisyliu/BayesianTracker
6eb5261c706b8fd15d22ce4ad1782af4513a7d32
[ "MIT" ]
null
null
null
btrack/include/tracker.h
chisyliu/BayesianTracker
6eb5261c706b8fd15d22ce4ad1782af4513a7d32
[ "MIT" ]
null
null
null
/* -------------------------------------------------------------------------------- Name: BayesianTracker Purpose: A multi object tracking library, specifically used to reconstruct tracks in crowded fields. Here we use a probabilistic network of information to perform the trajectory linking. This method uses positional and visual information for track linking. Authors: Alan R. Lowe (arl) a.lowe@ucl.ac.uk License: See LICENSE.md Created: 14/08/2014 -------------------------------------------------------------------------------- */ #ifndef _TRACKER_H_INCLUDED_ #define _TRACKER_H_INCLUDED_ #include "eigen/Eigen/Dense" #include <vector> #include <iostream> #include <map> #include <cmath> #include <limits> #include <algorithm> #include <set> #include <ctime> #include "types.h" #include "motion.h" #include "inference.h" #include "tracklet.h" #include "manager.h" #include "defs.h" #include "hyperbin.h" // #define PROB_NOT_ASSIGN 0.01 // #define DEFAULT_ACCURACY 2.0 // #define DISALLOW_METAPHASE_ANAPHASE_LINKING true // #define PROB_ASSIGN_EXP_DECAY true // #define DYNAMIC_ACCURACY false // #define DIMS 3 // #define FAST_COST_UPDATE false // // // // reserve space for objects and tracks // #define RESERVE_NEW_OBJECTS 1000 // #define RESERVE_ACTIVE_TRACKS 1000 // a pair for hypotheses, track/object ID and probability typedef std::pair<unsigned int, double> LinkHypothesis; // BayesianTracker is a multi object tracking algorithm, specifically // used to reconstruct tracks in crowded fields. Here we use a probabilistic // network of information to perform the trajectory linking. This method uses // positional information (position, velocity ...) as well as visual // information (intensity, correlation...) for track linking. // // The tracking algorithm assembles reliable sections of track that do not // contain cell division events (tracklets). Each new tracklet initiates a // probabilistic model in the form of a Kalman filter (Kalman, 1960), and // utilises this to predict future states (and error in states) of each of the // objects in the field of view. We assign new observations to the growing // tracklets (linking) by evaluating the posterior probability of each // potential linkage from a Bayesian belief matrix for all possible linkages // (Narayana and Haverkamp, 2007). The best linkages are those with the highest // posterior probability. class BayesianTracker { public: // Constructor BayesianTracker() {}; BayesianTracker(const bool verbose); // Default destructor ~BayesianTracker(); // set some parameters // TODO(arl): is this essential anymore? // unsigned int setup(const double prob_not_assign, const unsigned int max_lost, // const double accuracy); // set up the motion model. matrices are in the form of c-style linear arrays unsigned int set_motion_model(const unsigned int measurements, const unsigned int states, double* A_raw, double* H_raw, double* P_raw, double* Q_raw, double* R_raw, const double dt, const double accuracy, const unsigned int max_lost, const double prob_not_assign); // set up the object model unsigned int set_object_model(const unsigned int states, double* transition_raw, double* emission_raw, double* start_raw); // set the maximum search radius void set_max_search_radius(const float search_radius) { this->max_search_radius = search_radius; } // add new objects unsigned int xyzt(const double* xyzt); unsigned int append(const PyTrackObject& new_object); // infer the volume of observations void infer_tracking_volume() const; // initialise the tracker with the first observations unsigned int initialise(); // track and update tracks NOTE: this will be deprecated // unsigned int track(const unsigned int end_frame); // run the tracking on the entire set void track_all(); // move the tracking forward by n iterations, used in interactive mode void step() { step(1); }; void step(const unsigned int n_steps); // get the number of tracks inline unsigned int size() const { return tracks.size(); }; // return the Euclidean distance between object and trajectory double euclidean_dist(const size_t trk, const size_t obj) const { Eigen::Vector3d dxyz = tracks[trk]->position()-new_objects[obj]->position(); return std::sqrt(dxyz.transpose()*dxyz); }; // track maintenance bool purge(); // calculate the cost matrix void cost(Eigen::Ref<Eigen::MatrixXd> belief, const size_t n_tracks, const size_t n_objects); void cost_FAST(Eigen::Ref<Eigen::MatrixXd> belief, const size_t n_tracks, const size_t n_objects); // calculate linkages based on belief matrix void link(Eigen::Ref<Eigen::MatrixXd> belief, const size_t n_tracks, const size_t n_objects); // somewhere to store the tracks TrackManager tracks; // maintain the size of the ImagingVolume ImagingVolume volume; // statistics const PyTrackInfo* stats() { return &statistics; } private: // verbose output to stdio bool verbose = false; // default motion model, must remain uninitialised MotionModel motion_model; // default object model, must remain uninitialised ObjectModel object_model; // default tracking parameters double prob_not_assign = PROB_NOT_ASSIGN; double accuracy = DEFAULT_ACCURACY; unsigned int max_lost = MAX_LOST; // provide a global ID counter for new tracks inline unsigned int get_new_ID() { new_ID++; return new_ID; }; // display the debug output to std::out void debug_output(const unsigned int frm) const; // update the list of active tracks bool update_active(); // pointer to the track manager // TrackManager* p_manager; // maintain pointers to tracks std::vector<TrackletPtr> active; std::vector<TrackObjectPtr> new_objects; // some space to store the objects std::vector<TrackObjectPtr> objects; // sizes of various vectors size_t n_objects; unsigned int current_frame; unsigned int o_counter; // store the frame numbers of incoming tracks std::set<unsigned int> frames_set; std::vector<unsigned int> frames; // tracker initialisation bool initialised = false; // ID counter for new tracks unsigned int new_ID = 0; // counter to run the purge function unsigned int purge_iter; // counters for the number of lost tracks and number of conflicts unsigned int n_lost = 0; unsigned int n_conflicts = 0; float max_search_radius = MAX_SEARCH_RADIUS; // set up a structure for the statistics PyTrackInfo statistics; }; #endif
28.166667
82
0.671034
[ "object", "vector", "model" ]
238338c3d31262124bfb3c9d26bcc499bcf74c8d
2,611
h
C
11/debian-10/postgresql-repmgr-11.11.0-15-linux-amd64-debian-10/files/postgresql/include/geos/geomgraph/index/MonotoneChainEdge.h
molliezhang/radondb-postgresql-kubernetes-1
7a3cbb050eb708a6db209e0effc8e5a4b34a2900
[ "Apache-2.0" ]
57
2020-02-08T17:52:17.000Z
2021-10-14T03:45:09.000Z
11/debian-10/postgresql-repmgr-11.11.0-15-linux-amd64-debian-10/files/postgresql/include/geos/geomgraph/index/MonotoneChainEdge.h
molliezhang/radondb-postgresql-kubernetes-1
7a3cbb050eb708a6db209e0effc8e5a4b34a2900
[ "Apache-2.0" ]
47
2020-02-12T16:41:40.000Z
2021-09-28T22:27:56.000Z
11/debian-10/postgresql-repmgr-11.11.0-15-linux-amd64-debian-10/files/postgresql/include/geos/geomgraph/index/MonotoneChainEdge.h
molliezhang/radondb-postgresql-kubernetes-1
7a3cbb050eb708a6db209e0effc8e5a4b34a2900
[ "Apache-2.0" ]
8
2020-03-17T11:18:07.000Z
2021-10-14T03:45:15.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2005-2006 Refractions Research Inc. * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #ifndef GEOS_GEOMGRAPH_INDEX_MONOTONECHAINEDGE_H #define GEOS_GEOMGRAPH_INDEX_MONOTONECHAINEDGE_H #include <geos/export.h> #include <geos/geom/Envelope.h> // for composition #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4251) // warning C4251: needs to have dll-interface to be used by clients of class #endif // Forward declarations namespace geos { namespace geom { class CoordinateSequence; } namespace geomgraph { class Edge; namespace index { class SegmentIntersector; } } } namespace geos { namespace geomgraph { // geos::geomgraph namespace index { // geos::geomgraph::index class GEOS_DLL MonotoneChainEdge { public: //MonotoneChainEdge(); ~MonotoneChainEdge() = default; MonotoneChainEdge(Edge* newE); const geom::CoordinateSequence* getCoordinates(); std::vector<size_t>& getStartIndexes(); double getMinX(size_t chainIndex); double getMaxX(size_t chainIndex); void computeIntersects(const MonotoneChainEdge& mce, SegmentIntersector& si); void computeIntersectsForChain(size_t chainIndex0, const MonotoneChainEdge& mce, size_t chainIndex1, SegmentIntersector& si); protected: Edge* e; const geom::CoordinateSequence* pts; // cache a reference to the coord array, for efficiency // the lists of start/end indexes of the monotone chains. // Includes the end point of the edge as a sentinel std::vector<size_t> startIndex; // these envelopes are created once and reused private: void computeIntersectsForChain(size_t start0, size_t end0, const MonotoneChainEdge& mce, size_t start1, size_t end1, SegmentIntersector& ei); bool overlaps(size_t start0, size_t end0, const MonotoneChainEdge& mce, size_t start1, size_t end1); }; } // namespace geos.geomgraph.index } // namespace geos.geomgraph } // namespace geos #ifdef _MSC_VER #pragma warning(pop) #endif #endif
29.670455
107
0.65339
[ "geometry", "vector" ]
238669f09b103b8db17743aaf4623db8463af299
2,880
c
C
cmds/spells/e/_exhume_corpses.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
cmds/spells/e/_exhume_corpses.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
cmds/spells/e/_exhume_corpses.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <spell.h> #include <objects.h> #include <magic.h> inherit SPELL; void create() { ::create(); set_spell_name("exhume corpses"); set_spell_level(([ "mage" : 6, "cleric" : 5, "inquisitor":5])); set_spell_sphere("necromancy"); set_syntax("cast CLASS exhume corpses"); set_description("With this art the necromancer taps onto the natural flow of negative energies and uses them to track and summon corpses, from various places in the world to the place he is in. The corpses summoned are that of common folk and thus are weak. This spell by itself does nothing to the souls of the deceased, yet the reason why necromancer calls to it is obvious, and thus only evil caster will ever call to it. Using this spell in civilized lands attracts unneeded attention."); set_helpful_spell(1); } string query_cast_string() { tell_object(caster,"%^CYAN%^Y%^BOLD%^%^BLACK%^o%^RESET%^%^CYAN%^u%^CYAN%^ close your eyes and turn around slowly, chanting a low song and dusting the ground with %^BOLD%^%^BLACK%^b%^BLACK%^o%^WHITE%^n%^BLACK%^e %^WHITE%^m%^BLACK%^e%^WHITE%^a%^BLACK%^l%^RESET%^%^CYAN%^ and %^CYAN%^c%^CYAN%^a%^BOLD%^%^BLACK%^r%^RESET%^%^CYAN%^b%^CYAN%^o%^BOLD%^%^BLACK%^n%^RESET%^%^CYAN%^."); tell_room(place,"%^CYAN%^"+caster->QCN+" closes "+caster->QP+" eyes and turns around slowly, chanting a low song and dusting the ground with %^BOLD%^%^BLACK%^b%^BLACK%^o%^WHITE%^n%^BLACK%^e %^WHITE%^m%^BLACK%^e%^WHITE%^a%^BLACK%^l%^RESET%^%^CYAN%^ and %^CYAN%^c%^CYAN%^a%^BOLD%^%^BLACK%^r%^RESET%^%^CYAN%^b%^CYAN%^o%^BOLD%^%^BLACK%^n%^RESET%^%^CYAN%^.",caster); return "display"; } void spell_effect() { int i; tell_room(place,"%^CYAN%^A low continuous thunder rolls over the place, and %^BOLD%^%^BLACK%^co%^RESET%^%^CYAN%^r%^BOLD%^%^BLACK%^p%^RESET%^%^CYAN%^s%^CYAN%^e%^BOLD%^%^BLACK%^s%^RESET%^%^CYAN%^ begin to materialize everywhere."); for (i=0; i<clevel/10 + 1; i++) { object corpse; corpse = new(OB_CORPSE); corpse->set_name("human"); corpse->copy_body(caster); corpse->set_gender(({"male","female"})[random(2)]); corpse->set_long("%^CYAN%^Before you is an %^CYAN%^o%^CYAN%^l%^CYAN%^d %^CYAN%^c%^BOLD%^%^BLACK%^o%^RESET%^%^CYAN%^r%^BOLD%^%^BLACK%^p%^RESET%^%^CYAN%^s%^CYAN%^e%^CYAN%^ of a human being in tattered clothes. Its features are %^CYAN%^r%^BOLD%^%^BLACK%^ott%^RESET%^%^CYAN%^e%^BOLD%^%^BLACK%^n %^BLACK%^aw%^RESET%^%^CYAN%^a%^BOLD%^%^BLACK%^y%^RESET%^%^CYAN%^ and are hard to discern. It smells as disgustingly as it looks, %^BOLD%^%^WHITE%^bi%^BLACK%^t%^WHITE%^s %^BLACK%^o%^WHITE%^f %^BLACK%^b%^WHITE%^o%^BLACK%^n%^BLACK%^e%^RESET%^%^CYAN%^ peer through decayed pieces. Who it was in life is impossible to tell at this point."); corpse->set_short("%^CYAN%^A human corpse%^RESET%^"); corpse->set_level(1); corpse->move(place); } }
68.571429
634
0.647222
[ "object" ]
238670f48bf1fab59e4de4167174cb3acad66655
6,870
h
C
src/ghost-address/stealth.h
nzsquirrell/NixCore
0cdc4455b4660f712abe6dc9f2777c77b371461f
[ "MIT" ]
43
2018-06-27T22:35:17.000Z
2021-01-21T01:18:15.000Z
src/ghost-address/stealth.h
nzsquirrell/NixCore
0cdc4455b4660f712abe6dc9f2777c77b371461f
[ "MIT" ]
32
2018-06-27T12:43:36.000Z
2020-12-04T22:23:36.000Z
src/ghost-address/stealth.h
nzsquirrell/NixCore
0cdc4455b4660f712abe6dc9f2777c77b371461f
[ "MIT" ]
27
2018-06-27T16:07:19.000Z
2021-02-21T21:10:38.000Z
// Copyright (c) 2014 The ShadowCoin developers // Copyright (c) 2017 The Particl developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #ifndef KEY_STEALTH_H #define KEY_STEALTH_H #include <stdlib.h> #include <stdio.h> #include <vector> #include <inttypes.h> #include <util.h> #include <serialize.h> #include <key.h> #include <uint256.h> #include <ghost-address/types.h> #include "lz4.h" #include <cstdio> #include <cstdlib> #include <cstring> class CScript; const uint32_t MAX_STEALTH_NARRATION_SIZE = 48; const uint32_t MIN_STEALTH_RAW_SIZE = 1 + 33 + 1 + 33 + 1 + 1; // without checksum (4bytes) or version (1byte) typedef uint32_t stealth_bitfield; struct stealth_prefix { uint8_t number_bits; stealth_bitfield bitfield; }; class CStealthAddress { public: CStealthAddress() { options = 0; number_signatures = 0; prefix.number_bits = 0; //index = 0; }; uint8_t options; stealth_prefix prefix; int number_signatures; ec_point scan_pubkey; ec_point spend_pubkey; mutable std::string label; CKey scan_secret; // Better to store the scan secret here as it's needed often CKeyID spend_secret_id; // store the spend secret in a keystore //CKey spend_secret; //uint32_t index; bool SetEncoded(const std::string &encodedAddress); std::string Encoded(bool fBech32=false) const; std::string ToString(bool fBech32=false) const {return Encoded(fBech32);} int FromRaw(const uint8_t *p, size_t nSize); int ToRaw(std::vector<uint8_t> &raw) const; int SetScanPubKey(CPubKey pk); CKeyID GetSpendKeyID() const; bool operator <(const CStealthAddress &y) const { return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], EC_COMPRESSED_SIZE) < 0; }; bool operator ==(const CStealthAddress &y) const { return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], EC_COMPRESSED_SIZE) == 0; }; template<typename Stream> void Serialize(Stream &s) const { s << options; s << number_signatures; s << prefix.number_bits; s << prefix.bitfield; s << scan_pubkey; s << spend_pubkey; s << label; bool fHaveScanSecret = scan_secret.IsValid(); s << fHaveScanSecret; if (fHaveScanSecret) s.write((char*)scan_secret.begin(), EC_SECRET_SIZE); } template <typename Stream> void Unserialize(Stream &s) { s >> options; s >> number_signatures; s >> prefix.number_bits; s >> prefix.bitfield; s >> scan_pubkey; s >> spend_pubkey; s >> label; bool fHaveScanSecret; s >> fHaveScanSecret; if (fHaveScanSecret) { s.read((char*)scan_secret.begin(), EC_SECRET_SIZE); scan_secret.SetFlags(true, true); // Only derive spend_secret_id if also have the scan secret. if (spend_pubkey.size() == EC_COMPRESSED_SIZE) // TODO: won't work for multiple spend pubkeys spend_secret_id = GetSpendKeyID(); }; } }; int SecretToPublicKey(const CKey &secret, ec_point &out); int StealthShared(const CKey &secret, const ec_point &pubkey, CKey &sharedSOut); int StealthSecret(const CKey &secret, const ec_point &pubkey, const ec_point &pkSpend, CKey &sharedSOut, ec_point &pkOut); int StealthSecretSpend(const CKey &scanSecret, const ec_point &ephemPubkey, const CKey &spendSecret, CKey &secretOut); int StealthSharedToSecretSpend(const CKey &sharedS, const CKey &spendSecret, CKey &secretOut); int StealthSharedToPublicKey(const ec_point &pkSpend, const CKey &sharedS, ec_point &pkOut); bool IsStealthAddress(const std::string &encodedAddress); inline uint32_t SetStealthMask(uint8_t nBits) { return (nBits == 32 ? 0xFFFFFFFF : ((1<<nBits)-1)); }; uint32_t FillStealthPrefix(uint8_t nBits, uint32_t nBitfield); bool ExtractStealthPrefix(const char *pPrefix, uint32_t &nPrefix); int MakeStealthData(const std::string &sNarration, stealth_prefix prefix, const CKey &sShared, const CPubKey &pkEphem, std::vector<uint8_t> &vData, uint32_t &nStealthPrefix, std::string &sError); int PrepareStealthOutput(const CStealthAddress &sx, const std::string &sNarration, CScript &scriptPubKey, std::vector<uint8_t> &vData, std::string &sError); void ECC_Start_Stealth(); void ECC_Stop_Stealth(); /* * * * * * */ typedef std::vector<uint8_t> data_chunk; const size_t ec_secret_size = 32; const size_t ec_compressed_size = 33; const size_t ec_uncompressed_size = 65; typedef struct ec_secret { uint8_t e[ec_secret_size]; } ec_secret; typedef data_chunk ec_point; typedef uint32_t stealth_bitfield; template <typename T, typename Iterator> T from_big_endian(Iterator in) { //VERIFY_UNSIGNED(T); T out = 0; size_t i = sizeof(T); while (0 < i) out |= static_cast<T>(*in++) << (8 * --i); return out; } template <typename T, typename Iterator> T from_little_endian(Iterator in) { //VERIFY_UNSIGNED(T); T out = 0; size_t i = 0; while (i < sizeof(T)) out |= static_cast<T>(*in++) << (8 * i++); return out; } class CGhostAddress { public: CGhostAddress() { options = 0; } uint8_t options; ec_point scan_pubkey; ec_point spend_pubkey; size_t number_signatures; stealth_prefix prefix; mutable std::string label; data_chunk scan_secret; data_chunk spend_secret; bool SetEncoded(const std::string& encodedAddress); std::string Encoded() const; bool operator <(const CGhostAddress& y) const { return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], ec_compressed_size) < 0; } bool operator ==(const CGhostAddress &y) const { return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], ec_compressed_size) == 0; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->options); READWRITE(this->scan_pubkey); READWRITE(this->spend_pubkey); READWRITE(this->label); READWRITE(this->scan_secret); READWRITE(this->spend_secret); } }; int GenerateRandomSecret(ec_secret& out); int SecretToPublicKey(const ec_secret& secret, ec_point& out); int StealthSecret(ec_secret& secret, ec_point& pubkey, const ec_point& pkSpend, ec_secret& sharedSOut, ec_point& pkOut); int StealthSecretSpend(ec_secret& scanSecret, ec_point& ephemPubkey, ec_secret& spendSecret, ec_secret& secretOut); int StealthSharedToSecretSpend(ec_secret& sharedS, ec_secret& spendSecret, ec_secret& secretOut); bool IsGhostAddress(const std::string& encodedAddress); #endif // KEY_STEALTH_H
26.423077
122
0.682824
[ "vector" ]
2387c0759e8bc47c46d86674022279581ad2ddb0
12,834
h
C
src/bitcoinrpc.h
oicu8/Neutron
85c17878f2225b7aaf54d2bd03997973712ccc5a
[ "MIT" ]
31
2017-10-05T16:06:42.000Z
2021-02-22T17:52:52.000Z
src/bitcoinrpc.h
oicu8/Neutron
85c17878f2225b7aaf54d2bd03997973712ccc5a
[ "MIT" ]
25
2017-09-27T01:07:44.000Z
2020-07-19T15:38:39.000Z
src/bitcoinrpc.h
oicu8/Neutron
85c17878f2225b7aaf54d2bd03997973712ccc5a
[ "MIT" ]
38
2017-09-09T15:41:20.000Z
2021-03-08T20:07:14.000Z
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2015-2020 The Neutron Developers // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _BITCOINRPC_H_ #define _BITCOINRPC_H_ #include <string> #include <list> #include <map> class CBlockIndex; #include "json/json_spirit_reader_template.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_utils.h" #include "util.h" #include "checkpoints.h" #include "univalue.h" class CRPCCommand; enum HTTPStatusCode { HTTP_OK = 200, HTTP_BAD_REQUEST = 400, HTTP_UNAUTHORIZED = 401, HTTP_FORBIDDEN = 403, HTTP_NOT_FOUND = 404, HTTP_BAD_METHOD = 405, HTTP_INTERNAL_SERVER_ERROR = 500, HTTP_SERVICE_UNAVAILABLE = 503, }; enum RPCErrorCode { // Standard JSON-RPC 2.0 errors RPC_INVALID_REQUEST = -32600, RPC_METHOD_NOT_FOUND = -32601, RPC_INVALID_PARAMS = -32602, RPC_INTERNAL_ERROR = -32603, RPC_PARSE_ERROR = -32700, // General application defined errors RPC_MISC_ERROR = -1, // std::exception thrown in command handling RPC_FORBIDDEN_BY_SAFE_MODE = -2, // Server is in safe mode, and command is not allowed in safe mode RPC_TYPE_ERROR = -3, // Unexpected type was passed as parameter RPC_INVALID_ADDRESS_OR_KEY = -5, // Invalid address or key RPC_OUT_OF_MEMORY = -7, // Ran out of memory during operation RPC_INVALID_PARAMETER = -8, // Invalid, missing or duplicate parameter RPC_DATABASE_ERROR = -20, // Database error RPC_DESERIALIZATION_ERROR = -22, // Error parsing or validating structure in raw format // P2P client errors RPC_CLIENT_NOT_CONNECTED = -9, RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, // Still downloading initial blocks RPC_CLIENT_NODE_ALREADY_ADDED = -23, // Node is already added RPC_CLIENT_NODE_NOT_ADDED = -24, // Node has not been added before RPC_CLIENT_NODE_NOT_CONNECTED = -29, // Node to disconnect not found in connected nodes RPC_CLIENT_INVALID_IP_OR_SUBNET = -30, // Invalid IP/Subnet RPC_CLIENT_P2P_DISABLED = -31, // No valid connection manager instance found // Wallet errors RPC_WALLET_ERROR = -4, // Unspecified problem with wallet (key not found etc.) RPC_WALLET_INSUFFICIENT_FUNDS = -6, // Not enough funds in wallet or account RPC_WALLET_INVALID_ACCOUNT_NAME = -11, // Invalid account name RPC_WALLET_KEYPOOL_RAN_OUT = -12, // Keypool ran out, call keypoolrefill first RPC_WALLET_UNLOCK_NEEDED = -13, // Enter the wallet passphrase with walletpassphrase first RPC_WALLET_PASSPHRASE_INCORRECT = -14, // The wallet passphrase entered was incorrect RPC_WALLET_WRONG_ENC_STATE = -15, // Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.) RPC_WALLET_ENCRYPTION_FAILED = -16, // Failed to encrypt the wallet RPC_WALLET_ALREADY_UNLOCKED = -17, // Wallet is already unlocked }; /* Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type. Only used by RPCTypeCheckObj */ struct UniValueType { UniValueType(UniValue::VType _type) : typeAny(false), type(_type) { } UniValueType() : typeAny(true) { } bool typeAny; UniValue::VType type; }; class JSONRPCRequest { public: UniValue id; std::string strMethod; UniValue params; bool fHelp; std::string URI; std::string authUser; JSONRPCRequest() { id = NullUniValue; params = NullUniValue; fHelp = false; } void parse(const UniValue& valRequest); }; UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id); UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const UniValue& id); std::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id); UniValue JSONRPCError(int code, const std::string& message); void ThreadRPCServer(void* parg); int CommandLineRPC(int argc, char *argv[]); // Convert parameter values for RPC call from strings to command-specific JSON objects UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams); // Convert named arguments to command-specific RPC representation UniValue RPCConvertNamedValues(const std::string& strMethod, const std::vector<std::string>& strParams); /* Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal); bool IsRPCRunning(); void RPCTypeCheck(const UniValue& params, const std::list<UniValue::VType>& typesExpected, bool fAllowNull=false); void RPCTypeCheckArgument(const UniValue& value, UniValue::VType typeExpected); void RPCTypeCheckObj(const UniValue& o, const std::map<std::string, UniValueType>& typesExpected, bool fAllowNull = false, bool fStrict = false); typedef UniValue(*rpcfn_type)(const UniValue& params, bool fHelp); class CRPCCommand { public: std::string name; rpcfn_type actor; bool okSafeMode; bool unlocked; }; // RPC command dispatcher class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](std::string name) const; std::string help(std::string name) const; UniValue execute(const JSONRPCRequest &request) const; std::vector<std::string> listCommands() const; bool appendCommand(const std::string& name, const CRPCCommand* pcmd); }; extern CRPCTable tableRPC; extern int64_t nWalletUnlockTime; extern CAmount AmountFromValue(const UniValue& value); extern UniValue ValueFromAmount(const CAmount& amount); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern double GetPoWMHashPS(); extern double GetPoSKernelPS(); extern std::string HexBits(unsigned int nBits); extern std::string HelpRequiringPassphrase(); extern void EnsureWalletIsUnlocked(); // Utilities: convert hex-encoded Values // (throws error if not hex). extern uint256 ParseHashV(const UniValue& v, std::string strName); extern uint256 ParseHashO(const UniValue& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName); extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey); extern std::string HelpExampleCli(std::string methodname, std::string args); extern std::string HelpExampleRpc(std::string methodname, std::string args); // in rpcnet.cpp extern UniValue getconnectioncount(const UniValue& params, bool fHelp); extern UniValue getpeerinfo(const UniValue& params, bool fHelp); extern UniValue addnode(const UniValue& params, bool fHelp); extern UniValue disconnectnode(const UniValue& params, bool fHelp); extern UniValue setban(const UniValue& params, bool fHelp); extern UniValue listbanned(const UniValue& params, bool fHelp); extern UniValue clearbanned(const UniValue& params, bool fHelp); extern UniValue sendalert(const UniValue& params, bool fHelp); extern UniValue spork(const UniValue& params, bool fHelp); // in rpcdarksend.cpp extern UniValue getpoolinfo(const UniValue& params, bool fHelp); extern UniValue masternode(const UniValue& params, bool fHelp); extern UniValue masternodelist(const UniValue& params, bool fHelp); extern UniValue masternodecount(const UniValue& params, bool fHelp); // in rpcdump.cpp extern UniValue importprivkey(const UniValue& params, bool fHelp); extern UniValue importwallet(const UniValue& params, bool fHelp); extern UniValue dumpprivkey(const UniValue& params, bool fHelp); extern UniValue dumpwallet(const UniValue& params, bool fHelp); // in rpcmining.cpp extern UniValue getsubsidy(const UniValue& params, bool fHelp); extern UniValue getmininginfo(const UniValue& params, bool fHelp); extern UniValue getstakinginfo(const UniValue& params, bool fHelp); extern UniValue getworkex(const UniValue& params, bool fHelp); extern UniValue getwork(const UniValue& params, bool fHelp); extern UniValue getblocktemplate(const UniValue& params, bool fHelp); extern UniValue submitblock(const UniValue& params, bool fHelp); extern UniValue setgenerate(const UniValue& params, bool fHelp); extern UniValue gethashespersec(const UniValue& params, bool fHelp); // in rpcwallet.cpp extern UniValue getinfo(const UniValue& params, bool fHelp); extern UniValue getdebuginfo(const UniValue& params, bool fHelp); extern UniValue getnewpubkey(const UniValue& params, bool fHelp); extern UniValue getnewaddress(const UniValue& params, bool fHelp); extern UniValue getaccountaddress(const UniValue& params, bool fHelp); extern UniValue setaccount(const UniValue& params, bool fHelp); extern UniValue getaccount(const UniValue& params, bool fHelp); extern UniValue getaddressesbyaccount(const UniValue& params, bool fHelp); extern UniValue sendtoaddress(const UniValue& params, bool fHelp); extern UniValue listaddressgroupings(const UniValue& params, bool fHelp); extern UniValue signmessage(const UniValue& params, bool fHelp); extern UniValue verifymessage(const UniValue& params, bool fHelp); extern UniValue getreceivedbyaddress(const UniValue& params, bool fHelp); extern UniValue getreceivedbyaccount(const UniValue& params, bool fHelp); extern UniValue getbalance(const UniValue& params, bool fHelp); extern UniValue movecmd(const UniValue& params, bool fHelp); extern UniValue sendfrom(const UniValue& params, bool fHelp); extern UniValue sendmany(const UniValue& params, bool fHelp); extern UniValue addmultisigaddress(const UniValue& params, bool fHelp); extern UniValue addredeemscript(const UniValue& params, bool fHelp); extern UniValue listreceivedbyaddress(const UniValue& params, bool fHelp); extern UniValue listreceivedbyaccount(const UniValue& params, bool fHelp); extern UniValue listtransactions(const UniValue& params, bool fHelp); extern UniValue listaccounts(const UniValue& params, bool fHelp); extern UniValue listsinceblock(const UniValue& params, bool fHelp); extern UniValue gettransaction(const UniValue& params, bool fHelp); extern UniValue backupwallet(const UniValue& params, bool fHelp); extern UniValue keypoolrefill(const UniValue& params, bool fHelp); extern UniValue walletpassphrase(const UniValue& params, bool fHelp); extern UniValue walletpassphrasechange(const UniValue& params, bool fHelp); extern UniValue walletlock(const UniValue& params, bool fHelp); extern UniValue encryptwallet(const UniValue& params, bool fHelp); extern UniValue validateaddress(const UniValue& params, bool fHelp); extern UniValue validatepubkey(const UniValue& params, bool fHelp); extern UniValue reservebalance(const UniValue& params, bool fHelp); extern UniValue checkwallet(const UniValue& params, bool fHelp); extern UniValue repairwallet(const UniValue& params, bool fHelp); extern UniValue resendtx(const UniValue& params, bool fHelp); extern UniValue makekeypair(const UniValue& params, bool fHelp); extern UniValue getminingreport(const UniValue& params, bool fHelp); extern UniValue listlockunspent(const UniValue& params, bool fHelp); extern UniValue lockunspent(const UniValue& params, bool fHelp); // in rcprawtransaction.cpp extern UniValue getrawtransaction(const UniValue& params, bool fHelp); extern UniValue listunspent(const UniValue& params, bool fHelp); extern UniValue createrawtransaction(const UniValue& params, bool fHelp); extern UniValue decoderawtransaction(const UniValue& params, bool fHelp); extern UniValue decodescript(const UniValue& params, bool fHelp); extern UniValue signrawtransaction(const UniValue& params, bool fHelp); extern UniValue sendrawtransaction(const UniValue& params, bool fHelp); // in rpcblockchain.cpp extern UniValue getbestblockhash(const UniValue& params, bool fHelp); extern UniValue getblockcount(const UniValue& params, bool fHelp); extern UniValue getdifficulty(const UniValue& params, bool fHelp); extern UniValue settxfee(const UniValue& params, bool fHelp); extern UniValue getrawmempool(const UniValue& params, bool fHelp); extern UniValue getblockhash(const UniValue& params, bool fHelp); extern UniValue getblock(const UniValue& params, bool fHelp); extern UniValue getblockbynumber(const UniValue& params, bool fHelp); extern UniValue getblockbyrange(const UniValue& params, bool fHelp); extern UniValue getcheckpoint(const UniValue& params, bool fHelp); extern UniValue getblockversionstats(const UniValue& params, bool fHelp); extern UniValue invalidateblock(const UniValue& params, bool fHelp); #endif
46.33213
130
0.765155
[ "vector" ]
238f82da6f285e787d4b6a3e5f58713fb5cfe187
1,404
h
C
GeneratorInterface/HiGenCommon/interface/HadronDecayGenEvtSelector.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
GeneratorInterface/HiGenCommon/interface/HadronDecayGenEvtSelector.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
GeneratorInterface/HiGenCommon/interface/HadronDecayGenEvtSelector.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef _HI_HadronDecayGenEvtSelector_h__ #define _HI_HadronDecayGenEvtSelector_h__ #include <vector> #include "GeneratorInterface/HiGenCommon/interface/BaseHiGenEvtSelector.h" class HadronDecayGenEvtSelector : public BaseHiGenEvtSelector { public: HadronDecayGenEvtSelector(const edm::ParameterSet& pset); ~HadronDecayGenEvtSelector() override { ; } bool filter(HepMC::GenEvent*) override; bool selectParticle(HepMC::GenParticle* par, int status, int pdg /*Absolute*/, double etaMax, double etaMin, double pMin, double ptMax, double ptMin) { return (par->status() == status && abs(par->pdg_id()) == pdg && par->momentum().eta() < etaMax && par->momentum().eta() > etaMin && par->momentum().rho() > pMin && par->momentum().perp() < ptMax && par->momentum().perp() > ptMin); } private: std::vector<int> hadronId_; std::vector<int> hadronStatus_; std::vector<double> hadronEtaMax_; std::vector<double> hadronEtaMin_; std::vector<double> hadronPMin_; std::vector<double> hadronPtMax_; std::vector<double> hadronPtMin_; int decayId_; int decayStatus_; double decayEtaMax_; double decayEtaMin_; double decayPMin_; double decayPtMax_; double decayPtMin_; int decayNtrig_; }; #endif
30.521739
111
0.64245
[ "vector" ]
239f9221a7cbc2a084f8fa23a4b0f575be52d23d
2,298
h
C
oxygine/src/core/FileSystem.h
chuckvalenza/oxygine-framework
e6cd7b78091e75e0dc5900fcdeadba4b97197d40
[ "MIT" ]
null
null
null
oxygine/src/core/FileSystem.h
chuckvalenza/oxygine-framework
e6cd7b78091e75e0dc5900fcdeadba4b97197d40
[ "MIT" ]
null
null
null
oxygine/src/core/FileSystem.h
chuckvalenza/oxygine-framework
e6cd7b78091e75e0dc5900fcdeadba4b97197d40
[ "MIT" ]
null
null
null
#pragma once #include "oxygine-include.h" #include "Object.h" namespace oxygine { namespace file { class buffer; class fileHandle: public ObjectBase { public: virtual void release() = 0; virtual unsigned int read(void* dest, unsigned int size) = 0; virtual unsigned int write(const void* src, unsigned int size) = 0; virtual unsigned int getSize() const = 0; virtual int seek(unsigned int offset, int whence) = 0; virtual unsigned int tell() const = 0; }; class FileSystem { public: enum status { //don't add new items (isExists will be broken) status_error, status_ok, }; FileSystem(bool readonly); virtual ~FileSystem(); void setPrefix(const char* str); bool isExists(const char* file); bool isExistsHere(const char* file); status deleteFile(const char* file); status renameFile(const char* src, const char* dest); status makeDirectory(const char* path); status deleteDirectory(const char* path); status open(const char* file, const char* mode, error_policy ep, fileHandle*& fh); status read(const char* file, file::buffer& bf, error_policy ep); void mount(FileSystem* fs); void unmount(FileSystem* fs); protected: virtual status _open(const char* file, const char* mode, error_policy ep, fileHandle*&) = 0; virtual status _read(const char* file, file::buffer&, error_policy ep) = 0; virtual bool _isExists(const char* file); virtual status _deleteFile(const char* file) = 0; virtual status _makeDirectory(const char* path) = 0; virtual status _deleteDirectory(const char* path) = 0; virtual status _renameFile(const char* src, const char* dest) = 0; char _prefix[32]; bool _readonly; typedef std::vector<FileSystem*> filesystems; filesystems _filesystems; }; void mount(FileSystem* fs); void unmount(FileSystem* fs); } }
32.366197
104
0.56745
[ "object", "vector" ]
23a25faa4c25e54ca940b74dcc49e15be7382c07
3,158
h
C
AudioKit/Core/STK/include/Envelope.h
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
206
2020-10-28T12:47:49.000Z
2022-03-26T14:09:30.000Z
AudioKit/Core/STK/include/Envelope.h
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
7
2020-10-29T10:29:23.000Z
2021-08-07T00:22:03.000Z
AudioKit/Core/STK/include/Envelope.h
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
30
2020-10-28T16:11:40.000Z
2021-12-28T01:15:23.000Z
#pragma once #include "Generator.h" namespace stk { /***************************************************/ /*! \class Envelope \brief STK linear line envelope class. This class implements a simple linear line envelope generator which is capable of ramping to an arbitrary target value by a specified \e rate. It also responds to simple \e keyOn and \e keyOff messages, ramping to 1.0 on keyOn and to 0.0 on keyOff. by Perry R. Cook and Gary P. Scavone, 1995--2016. */ /***************************************************/ class Envelope : public Generator { public: //! Default constructor. Envelope(); //! Class destructor. ~Envelope(); //! Assignment operator. Envelope &operator=(const Envelope &e); //! Set target = 1. void keyOn() { this->setTarget(1.0); }; //! Set target = 0. void keyOff() { this->setTarget(0.0); }; //! Set the \e rate. /*! The \e rate must be positive (though a value of 0.0 is allowed). */ void setRate(StkFloat rate); //! Set the \e rate based on a positive time duration (seconds). /*! The \e rate is calculated such that the envelope will ramp from a value of 0.0 to 1.0 in the specified time duration. */ void setTime(StkFloat time); //! Set the target value. void setTarget(StkFloat target); //! Set current and target values to \e value. void setValue(StkFloat value); //! Return the current envelope \e state (0 = at target, 1 otherwise). int getState(void) const { return state_; }; //! Return the last computed output value. StkFloat lastOut(void) const { return lastFrame_[0]; }; //! Compute and return one output sample. StkFloat tick(); //! Fill a channel of the StkFrames object with computed outputs. /*! The \c channel argument must be less than the number of channels in the StkFrames argument (the first channel is specified by 0). However, range checking is only performed if _STK_DEBUG_ is defined during compilation, in which case an out-of-range value will trigger an StkError exception. */ StkFrames &tick(StkFrames &frames, unsigned int channel = 0); protected: void sampleRateChanged(StkFloat newRate, StkFloat oldRate); StkFloat value_; StkFloat target_; StkFloat rate_; int state_; }; inline StkFloat Envelope::tick() { if (state_) { if (target_ > value_) { value_ += rate_; if (value_ >= target_) { value_ = target_; state_ = 0; } } else { value_ -= rate_; if (value_ <= target_) { value_ = target_; state_ = 0; } } lastFrame_[0] = value_; } return value_; } inline StkFrames &Envelope::tick(StkFrames &frames, unsigned int channel) { #if defined(_STK_DEBUG_) if (channel >= frames.channels()) { oStream_ << "Envelope::tick(): channel and StkFrames arguments are " "incompatible!"; handleError(StkError::FUNCTION_ARGUMENT); } #endif StkFloat *samples = &frames[channel]; unsigned int hop = frames.channels(); for (unsigned int i = 0; i < frames.frames(); i++, samples += hop) *samples = tick(); return frames; } }
25.467742
75
0.632679
[ "object" ]
23a316b0786bb36546c96d527f2ba475a94d68bb
1,891
c
C
d/laerad/parnelli/asgard/gen_storage.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/laerad/parnelli/asgard/gen_storage.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/laerad/parnelli/asgard/gen_storage.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
//updated by Styx to use general store inherit 9/15/01 //Coded by Bane// #include <std.h> #include "/d/common/common.h" inherit "/d/common/inherit/gs_storage.c"; object ob; void create() { ::create(); set_property("no teleport",1); set_name("Asgard's general store storage room"); set_short("Asgard's general store storage room"); set_long( "This is a storage room. If you are a mortal you shouldnt be here. "+ "Either teleport out or ask an immort to remove you." ); set_property("light",1); set_property("indoors",1); set_smell("default","It smells of oil and old clothes."); set_listen("default","The room is silent."); set_exits( ([ ]) ); } void reset() { ::reset(); if(!present("sword")) new(CWEAP"longsword")->move(TO); if(!present("axe")) new(CWEAP"battle_axe")->move(TO); if(!present("dagger")) new(CWEAP"dagger")->move(TO); if(!present("morningstar")) new(CWEAP"morningstar")->move(TO); if(!present("banded")) { ob = new(CARMOR"banded"); ob->move(TO); if(!random(2)){ ob->set_size(2); } else { ob->set_size(1); } } if(!present("chain")) { ob = new(CARMOR"chain"); ob->move(TO); if(!random(2)){ ob->set_size(2); } else { ob->set_size(1); } } if(!present("hide")){ ob = new(CARMOR"hide"); ob->move(TO); if(!random(2)){ ob->set_size(2); } else { ob->set_size(1); } } if(!present("leather")){ ob = new(CARMOR"leather"); ob->move(TO); if(!random(2)){ ob->set_size(2); } else { ob->set_size(1); } } if(!present("studded")){ ob = new(CARMOR"studded"); ob->move(TO); if(!random(2)){ ob->set_size(2); } else { ob->set_size(1); } } if(!present("helm")) new(CARMOR"helm")->move(TO); if(!present("robe")) new(CARMOR"robe")->move(TO); }
26.633803
72
0.563194
[ "object" ]
23aa82125dc920ce102d0f4f4d52ad4aff9122eb
11,648
c
C
src/qemu/src-pmp/chardev/char-mux.c
pmp-tool/PMP
ef5e05fb4612bb622a9e1039f772c6234b87df7d
[ "MIT" ]
8
2020-09-06T12:49:00.000Z
2022-03-09T04:02:06.000Z
src/qemu/src-pmp/chardev/char-mux.c
newthis/PMP
ef5e05fb4612bb622a9e1039f772c6234b87df7d
[ "MIT" ]
null
null
null
src/qemu/src-pmp/chardev/char-mux.c
newthis/PMP
ef5e05fb4612bb622a9e1039f772c6234b87df7d
[ "MIT" ]
7
2020-09-08T15:14:34.000Z
2021-06-24T18:03:49.000Z
/* * QEMU System Emulator * * Copyright (c) 2003-2008 Fabrice Bellard * * 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 "qemu/osdep.h" #include "qapi/error.h" #include "qemu/option.h" #include "chardev/char.h" #include "sysemu/block-backend.h" #include "sysemu/sysemu.h" #include "chardev/char-mux.h" /* MUX driver for serial I/O splitting */ /* Called with chr_write_lock held. */ static int mux_chr_write(Chardev *chr, const uint8_t *buf, int len) { MuxChardev *d = MUX_CHARDEV(chr); int ret; if (!d->timestamps) { ret = qemu_chr_fe_write(&d->chr, buf, len); } else { int i; ret = 0; for (i = 0; i < len; i++) { if (d->linestart) { char buf1[64]; int64_t ti; int secs; ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); if (d->timestamps_start == -1) { d->timestamps_start = ti; } ti -= d->timestamps_start; secs = ti / 1000; snprintf(buf1, sizeof(buf1), "[%02d:%02d:%02d.%03d] ", secs / 3600, (secs / 60) % 60, secs % 60, (int)(ti % 1000)); /* XXX this blocks entire thread. Rewrite to use * qemu_chr_fe_write and background I/O callbacks */ qemu_chr_fe_write_all(&d->chr, (uint8_t *)buf1, strlen(buf1)); d->linestart = 0; } ret += qemu_chr_fe_write(&d->chr, buf + i, 1); if (buf[i] == '\n') { d->linestart = 1; } } } return ret; } static const char * const mux_help[] = { "% h print this help\n\r", "% x exit emulator\n\r", "% s save disk data back to file (if -snapshot)\n\r", "% t toggle console timestamps\n\r", "% b send break (magic sysrq)\n\r", "% c switch between console and monitor\n\r", "% % sends %\n\r", NULL }; int term_escape_char = 0x01; /* ctrl-a is used for escape */ static void mux_print_help(Chardev *chr) { int i, j; char ebuf[15] = "Escape-Char"; char cbuf[50] = "\n\r"; if (term_escape_char > 0 && term_escape_char < 26) { snprintf(cbuf, sizeof(cbuf), "\n\r"); snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a'); } else { snprintf(cbuf, sizeof(cbuf), "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char); } /* XXX this blocks entire thread. Rewrite to use * qemu_chr_fe_write and background I/O callbacks */ qemu_chr_write_all(chr, (uint8_t *)cbuf, strlen(cbuf)); for (i = 0; mux_help[i] != NULL; i++) { for (j = 0; mux_help[i][j] != '\0'; j++) { if (mux_help[i][j] == '%') { qemu_chr_write_all(chr, (uint8_t *)ebuf, strlen(ebuf)); } else { qemu_chr_write_all(chr, (uint8_t *)&mux_help[i][j], 1); } } } } static void mux_chr_send_event(MuxChardev *d, int mux_nr, int event) { CharBackend *be = d->backends[mux_nr]; if (be && be->chr_event) { be->chr_event(be->opaque, event); } } static void mux_chr_be_event(Chardev *chr, int event) { MuxChardev *d = MUX_CHARDEV(chr); if (d->focus != -1) { mux_chr_send_event(d, d->focus, event); } } static int mux_proc_byte(Chardev *chr, MuxChardev *d, int ch) { if (d->term_got_escape) { d->term_got_escape = 0; if (ch == term_escape_char) { goto send_char; } switch (ch) { case '?': case 'h': mux_print_help(chr); break; case 'x': { const char *term = "QEMU: Terminated\n\r"; qemu_chr_write_all(chr, (uint8_t *)term, strlen(term)); exit(0); break; } case 's': blk_commit_all(); break; case 'b': qemu_chr_be_event(chr, CHR_EVENT_BREAK); break; case 'c': assert(d->mux_cnt > 0); /* handler registered with first fe */ /* Switch to the next registered device */ mux_set_focus(chr, (d->focus + 1) % d->mux_cnt); break; case 't': d->timestamps = !d->timestamps; d->timestamps_start = -1; d->linestart = 0; break; } } else if (ch == term_escape_char) { d->term_got_escape = 1; } else { send_char: return 1; } return 0; } static void mux_chr_accept_input(Chardev *chr) { MuxChardev *d = MUX_CHARDEV(chr); int m = d->focus; CharBackend *be = d->backends[m]; while (be && d->prod[m] != d->cons[m] && be->chr_can_read && be->chr_can_read(be->opaque)) { be->chr_read(be->opaque, &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1); } } static int mux_chr_can_read(void *opaque) { MuxChardev *d = MUX_CHARDEV(opaque); int m = d->focus; CharBackend *be = d->backends[m]; if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE) { return 1; } if (be && be->chr_can_read) { return be->chr_can_read(be->opaque); } return 0; } static void mux_chr_read(void *opaque, const uint8_t *buf, int size) { Chardev *chr = CHARDEV(opaque); MuxChardev *d = MUX_CHARDEV(opaque); int m = d->focus; CharBackend *be = d->backends[m]; int i; mux_chr_accept_input(opaque); for (i = 0; i < size; i++) if (mux_proc_byte(chr, d, buf[i])) { if (d->prod[m] == d->cons[m] && be && be->chr_can_read && be->chr_can_read(be->opaque)) { be->chr_read(be->opaque, &buf[i], 1); } else { d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i]; } } } void mux_chr_send_all_event(Chardev *chr, int event) { MuxChardev *d = MUX_CHARDEV(chr); int i; if (!machine_init_done) { return; } /* Send the event to all registered listeners */ for (i = 0; i < d->mux_cnt; i++) { mux_chr_send_event(d, i, event); } } static void mux_chr_event(void *opaque, int event) { mux_chr_send_all_event(CHARDEV(opaque), event); } static GSource *mux_chr_add_watch(Chardev *s, GIOCondition cond) { MuxChardev *d = MUX_CHARDEV(s); Chardev *chr = qemu_chr_fe_get_driver(&d->chr); ChardevClass *cc = CHARDEV_GET_CLASS(chr); if (!cc->chr_add_watch) { return NULL; } return cc->chr_add_watch(chr, cond); } static void char_mux_finalize(Object *obj) { MuxChardev *d = MUX_CHARDEV(obj); int i; for (i = 0; i < d->mux_cnt; i++) { CharBackend *be = d->backends[i]; if (be) { be->chr = NULL; } } qemu_chr_fe_deinit(&d->chr, false); } static void mux_chr_update_read_handlers(Chardev *chr) { MuxChardev *d = MUX_CHARDEV(chr); /* Fix up the real driver with mux routines */ qemu_chr_fe_set_handlers_full(&d->chr, mux_chr_can_read, mux_chr_read, mux_chr_event, NULL, chr, chr->gcontext, true, false); } void mux_set_focus(Chardev *chr, int focus) { MuxChardev *d = MUX_CHARDEV(chr); assert(focus >= 0); assert(focus < d->mux_cnt); if (d->focus != -1) { mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT); } d->focus = focus; chr->be = d->backends[focus]; mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN); } static void qemu_chr_open_mux(Chardev *chr, ChardevBackend *backend, bool *be_opened, Error **errp) { ChardevMux *mux = backend->u.mux.data; Chardev *drv; MuxChardev *d = MUX_CHARDEV(chr); drv = qemu_chr_find(mux->chardev); if (drv == NULL) { error_setg(errp, "mux: base chardev %s not found", mux->chardev); return; } d->focus = -1; /* only default to opened state if we've realized the initial * set of muxes */ *be_opened = machine_init_done; qemu_chr_fe_init(&d->chr, drv, errp); } static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend, Error **errp) { const char *chardev = qemu_opt_get(opts, "chardev"); ChardevMux *mux; if (chardev == NULL) { error_setg(errp, "chardev: mux: no chardev given"); return; } backend->type = CHARDEV_BACKEND_KIND_MUX; mux = backend->u.mux.data = g_new0(ChardevMux, 1); qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux)); mux->chardev = g_strdup(chardev); } /** * Called after processing of default and command-line-specified * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached * to a mux chardev. This is done here to ensure that * output/prompts/banners are only displayed for the FE that has * focus when initial command-line processing/machine init is * completed. * * After this point, any new FE attached to any new or existing * mux will receive CHR_EVENT_OPENED notifications for the BE * immediately. */ static int open_muxes(Chardev *chr) { /* send OPENED to all already-attached FEs */ mux_chr_send_all_event(chr, CHR_EVENT_OPENED); /* * mark mux as OPENED so any new FEs will immediately receive * OPENED event */ chr->be_open = 1; return 0; } static void char_mux_class_init(ObjectClass *oc, void *data) { ChardevClass *cc = CHARDEV_CLASS(oc); cc->parse = qemu_chr_parse_mux; cc->open = qemu_chr_open_mux; cc->chr_write = mux_chr_write; cc->chr_accept_input = mux_chr_accept_input; cc->chr_add_watch = mux_chr_add_watch; cc->chr_be_event = mux_chr_be_event; cc->chr_machine_done = open_muxes; cc->chr_update_read_handler = mux_chr_update_read_handlers; } static const TypeInfo char_mux_type_info = { .name = TYPE_CHARDEV_MUX, .parent = TYPE_CHARDEV, .class_init = char_mux_class_init, .instance_size = sizeof(MuxChardev), .instance_finalize = char_mux_finalize, }; static void register_types(void) { type_register_static(&char_mux_type_info); } type_init(register_types);
28.903226
80
0.571858
[ "object" ]
23aaf10663bbf6b586bef0f09a63fd0a3231f92c
1,007
h
C
main/includes/aabb.h
io-kats/3d-gallery
afbf8b90ad9659c18471d7505d82fff40a158ed4
[ "MIT" ]
1
2021-12-22T16:23:35.000Z
2021-12-22T16:23:35.000Z
main/includes/aabb.h
io-kats/3d-gallery
afbf8b90ad9659c18471d7505d82fff40a158ed4
[ "MIT" ]
null
null
null
main/includes/aabb.h
io-kats/3d-gallery
afbf8b90ad9659c18471d7505d82fff40a158ed4
[ "MIT" ]
null
null
null
#ifndef AABB_H #define AABB_H #include "ers/vec.h" #include "mesh.h" #include "ers/common.h" #include "transform.h" struct AABB { ers::vec3 center; ers::vec3 half_extents; AABB() = default; AABB(ers::vec3 center_, ers::vec3 half_extents_); AABB(const Mesh& m); // construct from mesh // AABB(const Model& m); // construct from model (possibly multiple meshes) // Returns the squared distance from the AABB to 'p'. // If the point is inside the AABB, the distance returned is zero. f32 SquaredDistanceToPoint(const ers::vec3& p) const; // Returns the squared distance from the AABB to 'p'. // If the point is inside the AABB, the value returned is negative. f32 SignedDistanceToPoint(const ers::vec3& p) const; // Returns the point on the AABB closest to 'p'. ers::vec3 GetClosestPoint(const ers::vec3& p) const; AABB GetUpdated(const Transform& t) const; ers::vec3 GetFurthestPoint(const ers::vec3& direction) const; Mesh* MakeMesh(); }; #endif
27.216216
77
0.694141
[ "mesh", "model", "transform" ]
23b0d304eba3aad90efe3845849bee85692186dc
55,167
h
C
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/localized_settings.pb.h
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/localized_settings.pb.h
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/localized_settings.pb.h
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/actions/sdk/v2/localized_settings.proto #ifndef PROTOBUF_INCLUDED_google_2factions_2fsdk_2fv2_2flocalized_5fsettings_2eproto #define PROTOBUF_INCLUDED_google_2factions_2fsdk_2fv2_2flocalized_5fsettings_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3007000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3007000 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> #include "google/actions/sdk/v2/theme_customization.pb.h" #include "google/api/field_behavior.pb.h" // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_google_2factions_2fsdk_2fv2_2flocalized_5fsettings_2eproto // Internal implementation detail -- do not use these members. struct TableStruct_google_2factions_2fsdk_2fv2_2flocalized_5fsettings_2eproto { static const ::google::protobuf::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::AuxillaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::ParseTable schema[1] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; void AddDescriptors_google_2factions_2fsdk_2fv2_2flocalized_5fsettings_2eproto(); namespace google { namespace actions { namespace sdk { namespace v2 { class LocalizedSettings; class LocalizedSettingsDefaultTypeInternal; extern LocalizedSettingsDefaultTypeInternal _LocalizedSettings_default_instance_; } // namespace v2 } // namespace sdk } // namespace actions namespace protobuf { template<> ::google::actions::sdk::v2::LocalizedSettings* Arena::CreateMaybeMessage<::google::actions::sdk::v2::LocalizedSettings>(Arena*); } // namespace protobuf } // namespace google namespace google { namespace actions { namespace sdk { namespace v2 { // =================================================================== class LocalizedSettings final : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.actions.sdk.v2.LocalizedSettings) */ { public: LocalizedSettings(); virtual ~LocalizedSettings(); LocalizedSettings(const LocalizedSettings& from); inline LocalizedSettings& operator=(const LocalizedSettings& from) { CopyFrom(from); return *this; } #if LANG_CXX11 LocalizedSettings(LocalizedSettings&& from) noexcept : LocalizedSettings() { *this = ::std::move(from); } inline LocalizedSettings& operator=(LocalizedSettings&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif static const ::google::protobuf::Descriptor* descriptor() { return default_instance().GetDescriptor(); } static const LocalizedSettings& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const LocalizedSettings* internal_default_instance() { return reinterpret_cast<const LocalizedSettings*>( &_LocalizedSettings_default_instance_); } static constexpr int kIndexInFileMessages = 0; void Swap(LocalizedSettings* other); friend void swap(LocalizedSettings& a, LocalizedSettings& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline LocalizedSettings* New() const final { return CreateMaybeMessage<LocalizedSettings>(nullptr); } LocalizedSettings* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<LocalizedSettings>(arena); } void CopyFrom(const ::google::protobuf::Message& from) final; void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const LocalizedSettings& from); void MergeFrom(const LocalizedSettings& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx); ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; } #else bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(LocalizedSettings* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return nullptr; } inline void* MaybeArenaPtr() const { return nullptr; } public: ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated string sample_invocations = 12 [(.google.api.field_behavior) = OPTIONAL]; int sample_invocations_size() const; void clear_sample_invocations(); static const int kSampleInvocationsFieldNumber = 12; const ::std::string& sample_invocations(int index) const; ::std::string* mutable_sample_invocations(int index); void set_sample_invocations(int index, const ::std::string& value); #if LANG_CXX11 void set_sample_invocations(int index, ::std::string&& value); #endif void set_sample_invocations(int index, const char* value); void set_sample_invocations(int index, const char* value, size_t size); ::std::string* add_sample_invocations(); void add_sample_invocations(const ::std::string& value); #if LANG_CXX11 void add_sample_invocations(::std::string&& value); #endif void add_sample_invocations(const char* value); void add_sample_invocations(const char* value, size_t size); const ::google::protobuf::RepeatedPtrField<::std::string>& sample_invocations() const; ::google::protobuf::RepeatedPtrField<::std::string>* mutable_sample_invocations(); // string display_name = 1 [(.google.api.field_behavior) = REQUIRED]; void clear_display_name(); static const int kDisplayNameFieldNumber = 1; const ::std::string& display_name() const; void set_display_name(const ::std::string& value); #if LANG_CXX11 void set_display_name(::std::string&& value); #endif void set_display_name(const char* value); void set_display_name(const char* value, size_t size); ::std::string* mutable_display_name(); ::std::string* release_display_name(); void set_allocated_display_name(::std::string* display_name); // string pronunciation = 2 [(.google.api.field_behavior) = REQUIRED]; void clear_pronunciation(); static const int kPronunciationFieldNumber = 2; const ::std::string& pronunciation() const; void set_pronunciation(const ::std::string& value); #if LANG_CXX11 void set_pronunciation(::std::string&& value); #endif void set_pronunciation(const char* value); void set_pronunciation(const char* value, size_t size); ::std::string* mutable_pronunciation(); ::std::string* release_pronunciation(); void set_allocated_pronunciation(::std::string* pronunciation); // string short_description = 3 [(.google.api.field_behavior) = REQUIRED]; void clear_short_description(); static const int kShortDescriptionFieldNumber = 3; const ::std::string& short_description() const; void set_short_description(const ::std::string& value); #if LANG_CXX11 void set_short_description(::std::string&& value); #endif void set_short_description(const char* value); void set_short_description(const char* value, size_t size); ::std::string* mutable_short_description(); ::std::string* release_short_description(); void set_allocated_short_description(::std::string* short_description); // string full_description = 4 [(.google.api.field_behavior) = REQUIRED]; void clear_full_description(); static const int kFullDescriptionFieldNumber = 4; const ::std::string& full_description() const; void set_full_description(const ::std::string& value); #if LANG_CXX11 void set_full_description(::std::string&& value); #endif void set_full_description(const char* value); void set_full_description(const char* value, size_t size); ::std::string* mutable_full_description(); ::std::string* release_full_description(); void set_allocated_full_description(::std::string* full_description); // string small_logo_image = 5 [(.google.api.field_behavior) = REQUIRED]; void clear_small_logo_image(); static const int kSmallLogoImageFieldNumber = 5; const ::std::string& small_logo_image() const; void set_small_logo_image(const ::std::string& value); #if LANG_CXX11 void set_small_logo_image(::std::string&& value); #endif void set_small_logo_image(const char* value); void set_small_logo_image(const char* value, size_t size); ::std::string* mutable_small_logo_image(); ::std::string* release_small_logo_image(); void set_allocated_small_logo_image(::std::string* small_logo_image); // string large_banner_image = 6 [(.google.api.field_behavior) = OPTIONAL]; void clear_large_banner_image(); static const int kLargeBannerImageFieldNumber = 6; const ::std::string& large_banner_image() const; void set_large_banner_image(const ::std::string& value); #if LANG_CXX11 void set_large_banner_image(::std::string&& value); #endif void set_large_banner_image(const char* value); void set_large_banner_image(const char* value, size_t size); ::std::string* mutable_large_banner_image(); ::std::string* release_large_banner_image(); void set_allocated_large_banner_image(::std::string* large_banner_image); // string developer_name = 7 [(.google.api.field_behavior) = REQUIRED]; void clear_developer_name(); static const int kDeveloperNameFieldNumber = 7; const ::std::string& developer_name() const; void set_developer_name(const ::std::string& value); #if LANG_CXX11 void set_developer_name(::std::string&& value); #endif void set_developer_name(const char* value); void set_developer_name(const char* value, size_t size); ::std::string* mutable_developer_name(); ::std::string* release_developer_name(); void set_allocated_developer_name(::std::string* developer_name); // string developer_email = 8 [(.google.api.field_behavior) = REQUIRED]; void clear_developer_email(); static const int kDeveloperEmailFieldNumber = 8; const ::std::string& developer_email() const; void set_developer_email(const ::std::string& value); #if LANG_CXX11 void set_developer_email(::std::string&& value); #endif void set_developer_email(const char* value); void set_developer_email(const char* value, size_t size); ::std::string* mutable_developer_email(); ::std::string* release_developer_email(); void set_allocated_developer_email(::std::string* developer_email); // string terms_of_service_url = 9 [(.google.api.field_behavior) = OPTIONAL]; void clear_terms_of_service_url(); static const int kTermsOfServiceUrlFieldNumber = 9; const ::std::string& terms_of_service_url() const; void set_terms_of_service_url(const ::std::string& value); #if LANG_CXX11 void set_terms_of_service_url(::std::string&& value); #endif void set_terms_of_service_url(const char* value); void set_terms_of_service_url(const char* value, size_t size); ::std::string* mutable_terms_of_service_url(); ::std::string* release_terms_of_service_url(); void set_allocated_terms_of_service_url(::std::string* terms_of_service_url); // string voice = 10 [(.google.api.field_behavior) = REQUIRED]; void clear_voice(); static const int kVoiceFieldNumber = 10; const ::std::string& voice() const; void set_voice(const ::std::string& value); #if LANG_CXX11 void set_voice(::std::string&& value); #endif void set_voice(const char* value); void set_voice(const char* value, size_t size); ::std::string* mutable_voice(); ::std::string* release_voice(); void set_allocated_voice(::std::string* voice); // string privacy_policy_url = 11 [(.google.api.field_behavior) = REQUIRED]; void clear_privacy_policy_url(); static const int kPrivacyPolicyUrlFieldNumber = 11; const ::std::string& privacy_policy_url() const; void set_privacy_policy_url(const ::std::string& value); #if LANG_CXX11 void set_privacy_policy_url(::std::string&& value); #endif void set_privacy_policy_url(const char* value); void set_privacy_policy_url(const char* value, size_t size); ::std::string* mutable_privacy_policy_url(); ::std::string* release_privacy_policy_url(); void set_allocated_privacy_policy_url(::std::string* privacy_policy_url); // string voice_locale = 14 [(.google.api.field_behavior) = OPTIONAL]; void clear_voice_locale(); static const int kVoiceLocaleFieldNumber = 14; const ::std::string& voice_locale() const; void set_voice_locale(const ::std::string& value); #if LANG_CXX11 void set_voice_locale(::std::string&& value); #endif void set_voice_locale(const char* value); void set_voice_locale(const char* value, size_t size); ::std::string* mutable_voice_locale(); ::std::string* release_voice_locale(); void set_allocated_voice_locale(::std::string* voice_locale); // .google.actions.sdk.v2.ThemeCustomization theme_customization = 13 [(.google.api.field_behavior) = OPTIONAL]; bool has_theme_customization() const; void clear_theme_customization(); static const int kThemeCustomizationFieldNumber = 13; const ::google::actions::sdk::v2::ThemeCustomization& theme_customization() const; ::google::actions::sdk::v2::ThemeCustomization* release_theme_customization(); ::google::actions::sdk::v2::ThemeCustomization* mutable_theme_customization(); void set_allocated_theme_customization(::google::actions::sdk::v2::ThemeCustomization* theme_customization); // @@protoc_insertion_point(class_scope:google.actions.sdk.v2.LocalizedSettings) private: class HasBitSetters; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField<::std::string> sample_invocations_; ::google::protobuf::internal::ArenaStringPtr display_name_; ::google::protobuf::internal::ArenaStringPtr pronunciation_; ::google::protobuf::internal::ArenaStringPtr short_description_; ::google::protobuf::internal::ArenaStringPtr full_description_; ::google::protobuf::internal::ArenaStringPtr small_logo_image_; ::google::protobuf::internal::ArenaStringPtr large_banner_image_; ::google::protobuf::internal::ArenaStringPtr developer_name_; ::google::protobuf::internal::ArenaStringPtr developer_email_; ::google::protobuf::internal::ArenaStringPtr terms_of_service_url_; ::google::protobuf::internal::ArenaStringPtr voice_; ::google::protobuf::internal::ArenaStringPtr privacy_policy_url_; ::google::protobuf::internal::ArenaStringPtr voice_locale_; ::google::actions::sdk::v2::ThemeCustomization* theme_customization_; mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2factions_2fsdk_2fv2_2flocalized_5fsettings_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // LocalizedSettings // string display_name = 1 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_display_name() { display_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::display_name() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.display_name) return display_name_.GetNoArena(); } inline void LocalizedSettings::set_display_name(const ::std::string& value) { display_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.display_name) } #if LANG_CXX11 inline void LocalizedSettings::set_display_name(::std::string&& value) { display_name_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.display_name) } #endif inline void LocalizedSettings::set_display_name(const char* value) { GOOGLE_DCHECK(value != nullptr); display_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.display_name) } inline void LocalizedSettings::set_display_name(const char* value, size_t size) { display_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.display_name) } inline ::std::string* LocalizedSettings::mutable_display_name() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.display_name) return display_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_display_name() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.display_name) return display_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_display_name(::std::string* display_name) { if (display_name != nullptr) { } else { } display_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), display_name); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.display_name) } // string pronunciation = 2 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_pronunciation() { pronunciation_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::pronunciation() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.pronunciation) return pronunciation_.GetNoArena(); } inline void LocalizedSettings::set_pronunciation(const ::std::string& value) { pronunciation_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.pronunciation) } #if LANG_CXX11 inline void LocalizedSettings::set_pronunciation(::std::string&& value) { pronunciation_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.pronunciation) } #endif inline void LocalizedSettings::set_pronunciation(const char* value) { GOOGLE_DCHECK(value != nullptr); pronunciation_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.pronunciation) } inline void LocalizedSettings::set_pronunciation(const char* value, size_t size) { pronunciation_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.pronunciation) } inline ::std::string* LocalizedSettings::mutable_pronunciation() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.pronunciation) return pronunciation_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_pronunciation() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.pronunciation) return pronunciation_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_pronunciation(::std::string* pronunciation) { if (pronunciation != nullptr) { } else { } pronunciation_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), pronunciation); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.pronunciation) } // string short_description = 3 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_short_description() { short_description_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::short_description() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.short_description) return short_description_.GetNoArena(); } inline void LocalizedSettings::set_short_description(const ::std::string& value) { short_description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.short_description) } #if LANG_CXX11 inline void LocalizedSettings::set_short_description(::std::string&& value) { short_description_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.short_description) } #endif inline void LocalizedSettings::set_short_description(const char* value) { GOOGLE_DCHECK(value != nullptr); short_description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.short_description) } inline void LocalizedSettings::set_short_description(const char* value, size_t size) { short_description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.short_description) } inline ::std::string* LocalizedSettings::mutable_short_description() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.short_description) return short_description_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_short_description() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.short_description) return short_description_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_short_description(::std::string* short_description) { if (short_description != nullptr) { } else { } short_description_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), short_description); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.short_description) } // string full_description = 4 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_full_description() { full_description_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::full_description() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.full_description) return full_description_.GetNoArena(); } inline void LocalizedSettings::set_full_description(const ::std::string& value) { full_description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.full_description) } #if LANG_CXX11 inline void LocalizedSettings::set_full_description(::std::string&& value) { full_description_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.full_description) } #endif inline void LocalizedSettings::set_full_description(const char* value) { GOOGLE_DCHECK(value != nullptr); full_description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.full_description) } inline void LocalizedSettings::set_full_description(const char* value, size_t size) { full_description_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.full_description) } inline ::std::string* LocalizedSettings::mutable_full_description() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.full_description) return full_description_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_full_description() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.full_description) return full_description_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_full_description(::std::string* full_description) { if (full_description != nullptr) { } else { } full_description_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), full_description); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.full_description) } // string small_logo_image = 5 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_small_logo_image() { small_logo_image_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::small_logo_image() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.small_logo_image) return small_logo_image_.GetNoArena(); } inline void LocalizedSettings::set_small_logo_image(const ::std::string& value) { small_logo_image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.small_logo_image) } #if LANG_CXX11 inline void LocalizedSettings::set_small_logo_image(::std::string&& value) { small_logo_image_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.small_logo_image) } #endif inline void LocalizedSettings::set_small_logo_image(const char* value) { GOOGLE_DCHECK(value != nullptr); small_logo_image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.small_logo_image) } inline void LocalizedSettings::set_small_logo_image(const char* value, size_t size) { small_logo_image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.small_logo_image) } inline ::std::string* LocalizedSettings::mutable_small_logo_image() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.small_logo_image) return small_logo_image_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_small_logo_image() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.small_logo_image) return small_logo_image_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_small_logo_image(::std::string* small_logo_image) { if (small_logo_image != nullptr) { } else { } small_logo_image_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), small_logo_image); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.small_logo_image) } // string large_banner_image = 6 [(.google.api.field_behavior) = OPTIONAL]; inline void LocalizedSettings::clear_large_banner_image() { large_banner_image_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::large_banner_image() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.large_banner_image) return large_banner_image_.GetNoArena(); } inline void LocalizedSettings::set_large_banner_image(const ::std::string& value) { large_banner_image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.large_banner_image) } #if LANG_CXX11 inline void LocalizedSettings::set_large_banner_image(::std::string&& value) { large_banner_image_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.large_banner_image) } #endif inline void LocalizedSettings::set_large_banner_image(const char* value) { GOOGLE_DCHECK(value != nullptr); large_banner_image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.large_banner_image) } inline void LocalizedSettings::set_large_banner_image(const char* value, size_t size) { large_banner_image_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.large_banner_image) } inline ::std::string* LocalizedSettings::mutable_large_banner_image() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.large_banner_image) return large_banner_image_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_large_banner_image() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.large_banner_image) return large_banner_image_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_large_banner_image(::std::string* large_banner_image) { if (large_banner_image != nullptr) { } else { } large_banner_image_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), large_banner_image); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.large_banner_image) } // string developer_name = 7 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_developer_name() { developer_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::developer_name() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.developer_name) return developer_name_.GetNoArena(); } inline void LocalizedSettings::set_developer_name(const ::std::string& value) { developer_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.developer_name) } #if LANG_CXX11 inline void LocalizedSettings::set_developer_name(::std::string&& value) { developer_name_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.developer_name) } #endif inline void LocalizedSettings::set_developer_name(const char* value) { GOOGLE_DCHECK(value != nullptr); developer_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.developer_name) } inline void LocalizedSettings::set_developer_name(const char* value, size_t size) { developer_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.developer_name) } inline ::std::string* LocalizedSettings::mutable_developer_name() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.developer_name) return developer_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_developer_name() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.developer_name) return developer_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_developer_name(::std::string* developer_name) { if (developer_name != nullptr) { } else { } developer_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), developer_name); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.developer_name) } // string developer_email = 8 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_developer_email() { developer_email_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::developer_email() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.developer_email) return developer_email_.GetNoArena(); } inline void LocalizedSettings::set_developer_email(const ::std::string& value) { developer_email_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.developer_email) } #if LANG_CXX11 inline void LocalizedSettings::set_developer_email(::std::string&& value) { developer_email_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.developer_email) } #endif inline void LocalizedSettings::set_developer_email(const char* value) { GOOGLE_DCHECK(value != nullptr); developer_email_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.developer_email) } inline void LocalizedSettings::set_developer_email(const char* value, size_t size) { developer_email_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.developer_email) } inline ::std::string* LocalizedSettings::mutable_developer_email() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.developer_email) return developer_email_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_developer_email() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.developer_email) return developer_email_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_developer_email(::std::string* developer_email) { if (developer_email != nullptr) { } else { } developer_email_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), developer_email); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.developer_email) } // string terms_of_service_url = 9 [(.google.api.field_behavior) = OPTIONAL]; inline void LocalizedSettings::clear_terms_of_service_url() { terms_of_service_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::terms_of_service_url() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) return terms_of_service_url_.GetNoArena(); } inline void LocalizedSettings::set_terms_of_service_url(const ::std::string& value) { terms_of_service_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) } #if LANG_CXX11 inline void LocalizedSettings::set_terms_of_service_url(::std::string&& value) { terms_of_service_url_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) } #endif inline void LocalizedSettings::set_terms_of_service_url(const char* value) { GOOGLE_DCHECK(value != nullptr); terms_of_service_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) } inline void LocalizedSettings::set_terms_of_service_url(const char* value, size_t size) { terms_of_service_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) } inline ::std::string* LocalizedSettings::mutable_terms_of_service_url() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) return terms_of_service_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_terms_of_service_url() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) return terms_of_service_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_terms_of_service_url(::std::string* terms_of_service_url) { if (terms_of_service_url != nullptr) { } else { } terms_of_service_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), terms_of_service_url); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.terms_of_service_url) } // string voice = 10 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_voice() { voice_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::voice() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.voice) return voice_.GetNoArena(); } inline void LocalizedSettings::set_voice(const ::std::string& value) { voice_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.voice) } #if LANG_CXX11 inline void LocalizedSettings::set_voice(::std::string&& value) { voice_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.voice) } #endif inline void LocalizedSettings::set_voice(const char* value) { GOOGLE_DCHECK(value != nullptr); voice_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.voice) } inline void LocalizedSettings::set_voice(const char* value, size_t size) { voice_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.voice) } inline ::std::string* LocalizedSettings::mutable_voice() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.voice) return voice_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_voice() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.voice) return voice_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_voice(::std::string* voice) { if (voice != nullptr) { } else { } voice_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), voice); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.voice) } // string voice_locale = 14 [(.google.api.field_behavior) = OPTIONAL]; inline void LocalizedSettings::clear_voice_locale() { voice_locale_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::voice_locale() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.voice_locale) return voice_locale_.GetNoArena(); } inline void LocalizedSettings::set_voice_locale(const ::std::string& value) { voice_locale_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.voice_locale) } #if LANG_CXX11 inline void LocalizedSettings::set_voice_locale(::std::string&& value) { voice_locale_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.voice_locale) } #endif inline void LocalizedSettings::set_voice_locale(const char* value) { GOOGLE_DCHECK(value != nullptr); voice_locale_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.voice_locale) } inline void LocalizedSettings::set_voice_locale(const char* value, size_t size) { voice_locale_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.voice_locale) } inline ::std::string* LocalizedSettings::mutable_voice_locale() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.voice_locale) return voice_locale_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_voice_locale() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.voice_locale) return voice_locale_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_voice_locale(::std::string* voice_locale) { if (voice_locale != nullptr) { } else { } voice_locale_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), voice_locale); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.voice_locale) } // string privacy_policy_url = 11 [(.google.api.field_behavior) = REQUIRED]; inline void LocalizedSettings::clear_privacy_policy_url() { privacy_policy_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& LocalizedSettings::privacy_policy_url() const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) return privacy_policy_url_.GetNoArena(); } inline void LocalizedSettings::set_privacy_policy_url(const ::std::string& value) { privacy_policy_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) } #if LANG_CXX11 inline void LocalizedSettings::set_privacy_policy_url(::std::string&& value) { privacy_policy_url_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) } #endif inline void LocalizedSettings::set_privacy_policy_url(const char* value) { GOOGLE_DCHECK(value != nullptr); privacy_policy_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) } inline void LocalizedSettings::set_privacy_policy_url(const char* value, size_t size) { privacy_policy_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) } inline ::std::string* LocalizedSettings::mutable_privacy_policy_url() { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) return privacy_policy_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* LocalizedSettings::release_privacy_policy_url() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) return privacy_policy_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void LocalizedSettings::set_allocated_privacy_policy_url(::std::string* privacy_policy_url) { if (privacy_policy_url != nullptr) { } else { } privacy_policy_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), privacy_policy_url); // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.privacy_policy_url) } // repeated string sample_invocations = 12 [(.google.api.field_behavior) = OPTIONAL]; inline int LocalizedSettings::sample_invocations_size() const { return sample_invocations_.size(); } inline void LocalizedSettings::clear_sample_invocations() { sample_invocations_.Clear(); } inline const ::std::string& LocalizedSettings::sample_invocations(int index) const { // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.sample_invocations) return sample_invocations_.Get(index); } inline ::std::string* LocalizedSettings::mutable_sample_invocations(int index) { // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.sample_invocations) return sample_invocations_.Mutable(index); } inline void LocalizedSettings::set_sample_invocations(int index, const ::std::string& value) { // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.sample_invocations) sample_invocations_.Mutable(index)->assign(value); } #if LANG_CXX11 inline void LocalizedSettings::set_sample_invocations(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:google.actions.sdk.v2.LocalizedSettings.sample_invocations) sample_invocations_.Mutable(index)->assign(std::move(value)); } #endif inline void LocalizedSettings::set_sample_invocations(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); sample_invocations_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.actions.sdk.v2.LocalizedSettings.sample_invocations) } inline void LocalizedSettings::set_sample_invocations(int index, const char* value, size_t size) { sample_invocations_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.actions.sdk.v2.LocalizedSettings.sample_invocations) } inline ::std::string* LocalizedSettings::add_sample_invocations() { // @@protoc_insertion_point(field_add_mutable:google.actions.sdk.v2.LocalizedSettings.sample_invocations) return sample_invocations_.Add(); } inline void LocalizedSettings::add_sample_invocations(const ::std::string& value) { sample_invocations_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.actions.sdk.v2.LocalizedSettings.sample_invocations) } #if LANG_CXX11 inline void LocalizedSettings::add_sample_invocations(::std::string&& value) { sample_invocations_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.actions.sdk.v2.LocalizedSettings.sample_invocations) } #endif inline void LocalizedSettings::add_sample_invocations(const char* value) { GOOGLE_DCHECK(value != nullptr); sample_invocations_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.actions.sdk.v2.LocalizedSettings.sample_invocations) } inline void LocalizedSettings::add_sample_invocations(const char* value, size_t size) { sample_invocations_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.actions.sdk.v2.LocalizedSettings.sample_invocations) } inline const ::google::protobuf::RepeatedPtrField<::std::string>& LocalizedSettings::sample_invocations() const { // @@protoc_insertion_point(field_list:google.actions.sdk.v2.LocalizedSettings.sample_invocations) return sample_invocations_; } inline ::google::protobuf::RepeatedPtrField<::std::string>* LocalizedSettings::mutable_sample_invocations() { // @@protoc_insertion_point(field_mutable_list:google.actions.sdk.v2.LocalizedSettings.sample_invocations) return &sample_invocations_; } // .google.actions.sdk.v2.ThemeCustomization theme_customization = 13 [(.google.api.field_behavior) = OPTIONAL]; inline bool LocalizedSettings::has_theme_customization() const { return this != internal_default_instance() && theme_customization_ != nullptr; } inline const ::google::actions::sdk::v2::ThemeCustomization& LocalizedSettings::theme_customization() const { const ::google::actions::sdk::v2::ThemeCustomization* p = theme_customization_; // @@protoc_insertion_point(field_get:google.actions.sdk.v2.LocalizedSettings.theme_customization) return p != nullptr ? *p : *reinterpret_cast<const ::google::actions::sdk::v2::ThemeCustomization*>( &::google::actions::sdk::v2::_ThemeCustomization_default_instance_); } inline ::google::actions::sdk::v2::ThemeCustomization* LocalizedSettings::release_theme_customization() { // @@protoc_insertion_point(field_release:google.actions.sdk.v2.LocalizedSettings.theme_customization) ::google::actions::sdk::v2::ThemeCustomization* temp = theme_customization_; theme_customization_ = nullptr; return temp; } inline ::google::actions::sdk::v2::ThemeCustomization* LocalizedSettings::mutable_theme_customization() { if (theme_customization_ == nullptr) { auto* p = CreateMaybeMessage<::google::actions::sdk::v2::ThemeCustomization>(GetArenaNoVirtual()); theme_customization_ = p; } // @@protoc_insertion_point(field_mutable:google.actions.sdk.v2.LocalizedSettings.theme_customization) return theme_customization_; } inline void LocalizedSettings::set_allocated_theme_customization(::google::actions::sdk::v2::ThemeCustomization* theme_customization) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); if (message_arena == nullptr) { delete reinterpret_cast< ::google::protobuf::MessageLite*>(theme_customization_); } if (theme_customization) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { theme_customization = ::google::protobuf::internal::GetOwnedMessage( message_arena, theme_customization, submessage_arena); } } else { } theme_customization_ = theme_customization; // @@protoc_insertion_point(field_set_allocated:google.actions.sdk.v2.LocalizedSettings.theme_customization) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace v2 } // namespace sdk } // namespace actions } // namespace google // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // PROTOBUF_INCLUDED_google_2factions_2fsdk_2fv2_2flocalized_5fsettings_2eproto
47.313036
139
0.776678
[ "object" ]
23be3da4039a4db3f74eec8e2910477a6c577506
6,587
c
C
router/rtrFdback.c
wisehackermonkey/magic
fb85e97b9233cff352d964823173c18527c714aa
[ "TCL", "X11", "MIT" ]
null
null
null
router/rtrFdback.c
wisehackermonkey/magic
fb85e97b9233cff352d964823173c18527c714aa
[ "TCL", "X11", "MIT" ]
null
null
null
router/rtrFdback.c
wisehackermonkey/magic
fb85e97b9233cff352d964823173c18527c714aa
[ "TCL", "X11", "MIT" ]
null
null
null
/* rtrFeedback.c - * * Code to manage feedback from the channel router. If there are * errors during channel routing, the router reroutes in a different * direction to try to reduce the number of errors. It has to save * feedback from these attempts until it knows which version of the * routing is the real one, whose errors should appear in the layout. * * ********************************************************************* * * Copyright (C) 1985, 1990 Regents of the University of California. * * * Permission to use, copy, modify, and distribute this * * * software and its documentation for any purpose and without * * * fee is hereby granted, provided that the above copyright * * * notice appear in all copies. The University of California * * * makes no representations about the suitability of this * * * software for any purpose. It is provided "as is" without * * * express or implied warranty. Export of this software outside * * * of the United States of America may require an export license. * * ********************************************************************* */ #ifndef lint static char rcsid[] __attribute__ ((unused)) = "$Header: /usr/cvsroot/magic-8.0/router/rtrFdback.c,v 1.1.1.1 2008/02/03 20:43:50 tim Exp $"; #endif /* not lint */ #include <stdio.h> #include <string.h> #include "utils/magic.h" #include "utils/geometry.h" #include "utils/styles.h" #include "tiles/tile.h" #include "utils/hash.h" #include "database/database.h" #include "windows/windows.h" #include "utils/main.h" #include "utils/utils.h" #include "gcr/gcr.h" #include "router/router.h" #include "utils/heap.h" #include "grouter/grouter.h" #include "utils/netlist.h" #include "textio/textio.h" #include "dbwind/dbwind.h" #include "utils/malloc.h" /* This module maintains two linked lists of feedback information, one for * each of the possible attempts at channel routing. The information consists * of a box covering the area to be marked with feedback, and the text of * a feedback message associated with the area. */ typedef struct rtrFb { Rect rtr_R; /* Box for feedback paint */ char * rtr_c; /* Text for feedback */ struct rtrFb * rtr_Fnext; /* Link to next feedback */ } RtrFB; RtrFB * rtrFList[] = {(RtrFB *) NULL, (RtrFB *) NULL}; /* Lists of feedback */ int rtrFNum; /* Says which list is active */ /* * ---------------------------------------------------------------------------- * * RtrChannelError -- * * This utility procedure is provided for use by the channel router * (which isn't supposed to know anything about the rest of Magic). * This procedure just enters a feedback area to describe an error * that occurred at a particular location in a channel. * * Results: * None. * * Side effects: * A new feedback area is created. * Remembers this channel in the table of channels to be dumped * at the end of routing (for debugging the channel router). * * ---------------------------------------------------------------------------- */ void RtrChannelError(ch, col, track, msg, net) GCRChannel *ch; /* Channel where error occurred. */ int col; /* Column where error occurred. */ int track; /* Track where error occurred. */ char *msg; /* Message identifying error. */ NLNet *net; /* Net where error occurred */ { Rect box; Point old, new; char buff[2048]; char * netname; if (net) { netname = NLNetName(net); if ((strlen(netname) + strlen(msg)) >= 2048) netname = "too long"; (void) sprintf(buff, "Net `%s', channel %p: ", netname, ch); } else { (void) sprintf(buff, "channel %p: ", ch); } (void) strcat(buff, msg); old.p_x = col; old.p_y = track; GeoTransPoint(&ch->gcr_transform, &old, &new); box.r_xbot = ch->gcr_origin.p_x + (new.p_x * RtrGridSpacing) - 2; box.r_xtop = box.r_xbot + 4; box.r_ybot = ch->gcr_origin.p_y + (new.p_y * RtrGridSpacing) - 2; box.r_ytop = box.r_ybot + 4; (void) rtrFBAdd(&box, buff); } /* * ---------------------------------------------------------------------------- * * rtrFBClear -- * * Initialization for the module, on each channel invocation. * * Results: * None. * * Side effects: * Frees memory and initializes list pointers to NULL. * * ---------------------------------------------------------------------------- */ void rtrFBClear() { RtrFB * temp; for(temp=rtrFList[0]; temp!=(RtrFB *) NULL; rtrFList[0]=temp) { temp=temp->rtr_Fnext; freeMagic(rtrFList[0]->rtr_c); freeMagic((char *) rtrFList[0]); } for(temp=rtrFList[1]; temp!=(RtrFB *) NULL; rtrFList[1]=temp) { temp=temp->rtr_Fnext; freeMagic(rtrFList[1]->rtr_c); freeMagic((char *) rtrFList[1]); } rtrFNum=0; } /* * ---------------------------------------------------------------------------- * * rtrFBAdd -- * * Save the information needed to generate a feedback rectangle. * * Results: * None. * * Side effects: * Memory is allocated. Global variables get changed. * * ---------------------------------------------------------------------------- */ void rtrFBAdd(r, t) Rect * r; char * t; { RtrFB * new; new=(RtrFB *) mallocMagic((unsigned) sizeof(RtrFB)); ASSERT(new!=(RtrFB *) NULL, "Malloc failed in rtrFBSave"); new->rtr_R= *r; new->rtr_c=StrDup((char **) NULL, t); new->rtr_Fnext=rtrFList[rtrFNum]; rtrFList[rtrFNum]=new; } /* * ---------------------------------------------------------------------------- * * RtrFBPaint -- * * Paint the information from the selected list into the given design. * * Results: * None. * * Side effects: * None. * * ---------------------------------------------------------------------------- */ void RtrFBPaint(num) int num; /* Selects which list to use */ { RtrFB *temp; for (temp = rtrFList[num]; temp; temp = temp->rtr_Fnext) DBWFeedbackAdd(&temp->rtr_R, temp->rtr_c, EditCellUse->cu_def, 1, STYLE_PALEHIGHLIGHTS); rtrFBClear(); } /* * ---------------------------------------------------------------------------- * * RtrFBSwitch -- * * Switch from list 0 to list 1 to record feedback patches. * * Results: * None. * * Side effects: * Changes this module's global keeping track of which list. * * ---------------------------------------------------------------------------- */ void RtrFBSwitch() { ASSERT(rtrFNum==0, "RtrFBSwitch"); rtrFNum=1; }
27.793249
140
0.551693
[ "geometry" ]
23c386e4327cf7f2b38c859fc5fa7260fcb7a6a2
3,698
h
C
src/internals/Crc.h
nuket/ArduinoShell
a61b2087431a025008c7858b9a69ee5d1c215842
[ "Unlicense", "MIT" ]
21
2016-11-06T17:54:22.000Z
2022-03-24T02:47:32.000Z
src/internals/Crc.h
nuket/ArduinoShell
a61b2087431a025008c7858b9a69ee5d1c215842
[ "Unlicense", "MIT" ]
4
2016-01-10T23:57:08.000Z
2020-08-02T20:08:09.000Z
src/internals/Crc.h
nuket/ArduinoShell
a61b2087431a025008c7858b9a69ee5d1c215842
[ "Unlicense", "MIT" ]
2
2019-01-29T05:11:06.000Z
2020-03-18T11:46:41.000Z
/* Arduino Shell Copyright (c) 2015 Max Vilimpoc 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. */ /** * \file Crc.h * Functions and types for CRC checks. * * Generated on Wed Oct 28 00:22:37 2015, * by pycrc v0.8.3, https://pycrc.org * using the configuration: * Width = 16 * Poly = 0x8005 * XorIn = 0x0000 * ReflectIn = True * XorOut = 0x0000 * ReflectOut = True * Algorithm = bit-by-bit-fast * * python pycrc.py --model=crc-16 --algorithm=bit-by-bit-fast --generate=h -o Crc.h *****************************************************************************/ #ifndef __CRC_H__ #define __CRC_H__ #include <stdlib.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /** * The definition of the used algorithm. * * This is not used anywhere in the generated code, but it may be used by the * application code to call algoritm-specific code, is desired. *****************************************************************************/ #define CRC_ALGO_BIT_BY_BIT_FAST 1 /** * The type of the CRC values. * * This type must be big enough to contain at least 16 bits. *****************************************************************************/ typedef uint_fast16_t crc_t; /** * Reflect all bits of a \a data word of \a data_len bytes. * * \param data The data word to be reflected. * \param data_len The width of \a data expressed in number of bits. * \return The reflected data. *****************************************************************************/ crc_t crc_reflect(crc_t data, size_t data_len); /** * Calculate the initial crc value. * * \return The initial crc value. *****************************************************************************/ static inline crc_t crc_init(void) { return 0x0000; } /** * Update the crc value with new data. * * \param crc The current crc value. * \param data Pointer to a buffer of \a data_len bytes. * \param data_len Number of bytes in the \a data buffer. * \return The updated crc value. *****************************************************************************/ crc_t crc_update(crc_t crc, const void *data, size_t data_len); /** * Calculate the final crc value. * * \param crc The current crc value. * \return The final crc value. *****************************************************************************/ static inline crc_t crc_finalize(crc_t crc) { return crc_reflect(crc, 16) ^ 0x0000; } #ifdef __cplusplus } /* closing brace for extern "C" */ #endif #endif /* __CRC_H__ */
31.338983
83
0.581936
[ "model" ]
23ce927df73fdd392380b96739378979f117560b
10,653
h
C
src/toyui/Style/Style.h
mewbak/kiui
8aa65434ba4f6ebe1fbdc41f88f6f59a201ae850
[ "Zlib" ]
552
2015-02-27T20:23:07.000Z
2015-10-05T04:40:21.000Z
src/toyui/Style/Style.h
mewbak/kiui
8aa65434ba4f6ebe1fbdc41f88f6f59a201ae850
[ "Zlib" ]
30
2015-03-31T11:40:43.000Z
2015-08-26T14:44:50.000Z
src/toyui/Style/Style.h
mewbak/kiui
8aa65434ba4f6ebe1fbdc41f88f6f59a201ae850
[ "Zlib" ]
63
2015-10-30T05:05:08.000Z
2020-10-15T05:04:28.000Z
// Copyright (c) 2016 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifndef TOY_STYLE_H #define TOY_STYLE_H /* toy */ #include <toyobj/Object.h> #include <toyobj/Indexer.h> #include <toyobj/Arg.h> #include <toyobj/Util/Colour.h> #include <toyobj/Util/NonCopy.h> #include <toyui/Types.h> #include <toyui/Frame/Dim.h> #include <toyui/Style/ImageSkin.h> /* std */ #include <vector> namespace toy { struct WidgetStates { int value = 0; int& operator()() { return value; } }; using CustomRenderer = std::function<bool (const Frame&, Renderer&)>; class _refl_ TOY_UI_EXPORT Shadow : public Struct { public: _constr_ Shadow(float xpos, float ypos, float blur, float spread, Colour colour = Colour::AlphaBlack) : d_xpos(xpos), d_ypos(ypos), d_blur(blur), d_spread(spread), d_colour(colour), d_null(false), d_radius(spread + blur) {} _constr_ Shadow() : d_null(true) {} _attr_ _mut_ float d_xpos; _attr_ _mut_ float d_ypos; _attr_ _mut_ float d_blur; _attr_ _mut_ float d_spread; _attr_ _mut_ Colour d_colour; bool d_null; float d_radius; }; class _refl_ TOY_UI_EXPORT Paint : public Struct { public: Paint() : Struct() {} Paint(const Colour& colour) : Struct(), m_colour(colour) {} Paint(const Colour& first, const Colour& second) : Struct(), m_colour(), m_gradient{ first, second } {} bool m_empty; float m_width; Colour m_colour; std::vector<Colour> m_gradient; Image* m_image; }; class TOY_UI_EXPORT Options { public: std::vector<Var> m_fields; void set(size_t index, Var value) { if(index >= m_fields.size()) m_fields.resize(index+1); m_fields[index] = value; } void merge(const Options& other) { for(size_t i = 0; i < other.m_fields.size(); ++i) if(!other.m_fields[i].none()) set(i, other.m_fields[i]); } }; class _refl_ TOY_UI_EXPORT Layout : public Struct { public: _constr_ Layout(const string& name = "") : m_name(name), m_solver(FRAME_SOLVER), m_layout(Dim<AutoLayout>(AUTO_LAYOUT, AUTO_LAYOUT)), m_flow(FLOW), m_space(Space::preset(SHEET)) , m_clipping(NOCLIP), m_opacity(CLEAR), m_align(Dim<Align>(LEFT, LEFT)) , m_span(DimFloat(1.f, 1.f)), m_pivot(Dim<Pivot>(FORWARD, FORWARD)), m_zorder(0), m_updated(0) {} _attr_ _mut_ string m_name; _attr_ _mut_ LayoutSolver m_solver; _attr_ _mut_ Dim<AutoLayout> m_layout; _attr_ _mut_ Flow m_flow; _attr_ _mut_ Space m_space; _attr_ _mut_ Clipping m_clipping; _attr_ _mut_ Opacity m_opacity; _attr_ _mut_ Dim<Align> m_align; _attr_ _mut_ DimFloat m_span; _attr_ _mut_ DimFloat m_size; _attr_ _mut_ BoxFloat m_padding; _attr_ _mut_ DimFloat m_margin; _attr_ _mut_ DimFloat m_spacing; _attr_ _mut_ Dim<Pivot> m_pivot; _attr_ _mut_ int m_zorder; _attr_ _mut_ size_t m_updated; }; class _refl_ TOY_UI_EXPORT InkStyle : public Struct { public: _constr_ InkStyle(const string& name = "") : m_name(name), m_empty(true), m_background_colour(Colour::None), m_border_colour(Colour::None), m_image_colour(Colour::None), m_text_colour(Colour::None) , m_text_font("dejavu"), m_text_size(14.f), m_text_break(true), m_text_wrap(false) , m_border_width(0.f), m_corner_radius(), m_weak_corners(false), m_padding(0.f), m_margin(0.f) , m_align(Dim<Align>(LEFT, LEFT)), m_linear_gradient(DimFloat(0.f, 0.f)), m_linear_gradient_dim(DIM_Y) , m_image(nullptr), m_overlay(nullptr), m_tile(nullptr), m_hover_cursor(nullptr) {} void prepare() { if(!m_background_colour.null() || !m_text_colour.null() || !m_border_colour.null() || m_image || !m_image_skin.null() || m_customRenderer) m_empty = false; } _attr_ _mut_ string m_name; _attr_ _mut_ bool m_empty; _attr_ _mut_ Colour m_background_colour; _attr_ _mut_ Colour m_border_colour; _attr_ _mut_ Colour m_image_colour; _attr_ _mut_ Colour m_text_colour; _attr_ _mut_ string m_text_font; _attr_ _mut_ float m_text_size; _attr_ _mut_ bool m_text_break; _attr_ _mut_ bool m_text_wrap; _attr_ _mut_ BoxFloat m_border_width; _attr_ _mut_ BoxFloat m_corner_radius; _attr_ _mut_ bool m_weak_corners; _attr_ _mut_ BoxFloat m_padding; _attr_ _mut_ BoxFloat m_margin; _attr_ _mut_ Dim<Align> m_align; _attr_ _mut_ DimFloat m_linear_gradient; _attr_ _mut_ Dimension m_linear_gradient_dim; _attr_ _mut_ Image* m_image; _attr_ _mut_ Image* m_overlay; _attr_ _mut_ Image* m_tile; _attr_ _mut_ ImageSkin m_image_skin; _attr_ _mut_ Shadow m_shadow; _attr_ _mut_ Colour m_shadow_colour; _attr_ _mut_ Style* m_hover_cursor; /*_attr_*/ CustomRenderer m_customRenderer; WidgetState m_state; }; using StyleMap = std::map<string, Options>; class _refl_ TOY_UI_EXPORT Style : public Struct { public: Style(const string& name, Type* type, Style* base, Args args); Style() : Style("", nullptr, nullptr, {}) {} Style(const string& name, Style& base, Args args = {}) : Style(name, nullptr, &base, args) {} Style(Type& type, Style& base, Args args = {}) : Style(type.m_name, &type, &base, args) {} void init(); void load(StyleMap& layout_defs, StyleMap& skin_defs); void define(Style& level, StyleMap& layout_defs, StyleMap& skin_defs); InkStyle& skin(WidgetState state); InkStyle& decline_skin(WidgetStates state); public: _attr_ Type* m_style_type; _attr_ Style* m_base; _attr_ string m_name; _attr_ Layout m_layout; _attr_ InkStyle m_skin; std::vector<InkStyle> m_skins; Args m_args; bool m_defined; }; struct TOY_UI_EXPORT Styles { Styles(); void setup(UiWindow& window); Style widget = { "Widget", &cls<Widget>(), nullptr, Args{ { &Layout::m_solver, FRAME_SOLVER } } }; Style wedge = { cls<Wedge>(), widget, Args{ { &Layout::m_solver, ROW_SOLVER }, { &Layout::m_space, SHEET } } }; Style root_sheet = { cls<RootSheet>(), wedge, Args{ { &Layout::m_space, LAYOUT }, { &Layout::m_clipping, CLIP }, { &Layout::m_opacity, OPAQUE } } }; Style item = { "Item", widget, Args{ { &Layout::m_space, BLOCK }, { &Layout::m_align, Dim<Align>{ LEFT, CENTER } }, { &InkStyle::m_text_colour, Colour::White }, { &InkStyle::m_padding, BoxFloat(2.f) } } }; Style control = { "Control", item, Args{ { &Layout::m_opacity, OPAQUE } } }; Style spacer = { "Spacer", item, Args{ { &Layout::m_space, SPACER } } }; Style filler = { "Filler", spacer, Args{ { &Layout::m_space, FLEX } } }; Style div = { "Div", wedge, Args{ { &Layout::m_space, DIV } } }; Style row = { "Row", wedge, Args{ { &Layout::m_space, LINE } } }; Style stack = { "Stack", wedge, Args{ { &Layout::m_space, STACK } } }; Style sheet = { "Sheet", wedge, Args{ { &Layout::m_space, SHEET } } }; Style list = { "List", wedge }; Style header = { "Header", row }; Style board = { "Board", wedge, Args{ { &Layout::m_space, BOARD }, { &Layout::m_clipping, CLIP } } }; Style layout = { "Layout", board, Args{ { &Layout::m_space, LAYOUT } } }; Style screen = { "Screen", wedge, Args{ { &Layout::m_flow, FREE }, { &Layout::m_space, LAYOUT } } }; Style decal = { "Decal", wedge, Args{ { &Layout::m_flow, FREE }, { &Layout::m_space, BLOCK } } }; Style overlay = { "Overlay", wedge, Args{ { &Layout::m_flow, FREE }, { &Layout::m_space, UNIT }, { &Layout::m_opacity, OPAQUE } } }; Style gridsheet = { cls<GridSheet>(), wedge, Args{ { &Layout::m_opacity, OPAQUE }, { &Layout::m_spacing, DimFloat(5.f) } } }; Style wrap_control = { "WrapControl", wedge, Args{ { &Layout::m_space, LINE }, { &Layout::m_opacity, OPAQUE } } }; Style label = { cls<Label>(), item, Args{ { &Layout::m_align, Dim<Align>{ LEFT, CENTER } } } }; Style title = { "Title", item }; Style text = { "Text", item, Args{ { &Layout::m_space, Space{ PARAGRAPH, FIXED, WRAP } }, { &InkStyle::m_text_wrap, true } } }; Style button = { cls<Button>(), control }; Style wrap_button = { cls<WrapButton>(), wrap_control }; Style multi_button = { cls<MultiButton>(), wrap_button }; Style toggle = { cls<Toggle>(), control }; Style checkbox = { cls<Checkbox>(), toggle }; Style tooltip = { cls<Tooltip>(), decal, Args{ { &Layout::m_zorder, -2 } } }; Style rectangle = { cls<Rectangle>(), decal, Args{ { &Layout::m_space, BLOCK }, { &InkStyle::m_border_width, 1.f }, { &InkStyle::m_border_colour, Colour::Cyan } } }; Style type_in = { cls<TypeIn>(), wrap_control, Args{ { &Layout::m_opacity, OPAQUE } } }; Style textbox = { cls<Textbox>(), type_in, Args{ { &Layout::m_space, LAYOUT }, { &InkStyle::m_text_wrap, true } } }; Style caret = { "Caret", item, Args{ { &InkStyle::m_background_colour, Colour::White } } }; Style figure = { "Figure", item, Args{ { &InkStyle::m_empty, false} } }; Style radio_switch = { cls<RadioSwitch>(), wrap_control }; Style radio_choice = { "RadioChoice", multi_button }; Style radio_choice_item = { "RadioChoiceItem", item }; Style slider = { cls<Slider>(), wrap_control, Args{ { &Layout::m_space, FLEX } } }; Style slider_knob = { "SliderKnob", item, Args{ /*{ &Layout::m_flow, OVERLAY }, { &Layout::m_space, FLEX }*/ } }; Style slider_display = { "SliderDisplay", label, Args{ { &Layout::m_flow, OVERLAY }, { &Layout::m_align, Dim<Align>{ CENTER, CENTER } } } }; Style progress_bar = { "Fillbar", row }; Style number_input = { "NumberInput", row }; Style slider_input = { "SliderInput", row }; Style field_input = { "Field", wrap_control }; Style input_bool = { cls<Input<bool>>(), wedge, Args{ { &Layout::m_space, UNIT } } }; Style input_string = { cls<Input<string>>(), type_in }; Style input_color = { cls<Input<Colour>>(), row }; Style scrollsheet = { cls<ScrollSheet>(), wedge, Args{ { &Layout::m_solver, GRID_SOLVER }, { &Layout::m_opacity, OPAQUE } } }; Style scroll_zone = { "ScrollZone", layout, Args{ { &Layout::m_layout, Dim<AutoLayout>{ AUTO_SIZE, AUTO_SIZE } }, { &Layout::m_clipping, CLIP } } }; Style scroll_surface = { "ScrollSurface", wedge }; Style scrollplan = { cls<ScrollPlan>(), scrollsheet }; Style scrollplan_surface = { "ScrollplanSurface", sheet, Args{ { &Layout::m_space, BLOCK }/*, { &InkStyle::m_customRenderer, &drawGrid }*/ } }; Style table = { cls<Table>(), stack, Args{ /*{ &Layout::m_solver, TABLE_SOLVER },*/ { &Layout::m_spacing, DimFloat(0.f, 2.f) } } }; Style table_head = { "TableHead", gridsheet, Args{ { &Layout::m_space, DIV } } }; Style column_header = { "ColumnHeader", row, Args{ { &Layout::m_space, LINE } } }; Style popup = { cls<Popup>(), overlay, Args{ { &Layout::m_size, DimFloat{ 280.f, 350.f } } } }; }; } #endif // TOY_STYLE_H
40.048872
167
0.675584
[ "object", "vector" ]
d95d02641ce92505aca135923c872ed333af3b31
3,537
c
C
fdf_map_loading.c
coder-guy22296/42-fdf
0b6f1612dcc6595b61bb52ccc99ed61f3566f237
[ "Apache-2.0" ]
null
null
null
fdf_map_loading.c
coder-guy22296/42-fdf
0b6f1612dcc6595b61bb52ccc99ed61f3566f237
[ "Apache-2.0" ]
null
null
null
fdf_map_loading.c
coder-guy22296/42-fdf
0b6f1612dcc6595b61bb52ccc99ed61f3566f237
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fdf_map_loading.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cyildiri <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/22 09:16:46 by cyildiri #+# #+# */ /* Updated: 2016/12/22 09:16:51 by cyildiri ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" /* ** Load an fdf file into a linked list of arrays of strings */ int load_into_list(int fd, t_list **lines, int *max_column_cnt) { char *line; int line_cnt; int col_cnt; char **column_arr; line_cnt = 0; *max_column_cnt = -99; line = NULL; while (get_next_line(fd, &line) == 1) { column_arr = ft_strsplit(line, ' '); col_cnt = ft_cntwords(line, ' '); *max_column_cnt = (col_cnt > *max_column_cnt) ? col_cnt : *max_column_cnt; ft_lstadd(lines, ft_lstnew((void *)column_arr, sizeof(char *) * (col_cnt + 1))); ft_memdel((void **)&line); line_cnt++; } return (line_cnt); } /* ** Converts a linked list of arrays of strings into a 2d array of integers */ void convert_list2array(t_list *lines, int **arr2d, int rows, int columns) { t_list *tmp; int valid_col; int row; int col; row = 0; while (lines != NULL && row < rows) { tmp = lines->next; col = 0; valid_col = (((char **)lines->content)[col] == 0) ? 0 : 1; while (col < columns) { if (valid_col) { valid_col = (((char **)lines->content)[col + 1] == 0) ? 0 : 1; arr2d[row][col] = ft_atoi(((char **)lines->content)[col]); } else arr2d[row][col] = -2147483648; col++; } lines = tmp; row++; } } /* ** Sets the minimum and maximum z values for a specified object */ static void set_min_max_z(t_3d_object *obj, int x, int y, int z) { if ((z > obj->z_max || (x == 0 && y == 0)) && z != -2147483648) obj->z_max = z; if ((z < obj->z_min || (x == 0 && y == 0)) && z != -2147483648) obj->z_min = z; } /* ** sets the line draw order for a square in the wireframe */ static void set_object_vert_indices(t_3d_object *obj, int cur_vert, int cols, int *cur_face_vert) { obj->faces_arr[*cur_face_vert / 4] = 4; obj->vertex_ind[(*cur_face_vert)++] = cur_vert + 1; obj->vertex_ind[(*cur_face_vert)++] = cur_vert; obj->vertex_ind[(*cur_face_vert)++] = cur_vert + cols; obj->vertex_ind[(*cur_face_vert)++] = cur_vert + cols + 1; } /* ** converts 2d int array into my 3d model struct */ t_3d_object *array2d_to_object(int **arr2d, int rows, int cols) { t_3d_object *obj; int cur_face_vert; int cur_vert; int y; int x; obj = new_fdf_wireframe((rows - 1) * (cols - 1), rows * cols, 4); cur_face_vert = 0; cur_vert = 0; y = 0; while (y < rows) { x = 0; while (x < cols) { set_min_max_z(obj, x, y, arr2d[y][x]); obj->vertices[cur_vert] = vec3fc(x, y, arr2d[y][x], 0x0); if (x < cols - 1 && y < rows - 1) set_object_vert_indices(obj, cur_vert, cols, &cur_face_vert); cur_vert++; x++; } y++; } return (obj); }
25.817518
80
0.478937
[ "object", "model", "3d" ]
d96210543ba11c7e1f4cff8febd63829586450b9
3,535
h
C
src/ppl/nn/oputils/broadcast.h
weisk/ppl.nn
7dd75a1077867fc9a762449953417088446ae2f8
[ "Apache-2.0" ]
1
2021-10-06T14:39:58.000Z
2021-10-06T14:39:58.000Z
src/ppl/nn/oputils/broadcast.h
wolf15/ppl.nn
ac23e5eb518039536f1ef39b43c63d6bda900e77
[ "Apache-2.0" ]
null
null
null
src/ppl/nn/oputils/broadcast.h
wolf15/ppl.nn
ac23e5eb518039536f1ef39b43c63d6bda900e77
[ "Apache-2.0" ]
null
null
null
#ifndef _ST_HPC_PPL_NN_OPUTILS_BROADCAST_H_ #define _ST_HPC_PPL_NN_OPUTILS_BROADCAST_H_ #include "ppl/nn/common/tensor_shape.h" #include <vector> namespace ppl { namespace nn { namespace oputils { class BroadCaster { public: BroadCaster() {} virtual ~BroadCaster() {} void SetInputTensorShape0(const TensorShape& input_tensor_shape0) { input_tensor_shape0_ = input_tensor_shape0; } void SetInputTensorShape1(const TensorShape& input_tensor_shape1) { input_tensor_shape1_ = input_tensor_shape1; } const TensorShape& InputTensorShape0() const { return input_tensor_shape0_; } const TensorShape& InputTensorShape1() const { return input_tensor_shape1_; } virtual void CalcBroadCast(void) = 0; void SetInputTensorShapes(const TensorShape& input_tensor_shape0, const TensorShape& input_tensor_shape1) { input_tensor_shape0_ = input_tensor_shape0; input_tensor_shape1_ = input_tensor_shape1; CalcBroadCast(); // will calculate broad cast automatically } /* functions below are valid only when calcBroadCast() has already called. */ bool CanBroadCast(void) { return can_broadcast_; } const TensorShape& OutputTensorShape(void) const { return output_tensor_shape_; } protected: bool can_broadcast_ = false; TensorShape input_tensor_shape0_; TensorShape input_tensor_shape1_; TensorShape output_tensor_shape_; }; /** * MultiDirectionalBroadCaster * Used for ops such as Add, Sub, Mul and etc. * Input tensor 0 & input tensor 1 will both occur broadcasting * Details see: https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md */ class MultiDirectionalBroadCaster : public BroadCaster { public: MultiDirectionalBroadCaster() {} virtual ~MultiDirectionalBroadCaster() {} void CalcBroadCast(void) override; }; /** * MultiInputBroadCaster * Used for ops such as Max, Min, Sum and etc. * All input tensors may occur broadcasting * Details see: https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md */ class MultiInputBroadCaster { public: void CalcBroadCast(void); bool CanBroadCast() { return can_broadcast_; } TensorShape InputTensorShape(uint32_t idx) const { if (idx < input_tensor_shapes_.size()) { return input_tensor_shapes_[idx]; } return TensorShape(); } void SetInputTensorShape(uint32_t idx, const TensorShape& shape) { if (idx < input_tensor_shapes_.size()) { input_tensor_shapes_[idx] = shape; } } void PushBackInputTensorShape(const TensorShape& shape) { input_tensor_shapes_.push_back(shape); } void SetInputTensorShapes(const std::vector<TensorShape>& shapes) { input_tensor_shapes_ = shapes; CalcBroadCast(); } const TensorShape& OutputTensorShape(void) const { return output_tensor_shape_; } void ClearInputTensorShapes(void) { input_tensor_shapes_.clear(); } private: bool can_broadcast_ = false; std::vector<TensorShape> input_tensor_shapes_; TensorShape output_tensor_shape_; }; /** * MatMulBroadCaster * Used for Matmul. * Details see: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html */ class MatMulBroadCaster : public BroadCaster { public: MatMulBroadCaster() {} virtual ~MatMulBroadCaster() {} void CalcBroadCast(void) override; }; }}} // namespace ppl::nn::oputils #endif
26.984733
111
0.708062
[ "shape", "vector" ]
d96a32c55fcfe554499d62526202582cd4b3fb6c
28,603
h
C
dev/cmake-3.5.1/Source/cmGeneratorTarget.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
dev/cmake-3.5.1/Source/cmGeneratorTarget.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
dev/cmake-3.5.1/Source/cmGeneratorTarget.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2012 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifndef cmGeneratorTarget_h #define cmGeneratorTarget_h #include "cmLinkItem.h" class cmCustomCommand; class cmGlobalGenerator; class cmLocalGenerator; class cmMakefile; class cmSourceFile; class cmTarget; class cmComputeLinkInformation; class cmGeneratorTarget { public: cmGeneratorTarget(cmTarget*, cmLocalGenerator* lg); ~cmGeneratorTarget(); cmLocalGenerator* GetLocalGenerator() const; bool IsImported() const; bool IsImportedGloballyVisible() const; const char *GetLocation(const std::string& config) const; std::vector<cmCustomCommand> const &GetPreBuildCommands() const; std::vector<cmCustomCommand> const &GetPreLinkCommands() const; std::vector<cmCustomCommand> const &GetPostBuildCommands() const; #define DECLARE_TARGET_POLICY(POLICY) \ cmPolicies::PolicyStatus GetPolicyStatus ## POLICY () const \ { return this->PolicyMap.Get(cmPolicies::POLICY); } CM_FOR_EACH_TARGET_POLICY(DECLARE_TARGET_POLICY) #undef DECLARE_TARGET_POLICY /** Get the location of the target in the build tree with a placeholder referencing the configuration in the native build system. This location is suitable for use as the LOCATION target property. */ const char* GetLocationForBuild() const; cmComputeLinkInformation* GetLinkInformation(const std::string& config) const; cmState::TargetType GetType() const; const std::string& GetName() const; std::string GetExportName() const; std::vector<std::string> GetPropertyKeys() const; const char *GetProperty(const std::string& prop) const; bool GetPropertyAsBool(const std::string& prop) const; void GetSourceFiles(std::vector<cmSourceFile*>& files, const std::string& config) const; void GetObjectSources(std::vector<cmSourceFile const*> &, const std::string& config) const; const std::string& GetObjectName(cmSourceFile const* file); bool HasExplicitObjectName(cmSourceFile const* file) const; void AddExplicitObjectName(cmSourceFile const* sf); void GetResxSources(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetIDLSources(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetExternalObjects(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetHeaderSources(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetExtraSources(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetCustomCommands(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetExpectedResxHeaders(std::set<std::string>&, const std::string& config) const; void GetAppManifest(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetManifests(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetCertificates(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetXamlSources(std::vector<cmSourceFile const*>&, const std::string& config) const; void GetExpectedXamlHeaders(std::set<std::string>&, const std::string& config) const; void GetExpectedXamlSources(std::set<std::string>&, const std::string& config) const; std::set<cmLinkItem>const& GetUtilityItems() const; void ComputeObjectMapping(); const char* GetFeature(const std::string& feature, const std::string& config) const; bool GetFeatureAsBool(const std::string& feature, const std::string& config) const; bool IsLinkInterfaceDependentBoolProperty(const std::string &p, const std::string& config) const; bool IsLinkInterfaceDependentStringProperty(const std::string &p, const std::string& config) const; bool IsLinkInterfaceDependentNumberMinProperty(const std::string &p, const std::string& config) const; bool IsLinkInterfaceDependentNumberMaxProperty(const std::string &p, const std::string& config) const; bool GetLinkInterfaceDependentBoolProperty(const std::string &p, const std::string& config) const; const char *GetLinkInterfaceDependentStringProperty(const std::string &p, const std::string& config) const; const char *GetLinkInterfaceDependentNumberMinProperty(const std::string &p, const std::string& config) const; const char *GetLinkInterfaceDependentNumberMaxProperty(const std::string &p, const std::string& config) const; cmLinkInterface const* GetLinkInterface(const std::string& config, const cmGeneratorTarget* headTarget) const; void ComputeLinkInterface(const std::string& config, cmOptionalLinkInterface& iface, const cmGeneratorTarget* head) const; cmLinkInterfaceLibraries const* GetLinkInterfaceLibraries(const std::string& config, const cmGeneratorTarget* headTarget, bool usage_requirements_only) const; void ComputeLinkInterfaceLibraries(const std::string& config, cmOptionalLinkInterface &iface, const cmGeneratorTarget* head, bool usage_requirements_only) const; /** Get the full path to the target according to the settings in its makefile and the configuration type. */ std::string GetFullPath(const std::string& config="", bool implib = false, bool realname = false) const; std::string NormalGetFullPath(const std::string& config, bool implib, bool realname) const; std::string NormalGetRealName(const std::string& config) const; /** @return the Mac App directory without the base */ std::string GetAppBundleDirectory(const std::string& config, bool contentOnly) const; /** Return whether this target is an executable Bundle, a framework or CFBundle on Apple. */ bool IsBundleOnApple() const; /** Get the full name of the target according to the settings in its makefile. */ std::string GetFullName(const std::string& config="", bool implib = false) const; /** @return the Mac framework directory without the base. */ std::string GetFrameworkDirectory(const std::string& config, bool rootDir) const; /** Return the framework version string. Undefined if IsFrameworkOnApple returns false. */ std::string GetFrameworkVersion() const; /** @return the Mac CFBundle directory without the base */ std::string GetCFBundleDirectory(const std::string& config, bool contentOnly) const; /** Return the install name directory for the target in the * build tree. For example: "\@rpath/", "\@loader_path/", * or "/full/path/to/library". */ std::string GetInstallNameDirForBuildTree(const std::string& config) const; /** Return the install name directory for the target in the * install tree. For example: "\@rpath/" or "\@loader_path/". */ std::string GetInstallNameDirForInstallTree() const; cmListFileBacktrace GetBacktrace() const; const std::vector<std::string>& GetLinkDirectories() const; std::set<std::string>const& GetUtilities() const; cmListFileBacktrace const* GetUtilityBacktrace(const std::string& u) const; bool LinkLanguagePropagatesToDependents() const { return this->GetType() == cmState::STATIC_LIBRARY; } /** Get the macro to define when building sources in this target. If no macro should be defined null is returned. */ const char* GetExportMacro() const; /** Get the soname of the target. Allowed only for a shared library. */ std::string GetSOName(const std::string& config) const; void GetFullNameComponents(std::string& prefix, std::string& base, std::string& suffix, const std::string& config="", bool implib = false) const; /** Append to @a base the mac content directory and return it. */ std::string BuildMacContentDirectory(const std::string& base, const std::string& config = "", bool contentOnly = true) const; /** @return the mac content directory for this target. */ std::string GetMacContentDirectory(const std::string& config = 0, bool implib = false) const; cmTarget* Target; cmMakefile* Makefile; cmLocalGenerator* LocalGenerator; cmGlobalGenerator const* GlobalGenerator; cmSourceFile const* GetModuleDefinitionFile(const std::string& config) const; /** Return whether or not the target is for a DLL platform. */ bool IsDLLPlatform() const; /** @return whether this target have a well defined output file name. */ bool HaveWellDefinedOutputFiles() const; /** Link information from the transitive closure of the link implementation and the interfaces of its dependencies. */ struct LinkClosure { // The preferred linker language. std::string LinkerLanguage; // Languages whose runtime libraries must be linked. std::vector<std::string> Languages; }; LinkClosure const* GetLinkClosure(const std::string& config) const; void ComputeLinkClosure(const std::string& config, LinkClosure& lc) const; cmLinkImplementation const* GetLinkImplementation(const std::string& config) const; void ComputeLinkImplementationLanguages(const std::string& config, cmOptionalLinkImplementation& impl ) const; cmLinkImplementationLibraries const* GetLinkImplementationLibraries(const std::string& config) const; void ComputeLinkImplementationLibraries(const std::string& config, cmOptionalLinkImplementation& impl, const cmGeneratorTarget* head) const; cmGeneratorTarget* FindTargetToLink(std::string const& name) const; // Compute the set of languages compiled by the target. This is // computed every time it is called because the languages can change // when source file properties are changed and we do not have enough // information to forward these property changes to the targets // until we have per-target object file properties. void GetLanguages(std::set<std::string>& languages, std::string const& config) const; void GetObjectLibrariesCMP0026(std::vector<cmGeneratorTarget*>& objlibs) const; std::string GetFullNameImported(const std::string& config, bool implib) const; bool GetConfigCommonSourceFiles(std::vector<cmSourceFile*>& files) const; bool HaveBuildTreeRPATH(const std::string& config) const; /** Full path with trailing slash to the top-level directory holding object files for this target. Includes the build time config name placeholder if needed for the generator. */ std::string ObjectDirectory; void UseObjectLibraries(std::vector<std::string>& objs, const std::string& config) const; void GetAppleArchs(const std::string& config, std::vector<std::string>& archVec) const; /** Return the rule variable used to create this type of target. */ std::string GetCreateRuleVariable(std::string const& lang, std::string const& config) const; /** Get the include directories for this target. */ std::vector<std::string> GetIncludeDirectories( const std::string& config, const std::string& lang) const; void GetCompileOptions(std::vector<std::string> &result, const std::string& config, const std::string& language) const; void GetCompileFeatures(std::vector<std::string> &features, const std::string& config) const; void GetCompileDefinitions(std::vector<std::string> &result, const std::string& config, const std::string& language) const; bool IsSystemIncludeDirectory(const std::string& dir, const std::string& config) const; /** Add the target output files to the global generator manifest. */ void ComputeTargetManifest(const std::string& config) const; /** * Trace through the source files in this target and add al source files * that they depend on, used by all generators */ void TraceDependencies(); /** Get the directory in which this target will be built. If the configuration name is given then the generator will add its subdirectory for that configuration. Otherwise just the canonical output directory is given. */ std::string GetDirectory(const std::string& config = "", bool implib = false) const; /** Get the directory in which to place the target compiler .pdb file. If the configuration name is given then the generator will add its subdirectory for that configuration. Otherwise just the canonical compiler pdb output directory is given. */ std::string GetCompilePDBDirectory(const std::string& config = "") const; /** Get sources that must be built before the given source. */ std::vector<cmSourceFile*> const* GetSourceDepends(cmSourceFile const* sf) const; /** Return whether this target uses the default value for its output directory. */ bool UsesDefaultOutputDir(const std::string& config, bool implib) const; // Cache target output paths for each configuration. struct OutputInfo { std::string OutDir; std::string ImpDir; std::string PdbDir; bool empty() const { return OutDir.empty() && ImpDir.empty() && PdbDir.empty(); } }; OutputInfo const* GetOutputInfo(const std::string& config) const; /** Get the name of the pdb file for the target. */ std::string GetPDBName(const std::string& config="") const; /** Whether this library has soname enabled and platform supports it. */ bool HasSOName(const std::string& config) const; struct CompileInfo { std::string CompilePdbDir; }; CompileInfo const* GetCompileInfo(const std::string& config) const; typedef std::map<std::string, CompileInfo> CompileInfoMapType; mutable CompileInfoMapType CompileInfoMap; bool IsNullImpliedByLinkLibraries(const std::string &p) const; /** Get the name of the compiler pdb file for the target. */ std::string GetCompilePDBName(const std::string& config="") const; /** Get the path for the MSVC /Fd option for this target. */ std::string GetCompilePDBPath(const std::string& config="") const; // Get the target base name. std::string GetOutputName(const std::string& config, bool implib) const; void AddSource(const std::string& src); void AddTracedSources(std::vector<std::string> const& srcs); /** * Flags for a given source file as used in this target. Typically assigned * via SET_TARGET_PROPERTIES when the property is a list of source files. */ enum SourceFileType { SourceFileTypeNormal, SourceFileTypePrivateHeader, // is in "PRIVATE_HEADER" target property SourceFileTypePublicHeader, // is in "PUBLIC_HEADER" target property SourceFileTypeResource, // is in "RESOURCE" target property *or* // has MACOSX_PACKAGE_LOCATION=="Resources" SourceFileTypeMacContent // has MACOSX_PACKAGE_LOCATION!="Resources" }; struct SourceFileFlags { SourceFileFlags(): Type(SourceFileTypeNormal), MacFolder(0) {} SourceFileFlags(SourceFileFlags const& r): Type(r.Type), MacFolder(r.MacFolder) {} SourceFileType Type; const char* MacFolder; // location inside Mac content folders }; void GetAutoUicOptions(std::vector<std::string> &result, const std::string& config) const; /** Get the names of the executable needed to generate a build rule that takes into account executable version numbers. This should be called only on an executable target. */ void GetExecutableNames(std::string& name, std::string& realName, std::string& impName, std::string& pdbName, const std::string& config) const; /** Get the names of the library needed to generate a build rule that takes into account shared library version numbers. This should be called only on a library target. */ void GetLibraryNames(std::string& name, std::string& soName, std::string& realName, std::string& impName, std::string& pdbName, const std::string& config) const; /** * Compute whether this target must be relinked before installing. */ bool NeedRelinkBeforeInstall(const std::string& config) const; /** Return true if builtin chrpath will work for this target */ bool IsChrpathUsed(const std::string& config) const; /** Get the directory in which this targets .pdb files will be placed. If the configuration name is given then the generator will add its subdirectory for that configuration. Otherwise just the canonical pdb output directory is given. */ std::string GetPDBDirectory(const std::string& config) const; ///! Return the preferred linker language for this target std::string GetLinkerLanguage(const std::string& config = "") const; /** Does this target have a GNU implib to convert to MS format? */ bool HasImplibGNUtoMS() const; /** Convert the given GNU import library name (.dll.a) to a name with a new extension (.lib or ${CMAKE_IMPORT_LIBRARY_SUFFIX}). */ bool GetImplibGNUtoMS(std::string const& gnuName, std::string& out, const char* newExt = 0) const; bool IsExecutableWithExports() const; /** Return whether or not the target has a DLL import library. */ bool HasImportLibrary() const; /** Get a build-tree directory in which to place target support files. */ std::string GetSupportDirectory() const; /** Return whether this target may be used to link another target. */ bool IsLinkable() const; /** Return whether this target is a shared library Framework on Apple. */ bool IsFrameworkOnApple() const; /** Return whether this target is an executable Bundle on Apple. */ bool IsAppBundleOnApple() const; /** Return whether this target is a XCTest on Apple. */ bool IsXCTestOnApple() const; /** Return whether this target is a CFBundle (plugin) on Apple. */ bool IsCFBundleOnApple() const; struct SourceFileFlags GetTargetSourceFileFlags(const cmSourceFile* sf) const; struct ResxData { mutable std::set<std::string> ExpectedResxHeaders; mutable std::vector<cmSourceFile const*> ResxSources; }; struct XamlData { std::set<std::string> ExpectedXamlHeaders; std::set<std::string> ExpectedXamlSources; std::vector<cmSourceFile const*> XamlSources; }; void ReportPropertyOrigin(const std::string &p, const std::string &result, const std::string &report, const std::string &compatibilityType) const; class TargetPropertyEntry; bool HaveInstallTreeRPATH() const; /** Whether this library has \@rpath and platform supports it. */ bool HasMacOSXRpathInstallNameDir(const std::string& config) const; /** Whether this library defaults to \@rpath. */ bool MacOSXRpathInstallNameDirDefault() const; /** Test for special case of a third-party shared library that has no soname at all. */ bool IsImportedSharedLibWithoutSOName(const std::string& config) const; const char* ImportedGetLocation(const std::string& config) const; /** Get the target major and minor version numbers interpreted from the VERSION property. Version 0 is returned if the property is not set or cannot be parsed. */ void GetTargetVersion(int& major, int& minor) const; /** Get the target major, minor, and patch version numbers interpreted from the VERSION or SOVERSION property. Version 0 is returned if the property is not set or cannot be parsed. */ void GetTargetVersion(bool soversion, int& major, int& minor, int& patch) const; private: friend class cmTargetTraceDependencies; struct SourceEntry { std::vector<cmSourceFile*> Depends; }; typedef std::map<cmSourceFile const*, SourceEntry> SourceEntriesType; SourceEntriesType SourceDepends; mutable std::map<cmSourceFile const*, std::string> Objects; std::set<cmSourceFile const*> ExplicitObjectName; mutable std::map<std::string, std::vector<std::string> > SystemIncludesCache; mutable std::string ExportMacro; void ConstructSourceFileFlags() const; mutable bool SourceFileFlagsConstructed; mutable std::map<cmSourceFile const*, SourceFileFlags> SourceFlagsMap; mutable std::map<std::string, bool> DebugCompatiblePropertiesDone; std::string GetFullNameInternal(const std::string& config, bool implib) const; void GetFullNameInternal(const std::string& config, bool implib, std::string& outPrefix, std::string& outBase, std::string& outSuffix) const; typedef std::map<std::string, LinkClosure> LinkClosureMapType; mutable LinkClosureMapType LinkClosureMap; // Returns ARCHIVE, LIBRARY, or RUNTIME based on platform and type. const char* GetOutputTargetType(bool implib) const; void ComputeVersionedName(std::string& vName, std::string const& prefix, std::string const& base, std::string const& suffix, std::string const& name, const char* version) const; struct CompatibleInterfacesBase { std::set<std::string> PropsBool; std::set<std::string> PropsString; std::set<std::string> PropsNumberMax; std::set<std::string> PropsNumberMin; }; CompatibleInterfacesBase const& GetCompatibleInterfaces(std::string const& config) const; struct CompatibleInterfaces: public CompatibleInterfacesBase { CompatibleInterfaces(): Done(false) {} bool Done; }; mutable std::map<std::string, CompatibleInterfaces> CompatibleInterfacesMap; typedef std::map<std::string, cmComputeLinkInformation*> cmTargetLinkInformationMap; mutable cmTargetLinkInformationMap LinkInformation; void CheckPropertyCompatibility(cmComputeLinkInformation *info, const std::string& config) const; cmGeneratorTarget(cmGeneratorTarget const&); void operator=(cmGeneratorTarget const&); struct LinkImplClosure: public std::vector<cmGeneratorTarget const*> { LinkImplClosure(): Done(false) {} bool Done; }; mutable std::map<std::string, LinkImplClosure> LinkImplClosureMap; typedef std::map<std::string, cmHeadToLinkInterfaceMap> LinkInterfaceMapType; mutable LinkInterfaceMapType LinkInterfaceMap; mutable LinkInterfaceMapType LinkInterfaceUsageRequirementsOnlyMap; cmHeadToLinkInterfaceMap& GetHeadToLinkInterfaceMap(std::string const& config) const; cmHeadToLinkInterfaceMap& GetHeadToLinkInterfaceUsageRequirementsMap( std::string const& config) const; // Cache import information from properties for each configuration. struct ImportInfo { ImportInfo(): NoSOName(false), Multiplicity(0) {} bool NoSOName; int Multiplicity; std::string Location; std::string SOName; std::string ImportLibrary; std::string Languages; std::string Libraries; std::string LibrariesProp; std::string SharedDeps; }; typedef std::map<std::string, ImportInfo> ImportInfoMapType; mutable ImportInfoMapType ImportInfoMap; void ComputeImportInfo(std::string const& desired_config, ImportInfo& info) const; ImportInfo const* GetImportInfo(const std::string& config) const; /** Strip off leading and trailing whitespace from an item named in the link dependencies of this target. */ std::string CheckCMP0004(std::string const& item) const; cmLinkInterface const* GetImportLinkInterface(const std::string& config, const cmGeneratorTarget* head, bool usage_requirements_only) const; typedef std::map<std::string, std::vector<cmSourceFile*> > SourceFilesMapType; mutable SourceFilesMapType SourceFilesMap; std::vector<TargetPropertyEntry*> IncludeDirectoriesEntries; std::vector<TargetPropertyEntry*> CompileOptionsEntries; std::vector<TargetPropertyEntry*> CompileFeaturesEntries; std::vector<TargetPropertyEntry*> CompileDefinitionsEntries; std::vector<TargetPropertyEntry*> SourceEntries; mutable std::set<std::string> LinkImplicitNullProperties; void ExpandLinkItems(std::string const& prop, std::string const& value, std::string const& config, const cmGeneratorTarget* headTarget, bool usage_requirements_only, std::vector<cmLinkItem>& items, bool& hadHeadSensitiveCondition) const; void LookupLinkItems(std::vector<std::string> const& names, std::vector<cmLinkItem>& items) const; void GetSourceFiles(std::vector<std::string>& files, const std::string& config) const; struct HeadToLinkImplementationMap: public std::map<cmGeneratorTarget const*, cmOptionalLinkImplementation> {}; typedef std::map<std::string, HeadToLinkImplementationMap> LinkImplMapType; mutable LinkImplMapType LinkImplMap; cmLinkImplementationLibraries const* GetLinkImplementationLibrariesInternal(const std::string& config, const cmGeneratorTarget* head) const; bool ComputeOutputDir(const std::string& config, bool implib, std::string& out) const; typedef std::map<std::string, OutputInfo> OutputInfoMapType; mutable OutputInfoMapType OutputInfoMap; typedef std::pair<std::string, bool> OutputNameKey; typedef std::map<OutputNameKey, std::string> OutputNameMapType; mutable OutputNameMapType OutputNameMap; mutable std::set<cmLinkItem> UtilityItems; cmPolicies::PolicyMap PolicyMap; mutable bool PolicyWarnedCMP0022; mutable bool DebugIncludesDone; mutable bool DebugCompileOptionsDone; mutable bool DebugCompileFeaturesDone; mutable bool DebugCompileDefinitionsDone; mutable bool DebugSourcesDone; mutable bool LinkImplementationLanguageIsContextDependent; mutable bool UtilityItemsDone; bool DLLPlatform; bool ComputePDBOutputDir(const std::string& kind, const std::string& config, std::string& out) const; public: const std::vector<const cmGeneratorTarget*>& GetLinkImplementationClosure(const std::string& config) const; mutable std::map<std::string, std::string> MaxLanguageStandards; std::map<std::string, std::string> const& GetMaxLanguageStandards() const { return this->MaxLanguageStandards; } struct StrictTargetComparison { bool operator()(cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const; }; }; #endif
40.745014
79
0.672901
[ "object", "vector" ]
d976276ed1764a5e38a0312e8f9d8d81a5048087
10,719
h
C
icu/source/test/intltest/fldset.h
NanoMichael/cross_compile_icu4c_for_android
2b5aa1ef725ebcdd6de5c5156125b0dc2aa74bdf
[ "Apache-2.0" ]
2
2019-12-07T11:29:58.000Z
2021-06-26T12:48:10.000Z
icu/source/test/intltest/fldset.h
NanoMichael/cross_compile_icu4c_for_android
2b5aa1ef725ebcdd6de5c5156125b0dc2aa74bdf
[ "Apache-2.0" ]
null
null
null
icu/source/test/intltest/fldset.h
NanoMichael/cross_compile_icu4c_for_android
2b5aa1ef725ebcdd6de5c5156125b0dc2aa74bdf
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ************************************************************************ * Copyright (c) 2007-2010, International Business Machines * Corporation and others. All Rights Reserved. ************************************************************************ */ #ifndef FLDSET_H_ #define FLDSET_H_ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "unicode/calendar.h" #include "unicode/ucal.h" #include "unicode/udat.h" #include "udbgutil.h" #include "dbgutil.h" #include "unicode/unistr.h" #define U_FIELDS_SET_MAX 64 /** * This class represents a collection of integer values (fields), each designated by * one of a particular set of enum values. Each integer value (int32_t) is optional and * may or may not be set. * * @internal ICU 3.8 */ class FieldsSet { protected: /** * subclass interface - construct the FieldsSet to reference one of the standard * enumerations. * @param whichEnum which enumaration value goes with this set. Will be used to calculate string * values and also enum size. * @see UDebugEnumType */ FieldsSet(UDebugEnumType whichEnum); /** * subclass interface - construct the FieldsSet without using a standard enum type. * @param fieldCount how many fields this object can hold. */ FieldsSet(int32_t fieldsCount); public: /** * Compare two sets. In typical test usage, 'this' is the resul of * a tested operation, and 'other' is the predefined expected value. * * @param other the set to compare against. * @param status will return U_ILLEGAL_ARGUMENT_ERROR if sets are not the same size * @return a formatted string listing which fields are set in * this, with the comparison made agaainst those fields in other. */ U_NAMESPACE_QUALIFIER UnicodeString diffFrom(const FieldsSet& other, UErrorCode &status) const; public: /** * Fill-in fields from a specified string, such as "NAME1=VALUE1,NAME2=VALUE2", etc. * @param str string to parse * @param status status of parse * @return the number of valid parsed fields on success, or a negative number on failure. */ int32_t parseFrom(const U_NAMESPACE_QUALIFIER UnicodeString& str, UErrorCode& status) { return parseFrom(str,NULL,status); } /** * Fill-in fields from a specified string, such as "NAME1=VALUE1,NAME2=VALUE2", etc. * @param inheritFrom if a field's value is given as 0-length, such as NAME1 in "NAME1=,NAME2=VALUE2", * the specified FieldsSet's value for NAME1 will be copied into this. * @param str string to parse * @param status status of parse * @return the number of valid parsed fields on success, or a negative number on failure. */ int32_t parseFrom(const U_NAMESPACE_QUALIFIER UnicodeString& str, const FieldsSet& inheritFrom, UErrorCode& status) { return parseFrom(str, &inheritFrom, status); } /** * Fill-in fields from a specified string, such as "NAME1=VALUE1,NAME2=VALUE2", etc. * @param inheritFrom if a field's value is given as 0-length, such as NAME1 in "NAME1=,NAME2=VALUE2", * the specified FieldsSet's value for NAME1 will be copied into this. * @param str string to parse * @param status status of parse * @return the number of valid parsed fields on success, or a negative number on failure. */ int32_t parseFrom(const U_NAMESPACE_QUALIFIER UnicodeString& str, const FieldsSet* inheritFrom, UErrorCode& status); protected: /** * Callback interface for subclass. * This function is called when parsing a field name, such as "MONTH" in "MONTH=4". * Base implementation is to lookup the enum value using udbg_* utilities, or else as an integer if * enum is not available. * * If there is a special directive, the implementer can catch it here and return -1 after special processing completes. * * @param inheritFrom the set inheriting from - may be null. * @param name the field name (key side) * @param substr the string in question (value side) * @param status error status - set to error for failure. * @return field number, or negative if field should be skipped. */ virtual int32_t handleParseName(const FieldsSet* inheritFrom, const U_NAMESPACE_QUALIFIER UnicodeString& name, const U_NAMESPACE_QUALIFIER UnicodeString& substr, UErrorCode& status); /** * Callback interface for subclass. * Base implementation is to call parseValueDefault(...) * @param inheritFrom the set inheriting from - may be null. * @param field which field is being parsed * @param substr the string in question (value side) * @param status error status - set to error for failure. * @see parseValueDefault */ virtual void handleParseValue(const FieldsSet* inheritFrom, int32_t field, const U_NAMESPACE_QUALIFIER UnicodeString& substr, UErrorCode& status); /** * the default implementation for handleParseValue. * Base implementation is to parse a decimal integer value, or inherit from inheritFrom if the string is 0-length. * Implementations of this function should call set(field,...) on successful parse. * @see handleParseValue */ void parseValueDefault(const FieldsSet* inheritFrom, int32_t field, const U_NAMESPACE_QUALIFIER UnicodeString& substr, UErrorCode& status); /** * convenience implementation for handleParseValue * attempt to load a value from an enum value using udbg_enumByString() * if fails, will call parseValueDefault() * @see handleParseValue */ void parseValueEnum(UDebugEnumType type, const FieldsSet* inheritFrom, int32_t field, const U_NAMESPACE_QUALIFIER UnicodeString& substr, UErrorCode& status); private: /** * Not callable - construct a default FieldsSet * @internal */ FieldsSet(); /** * construct the object. * @internal */ void construct(UDebugEnumType whichEnum, int32_t fieldCount); public: /** * destructor */ virtual ~FieldsSet(); /** * Mark all fields as unset */ void clear(); /** * Mark a specific field as unset * @param field the field to unset */ void clear(int32_t field); /** * Set a specific field * @param field the field to set (i.e. enum value) * @param value the field's value */ void set(int32_t field, int32_t value); UBool isSet(int32_t field) const; /** * Return the field's value * @param field which field * @return field's value, or -1 if unset. */ int32_t get(int32_t field) const; /** * Return true if both FieldsSet objects either are based on the same enum, or have the same number of fields. */ UBool isSameType(const FieldsSet& other) const; /** * @return the number of fields */ int32_t fieldCount() const; protected: int32_t fValue[U_FIELDS_SET_MAX]; UBool fIsSet[U_FIELDS_SET_MAX]; protected: int32_t fFieldCount; UDebugEnumType fEnum; }; /** * A subclass of FieldsSet representing the fields in a Calendar * @see Calendar */ class CalendarFieldsSet : public FieldsSet { public: CalendarFieldsSet(); virtual ~CalendarFieldsSet(); // void clear(UCalendarDateFields field) { clear((int32_t)field); } // void set(UCalendarDateFields field, int32_t amount) { set ((int32_t)field, amount); } // UBool isSet(UCalendarDateFields field) const { return isSet((int32_t)field); } // int32_t get(UCalendarDateFields field) const { return get((int32_t)field); } /** * @param matches fillin to hold any fields different. Will have the calendar's value set on them. * @return true if the calendar matches in these fields. */ UBool matches(U_NAMESPACE_QUALIFIER Calendar *cal, CalendarFieldsSet &diffSet, UErrorCode& status) const; /** * For each set field, set the same field on this Calendar. * Doesn't clear the Calendar first. * @param cal Calendar to modify * @param status Contains any errors propagated by the Calendar. */ void setOnCalendar(U_NAMESPACE_QUALIFIER Calendar *cal, UErrorCode& status) const; protected: /** * subclass override */ void handleParseValue(const FieldsSet* inheritFrom, int32_t field, const U_NAMESPACE_QUALIFIER UnicodeString& substr, UErrorCode& status); }; /** * This class simply implements a set of date and time styles * such as DATE=SHORT or TIME=SHORT,DATE=LONG, such as would be passed * to DateFormat::createInstance() * @see DateFormat */ class DateTimeStyleSet : public FieldsSet { public: DateTimeStyleSet(); virtual ~DateTimeStyleSet(); /** * @return the date style, or UDAT_NONE if not set */ UDateFormatStyle getDateStyle() const; /** * @return the time style, or UDAT_NONE if not set */ UDateFormatStyle getTimeStyle() const; protected: void handleParseValue(const FieldsSet* inheritFrom, int32_t field, const U_NAMESPACE_QUALIFIER UnicodeString& substr, UErrorCode& status); int32_t handleParseName(const FieldsSet* inheritFrom, const U_NAMESPACE_QUALIFIER UnicodeString& name, const U_NAMESPACE_QUALIFIER UnicodeString& substr, UErrorCode& status); }; #endif /*!UCONFIG_NO_FORMAT*/ #endif /*FLDSET_H_*/
36.335593
125
0.606586
[ "object" ]
d9786ea2d2d5ddfcb1c7f4ed37fc2f1460385f64
2,445
h
C
3rdparty/webkit/Source/WebCore/crypto/SerializedCryptoKeyWrap.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
3rdparty/webkit/Source/WebCore/crypto/SerializedCryptoKeyWrap.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
3rdparty/webkit/Source/WebCore/crypto/SerializedCryptoKeyWrap.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2019-01-25T13:55:25.000Z
2019-01-25T13:55:25.000Z
/* * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <wtf/Forward.h> #include <wtf/text/WTFString.h> #if ENABLE(SUBTLE_CRYPTO) namespace WebCore { // The purpose of the following APIs is to protect serialized CryptoKey data in IndexedDB or // any other local storage that go through the structured clone algorithm. However, a side effect // of this extra layer of protection is redundant communications between mainThread(document) and // workerThreads. Please refer to WorkerGlobalScope for detailed explanation. P.S. This extra layer // of protection is not required by the spec as of 11 December 2014: // https://www.w3.org/TR/WebCryptoAPI/#security-developers WEBCORE_EXPORT bool getDefaultWebCryptoMasterKey(Vector<uint8_t>&); WEBCORE_EXPORT bool deleteDefaultWebCryptoMasterKey(); WEBCORE_EXPORT bool wrapSerializedCryptoKey(const Vector<uint8_t>& masterKey, const Vector<uint8_t>& key, Vector<uint8_t>& result); WEBCORE_EXPORT bool unwrapSerializedCryptoKey(const Vector<uint8_t>& masterKey, const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key); } // namespace WebCore #endif // ENABLE(SUBTLE_CRYPTO)
47.941176
137
0.779959
[ "vector" ]
d97d800ae6190c8088d1468b529c2ec704061794
3,534
h
C
sdk/ode/include/ode/contact.h
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
2
2020-11-11T16:19:04.000Z
2021-01-19T01:53:29.000Z
sdk/ode/include/ode/contact.h
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2020-07-27T09:00:21.000Z
2020-07-27T10:58:10.000Z
sdk/ode/include/ode/contact.h
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2021-04-04T01:39:55.000Z
2021-04-04T01:39:55.000Z
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #ifndef _ODE_CONTACT_H_ #define _ODE_CONTACT_H_ #include <ode/common.h> #ifdef __cplusplus extern "C" { #endif enum { dContactMu2 = 0x001, dContactFDir1 = 0x002, dContactBounce = 0x004, dContactSoftERP = 0x008, dContactSoftCFM = 0x010, dContactMotion1 = 0x020, dContactMotion2 = 0x040, dContactMotionN = 0x080, dContactSlip1 = 0x100, dContactSlip2 = 0x200, dContactApprox0 = 0x0000, dContactApprox1_1 = 0x1000, dContactApprox1_2 = 0x2000, dContactApprox1 = 0x3000 }; typedef struct dSurfaceParameters { /* must always be defined */ int mode; dReal mu; /* only defined if the corresponding flag is set in mode */ dReal mu2; dReal bounce; dReal bounce_vel; dReal soft_erp; dReal soft_cfm; dReal motion1,motion2,motionN; dReal slip1,slip2; } dSurfaceParameters; /** * @brief Describe the contact point between two geoms. * * If two bodies touch, or if a body touches a static feature in its * environment, the contact is represented by one or more "contact * points", described by dContactGeom. * * The convention is that if body 1 is moved along the normal vector by * a distance depth (or equivalently if body 2 is moved the same distance * in the opposite direction) then the contact depth will be reduced to * zero. This means that the normal vector points "in" to body 1. * * @ingroup collide */ typedef struct dContactGeom { dVector3 pos; ///< contact position dVector3 normal; ///< normal vector dReal depth; ///< penetration depth dGeomID g1,g2; ///< the colliding geoms int side1,side2; ///< (to be documented) } dContactGeom; /* contact info used by contact joint */ typedef struct dContact { dSurfaceParameters surface; dContactGeom geom; dVector3 fdir1; } dContact; #ifdef __cplusplus } #endif #endif
33.657143
76
0.554612
[ "vector" ]
d97fbec79e15e6e78ff1c5c3f3b5cff358cd06ea
44,643
c
C
Benchmarks_with_Functional_Bugs/C/gcal-4.1/gcal_src/src/file-io.c
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/C/gcal-4.1/gcal_src/src/file-io.c
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/C/gcal-4.1/gcal_src/src/file-io.c
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
2
2020-11-26T13:27:14.000Z
2022-03-20T02:12:55.000Z
/*! * \file file-io.c * \brief Managing and accessing resource, include and response files. */ /* * Copyright (c) 1994, 95, 96, 1997, 2000, 2011 Thomas Esken * Copyright (c) 2010, 2011, 2013 Free Software Foundation, Inc. * * This software doesn't claim completeness, correctness or usability. * On principle I will not be liable for ANY damages or losses (implicit * or explicit), which result from using or handling my software. * If you use this software, you agree without any exception to this * agreement, which binds you LEGALLY !! * * This program is free software; you can redistribute it and/or modify * it under the terms of the `GNU General Public License' as published by * the `Free Software Foundation'; either version 3, or (at your option) * any later version. * * You should have received a copy of the `GNU General Public License' * along with this program; if not, write to the: * */ /* * Include header files. */ #include "tailor.h" #if HAVE_CTYPE_H # include <ctype.h> #endif #ifdef GCAL_SHELL # if HAVE_UNISTD_H # include <unistd.h> # endif #endif #if HAVE_SYS_STAT_H # if HAVE_SYS_TYPES_H # include <sys/types.h> # endif # include <sys/stat.h> #endif #include "common.h" #if USE_RC # include "rc-defs.h" #endif /* !USE_RC */ #include "globals.h" #include "gcal.h" #include "hd-defs.h" #include "hd-use.h" #if USE_RC # include "rc-utils.h" #endif #include "tty.h" #include "utils.h" #include "file-io.h" /* * static functions prototypes. */ __BEGIN_DECLARATIONS /* ************************************************** Defined in `file-io.c'. */ static void make_absolute_filename __P_ ((char **absolute_filename, const char *directory, const char *filename)); static FILE *get_file_ptr __P_ ((FILE * fp, const char *filename, const int level, const Fmode_enum mode, Bool * is_first)); __END_DECLARATIONS /* * Function implementations. */ FILE * file_open (filename, level, mode, bad_sys_include) char ** filename; const int level; const Fmode_enum mode; Bool * bad_sys_include; /*! Tries to open a resource/response file (MODE == `REsource', `REsponse') in the following order: 1) $GCALPATH 2) $HOME 3) $GCAL_USR_DATADIR (environment variable first; default name if unset) 4) $GCAL_SYS_DATADIR (environment variable first; default name if unset) and returns a file pointer to this file and it's MODIFIED name in some cases (due to this, it's necessary to reallocate the memory area of `&filename', which must be allocated on the heap), otherwise return a NULL pointer. If MODE is set to `USr_include', this function tries to open an include file (#include "file" directive found) in: 1) actual directory 2) $GCALPATH 3) $HOME 4) $GCAL_USR_DATADIR (environment variable first; default name if unset) 5) $GCAL_SYS_DATADIR (environment variable first; default name if unset) and returns a file pointer to this file and it's MODIFIED name in some cases (due to this, it's necessary to reallocate the memory area of `&filename', which must be allocated on the heap), otherwise return a NULL pointer. If a root directory based include file name is given, set `&bad_sys_include' to TRUE! If MODE is set to `SYs_include', this function tries to open an include file (#include <file> directive found) only in: 1) $GCAL_USR_DATADIR (environment variable first; default name if unset) 2) $GCAL_SYS_DATADIR (environment variable first; default name if unset) and returns a file pointer to this file and it's MODIFIED name in some cases (due to this, it's necessary to reallocate the memory area of `&filename', which must be allocated on the heap), otherwise return a NULL pointer. If a root directory based include file name is given, set `&bad_sys_include' to TRUE! If MODE is set to `HEre', this function tries to open a "here" file (`--here=ARG' option) in 1) actual directory and returns a file pointer to this file and it's name, otherwise return a NULL pointer. If MODE is set to `COmmon', this function tries to open a common file in 1) $PATH and returns a file pointer to this file and it's name, otherwise return a NULL pointer. Passes the nesting LEVEL only for informational purposes to other functions called here. NO informational messages will be emitted in `REsponse' and `COmmon' modes!! */ { auto FILE *fp = (FILE *) NULL; register int len; auto char *ptr_env; auto char *ptr_char; auto Bool is_absolute_filename = FALSE; #if USE_RC auto Bool is_root_based_filename = FALSE; auto Bool is_disk_given = FALSE; auto Bool is_first = (Bool) ((mode == REsource) ? TRUE : FALSE); #else /* !USE_RC */ auto Bool is_first = FALSE; #endif /* !USE_RC */ len = (int) strlen (*filename); if ((Uint) len >= maxlen_max) resize_all_strings (len + 1, FALSE, __FILE__, (long) __LINE__); strcpy (s1, *filename); ptr_char = *filename; #ifdef DISK_SEP ptr_char = strchr (*filename, *DISK_SEP); if (ptr_char != (char *) NULL) { /* If a disk/drive is specified, this is like an absolute file name! */ is_absolute_filename = TRUE; # if USE_RC is_disk_given = TRUE; # endif ptr_char++; } else ptr_char = *filename; #endif /* DISK_SEP */ #if USE_RC /* Check if an absolute file name is given. */ if (*ptr_char == *DIR_SEP || *ptr_char == *ACTUAL_DIR) { if (*ptr_char == *ACTUAL_DIR) { while (*ptr_char == *ACTUAL_DIR) ptr_char++; if (*ptr_char == *DIR_SEP) { is_absolute_filename = TRUE; ptr_char--; } } else is_absolute_filename = TRUE; } else /* Check if STDIN channel is wanted. */ if ((*ptr_char == '-') && (len == 1)) is_absolute_filename = TRUE; if (*ptr_char == *DIR_SEP) is_root_based_filename = TRUE; if ((is_disk_given || is_root_based_filename) && (mode == SYs_include)) { /* Include files names. which are based by the root directory, are not allowed in system include statements, e.g.: #include </foo> or #include </foo/bar>. */ *bad_sys_include = TRUE; return (NULL); } *bad_sys_include = FALSE; if (mode != SYs_include) #endif { if (mode != COmmon) { /* Try to open the file directly (either absolute file name, USr_include file type or HEre file type given). */ if (is_absolute_filename #if USE_RC || mode == USr_include || mode == HEre #endif ) { fp = get_file_ptr (fp, *filename, level, mode, &is_first); /* If the file is found, return to caller immediately. */ if (fp != (FILE *) NULL) return (fp); else if (is_absolute_filename #if USE_RC || mode == HEre #endif ) { #if USE_RC if ((fp == (FILE *) NULL) && (warning_level >= WARN_LVL_MAX)) /* Terminate if `--debug=abort' option is given and the absolute file name or the `HEre' file name isn't found. */ my_error (ERR_FILE_NOT_FOUND, *filename, 0L, *filename, 0); #endif return (NULL); } } } #if !defined(AMIGA) || defined(__GNUC__) if (fp == (FILE *) NULL) { /* Simple file name delivered and the file isn't found: * Either search a COmmon file in the directory/ies, which are stored in the environment variable $PATH * Or search all other file types in the directory/ies, which are stored in the environment variable $GCALPATH. */ if (mode == COmmon) ptr_env = getenv (ENV_VAR_PATH); else ptr_env = getenv (ENV_VAR_GCALPATH); if (ptr_env != (char *) NULL) if (*ptr_env) { auto Bool ok = FALSE; len = (int) strlen (ptr_env); if ((Uint) len >= maxlen_max) resize_all_strings (len + 1, FALSE, __FILE__, (long) __LINE__); strcpy (s2, ptr_env); while (!ok && (fp == (FILE *) NULL)) { ok = (Bool) ((ptr_char = strchr (s2, *PATH_SEP)) == (char *) NULL); if (ok) len = (int) strlen (s2); else len = (int) strlen (s2) - strlen (ptr_char); strncpy (s1, s2, len); s1[len] = '\0'; if (len) if (s1[len - 1] != *DIR_SEP) strcat (s1, DIR_SEP); strcat (s1, *filename); # ifdef SUFFIX_SEP if ((ptr_char = strchr (s1, *SUFFIX_SEP)) != (char *) NULL) *ptr_char = '\0'; # endif if (*s1) fp = get_file_ptr (fp, s1, level, mode, &is_first); if (ok) break; ptr_char = s2 + len + 1; if (!*ptr_char) break; strcpy (s2, ptr_char); } /* If a file isn't found yet but the last character of the $[GCAL]PATH environment variable is a PATH_SEP character (which means the last search for the file must be done in the actual directory), perform this file access! */ if ((fp == (FILE *) NULL) && (*(ptr_env + strlen (ptr_env) - 1) == *PATH_SEP)) fp = get_file_ptr (fp, *filename, level, mode, &is_first); } } if (mode != COmmon) { if (fp == (FILE *) NULL) { /* File not found in the $GCALPATH directory: * Search the file in the directory, which is stored in the environment variable of $HOME. */ ptr_env = getenv (ENV_VAR_HOME); if (ptr_env != (char *) NULL) if (*ptr_env) { make_absolute_filename (&s1, ptr_env, *filename); fp = get_file_ptr (fp, s1, level, mode, &is_first); } } } } /* It's not necessary to perform further searches for COmmon files in the $GCAL_???_DATADIR directories! */ if (mode == COmmon) return (fp); # if USE_RC if (fp == (FILE *) NULL) { /* File not found in the $HOME directory: * Search the file in the user's library directory of $HOME/[$]GCAL_USR_DATADIR. */ ptr_env = getenv (ENV_VAR_HOME); if (ptr_env != (char *) NULL) if (*ptr_env) { ptr_char = getenv (ENV_VAR_USR_DATADIR); /* Search the file in the directory specified in the $GCAL_USR_DATADIR environment variable first. */ if (ptr_char != (char *) NULL) { if (*ptr_char) { make_absolute_filename (&s1, ptr_env, ptr_char); strcpy (s2, s1); make_absolute_filename (&s1, s2, *filename); fp = get_file_ptr (fp, s1, level, mode, &is_first); } } else { /* If the $GCAL_USR_DATADIR environment variable is unset, search the file in burned-in user's library directory of GCAL_USR_DATADIR. */ make_absolute_filename (&s1, ptr_env, GCAL_USR_DATADIR); strcpy (s2, s1); make_absolute_filename (&s1, s2, *filename); fp = get_file_ptr (fp, s1, level, mode, &is_first); } } } if (fp == (FILE *) NULL) { /* The file isn't found in user library directory of $HOME/[$]GCAL_USR_DATADIR: * Search the file in the system's library directory of $GCAL_SYS_DATADIR. */ ptr_env = getenv (ENV_VAR_SYS_DATADIR); /* Search the file in the directory specified in the $GCAL_SYS_DATADIR environment variable first. */ if (ptr_env != (char *) NULL) { if (*ptr_env) { make_absolute_filename (&s1, ptr_env, *filename); fp = get_file_ptr (fp, s1, level, mode, &is_first); } } else { /* If the $GCAL_SYS_DATADIR environment variable is unset: * Search the file in burned-in system's library directory of GCAL_SYS_DATADIR. */ make_absolute_filename (&s1, GCAL_SYS_DATADIR, *filename); fp = get_file_ptr (fp, s1, level, mode, &is_first); } } # endif /* USE_RC */ #else /* AMIGA && !__GNUC__ */ /* It's not necessary to perform further searches for COmmon files, because the compiler/system doesn't support the `getenv()' function. */ if (mode == COmmon) return (fp); # if USE_RC /* This part is for compilers/systems which do not support the `getenv()' function. */ if (fp == (FILE *) NULL) { /* The file isn't found in the actual directory: * Search the file in the burned-in user's library directory of GCAL_USR_DATADIR. */ make_absolute_filename (&s1, GCAL_USR_DATADIR, *filename); fp = get_file_ptr (fp, s1, level, mode, &is_first); } if (fp == (FILE *) NULL) { /* The file isn't found in the user's library directory of GCAL_USR_DATADIR: * Search the file in the burned-in system's library directory of GCAL_SYS_DATADIR. */ make_absolute_filename (&s1, GCAL_SYS_DATADIR, *filename); fp = get_file_ptr (fp, s1, level, mode, &is_first); } # endif /* USE_RC */ #endif /* AMIGA && !__GNUC__ */ /* If the file is found: Copy the real (absolute) name of the file to `&filename'. */ if (fp != (FILE *) NULL) { len = (int) strlen (s1); if ((int) strlen (*filename) < len) /* We MUST reallocate the memory area of `&filename'! */ *filename = (char *) my_realloc ((VOID_PTR) * filename, len + 1, ERR_NO_MEMORY_AVAILABLE, __FILE__, ((long) __LINE__) - 3L, "*filename", 0); strcpy (*filename, s1); } #if USE_RC else /* File not found! */ if (warning_level >= WARN_LVL_MAX) /* Terminate if `--debug=abort' option is given. */ my_error (ERR_FILE_NOT_FOUND, *filename, 0L, *filename, 0); #endif return (fp); } char *file_read_line (fp, line_buffer, in_pool, pool, ptr_pool, filename, line_number, line_length, mode, is_include, is_dvar, is_tvar) FILE *fp; char **line_buffer; int *in_pool; char *pool; char *ptr_pool; const char *filename; long *line_number; int *line_length; const Fmode_enum mode; Bool *is_include; Bool *is_dvar; Bool *is_tvar; /*! Reads a line of a delivered resource/response file into `&line_buffer' using the delivered char vector `pool', which must be allocated by caller with size BUF_LEN+1 (BUF_LEN should be "A POWER OF 2", e.g., 4096). Returns the position in buffer of the character managed in next call by char pointer `ptr_pool', which must be defined by caller; or NULL if EOF is detected. */ { static Uint lbuf_max = MAXLEN_MAX; register int i = 1; auto char *ptr_char; auto char ch; auto Bool is_error = FALSE; #if USE_RC auto Bool is_rem = FALSE; #endif /* Ensure NOW that `&line_buffer' is ALWAYS as large as all "other" string vectors (s1...s7) are, because the `&line_buffer' is not resized in all cases when the "other" strings vectors are resized! */ if (lbuf_max < maxlen_max) { *line_buffer = (char *) my_realloc ((VOID_PTR) * line_buffer, maxlen_max, ERR_NO_MEMORY_AVAILABLE, __FILE__, ((long) __LINE__) - 3L, "*line_buffer", maxlen_max); lbuf_max = maxlen_max; } **line_buffer = '\0'; *line_length = 0; ptr_char = *line_buffer; (*is_include) = (*is_dvar) = (*is_tvar) = FALSE; /* Initial fill/refill of `pool'. */ if (!*in_pool) { *in_pool = read (fileno (fp), (char *) pool, BUF_LEN); if (!*in_pool) /* At end of file. */ return (NULL); else if (*in_pool < 0) /* File read error. */ my_error (ERR_READ_FILE, __FILE__, (long) __LINE__, filename, 0); ptr_pool = pool; } if (*ptr_pool == '\n') (*line_number)++; while ((*ptr_pool != REM_CHAR) && ( #if USE_RC ((mode == REsource) && (*ptr_pool != *RC_INCL_STMENT) && (*ptr_pool != RC_TVAR_CHAR) && !isalnum (*ptr_pool)) || #endif ((mode == REsponse) && (*ptr_pool != *MONTH3_LIT) && (*ptr_pool != *FYEAR_SEP) && (*ptr_pool != RSP_CHAR) && !isalnum (*ptr_pool) #if USE_RC && (*ptr_pool != RC_ADATE_CHAR) #endif && (*ptr_pool != *SWITCH) && (*ptr_pool != *SWITCH2)))) { if ((!**line_buffer && !isspace (*ptr_pool)) || **line_buffer) { if ((Uint) i >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + i - 1; } i++; *ptr_char++ = *ptr_pool++; } else ptr_pool++; (*in_pool)--; if (!*in_pool) { /* Refill `pool', because the line we work on isn't complete. */ *in_pool = read (fileno (fp), (char *) pool, BUF_LEN); if (!*in_pool) { /* At end of file. */ if (i > 1) /* Error, the line of the resource file contains no valid "date"-part. */ break; return (NULL); } else if (*in_pool < 0) /* File read error. */ my_error (ERR_READ_FILE, __FILE__, (long) __LINE__, filename, 0); ptr_pool = pool; } if (*ptr_pool == '\n') { if (i > 1) { /* Error, the line of the resource file contains no valid "date"-part. */ if ((Uint) i < maxlen_max) i--; (*in_pool)++; ptr_pool--; ptr_char--; break; } (*line_number)++; } } (*line_number)++; /* Skip whole line. */ if ((mode != COmmon) && (*ptr_pool == REM_CHAR)) { #if USE_RC is_rem = TRUE; #endif LOOP { ch = '\0'; /* Read until a NEWLINE character or EOF. */ while (*ptr_pool != '\n') { /* Refill `pool', because the line we work on isn't complete. */ if (!*in_pool) { *in_pool = read (fileno (fp), (char *) pool, BUF_LEN); if (!*in_pool) /* At end of file. */ return (NULL); else if (*in_pool < 0) /* File read error. */ my_error (ERR_READ_FILE, __FILE__, (long) __LINE__, filename, 0); ptr_pool = pool; } else { ch = *ptr_pool++; (*in_pool)--; } } /* Skip the trailing NEWLINE character of the line. */ ptr_pool++; if (*in_pool) (*in_pool)--; /* Check if it is a `\\'`\n' (BACKSLASH-NEWLINE) character sequence: If so, append the next line to the current line. */ if (ch == QUOTE_CHAR) { if (!*in_pool) { *in_pool = read (fileno (fp), (char *) pool, BUF_LEN); if (!*in_pool) /* At end of file. */ return (NULL); else if (*in_pool < 0) /* File read error. */ my_error (ERR_READ_FILE, __FILE__, (long) __LINE__, filename, 0); ptr_pool = pool; } (*line_number)++; } else break; } } else { if (i > 1) is_error = TRUE; #if USE_RC else if (mode == REsource) { if (*ptr_pool == *RC_INCL_STMENT) *is_include = TRUE; else if (isalpha (*ptr_pool)) *is_dvar = TRUE; else if (*ptr_pool == RC_TVAR_CHAR) *is_tvar = TRUE; else if (!isdigit (*ptr_pool)) is_error = TRUE; } #endif ch = (*ptr_char++) = *ptr_pool++; (*in_pool)--; LOOP { if (*in_pool) { if ((Uint) i < maxlen_max) i++; else { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + i++; } /* Character sequence `\\'`\n' (BACKSLASH-NEWLINE) found: Eliminate the sequence and append the next line to the current line. */ if ((*ptr_pool == '\n') && (ch == QUOTE_CHAR)) { if (is_error) { (*in_pool)--; break; } if ((Uint) i >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + i - 1; } ptr_char--; i -= 2; (*line_number)++; ch = *ptr_pool; if (*in_pool) ptr_pool++; } else { ch = *ptr_pool++; /* Single NEWLINE character found: We must finish the line! */ if (ch == '\n') { (*in_pool)--; break; } else { if ((Uint) i >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + i - 1; } *ptr_char++ = ch; } } if (*in_pool) (*in_pool)--; } /* Refill `pool', because the line we work on isn't complete. */ if (!*in_pool) { *in_pool = read (fileno (fp), (char *) pool, BUF_LEN); if (!*in_pool) { /* At end of file. */ if (!**line_buffer) return (NULL); else break; } else if (*in_pool < 0) /* File read error. */ my_error (ERR_READ_FILE, __FILE__, (long) __LINE__, filename, 0); ptr_pool = pool; } } } *ptr_char = '\0'; #if USE_RC if (!is_error && !is_rem && (mode == REsource)) { if (*is_tvar) { if (i > 2) { /* If the line does not consist of a text variable assignment or operation, expand the text variable. */ if ((isalpha (*(*line_buffer + 1)) && (*(*line_buffer + 2) != *RC_VAR_ASSIGN) && (*(*line_buffer + 2) != *RC_TVAR_ICMD_ASSIGN) && (*(*line_buffer + 2) != *RC_TVAR_UCMD_ASSIGN) && (*(*line_buffer + 2) != *RC_VAR_ADD) && (*(*line_buffer + 2) != *RC_VAR_SUB)) || *(*line_buffer + 1) == FLEFT_CHAR || *(*line_buffer + 1) == FCENTER_CHAR || *(*line_buffer + 1) == FRIGHT_CHAR) *is_tvar = FALSE; } else *is_tvar = FALSE; } /* Try to expand text variables NOW! */ if (!*is_tvar) { register int len; register int n; register int k; register int x; register int l; register int flen = 1; auto int fstyle = FSTYLE_NONE; auto int fwidth = SPECIAL_VALUE; auto char *ptr_tvar; static char tvar[2]; static char the_tvar; auto Bool is_quoted = FALSE; auto Bool restore_tvar = FALSE; auto Bool ok = FALSE; auto Bool is_cformat = FALSE; auto Bool is_lformat = FALSE; auto Bool is_sign = FALSE; auto Bool is_lzero = FALSE; auto Bool is_fformat = FALSE; auto Bool is_suffix = FALSE; /* Analyse line till ALL referenced text variables are expanded. */ do { ptr_char = *line_buffer; /* Check if the assigned TEXT contains any references to other TVAR variables, if so, insert their TEXTs. */ ptr_tvar = strchr (ptr_char, RC_TVAR_CHAR); if (ptr_tvar != (char *) NULL) { n = flen; /* Buffer the name of the text variable respecting a possible TVAR format $[<|:|>[+][0]N[&]#|*]TVAR. */ while (*(ptr_tvar + n) && !isalpha (*(ptr_tvar + n))) n++; the_tvar = *(ptr_tvar + n); *tvar = tvar[1] = '\0'; n = k = 0; do { /* Check for a TVAR format. */ flen = decode_format (ptr_tvar, flen, &is_cformat, &is_lformat, &is_sign, &is_lzero, &is_suffix, &is_fformat, &fstyle, &fwidth); if (fwidth == SPECIAL_VALUE) flen = 1; *tvar = *(ptr_tvar + flen); tvar[1] = *(ptr_tvar + flen + 1); len = (int) (ptr_tvar - ptr_char); if (len) { while ((Uint) len + k >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + n; } strncpy (s5 + k, ptr_char, len); k += len; } s5[k] = '\0'; if (k) if (s5[k - 1] == QUOTE_CHAR) is_quoted = TRUE; if (!is_quoted && isalpha (*tvar)) { register int j = 0; register int j_buf; /* Try to insert the value of this TVAR (this is its TEXT). */ if (rc_tvar[IDX (*tvar)].tvar_local.tvar_text != (char *) NULL || rc_tvar[IDX (*tvar)].tvar_global. tvar_text != (char *) NULL) { auto char *buf; if (rc_tvar[IDX (*tvar)].tvar_local. tvar_text != (char *) NULL) { if (!*rc_tvar[IDX (*tvar)].tvar_local. tvar_text) { if (rc_tvar[IDX (*tvar)].tvar_global. tvar_text != (char *) NULL) buf = rc_tvar[IDX (*tvar)].tvar_global. tvar_text; else buf = rc_tvar[IDX (*tvar)].tvar_local. tvar_text; } else buf = rc_tvar[IDX (*tvar)].tvar_local. tvar_text; } else buf = rc_tvar[IDX (*tvar)].tvar_global. tvar_text; j_buf = (int) strlen (buf); if (fwidth != SPECIAL_VALUE) { if (is_fformat) j = fwidth; else { register int num_hls = 0; auto char *ptr_buf = buf; auto char *tvar_text; auto Bool quote = FALSE; /* Scan contents of TVAR for special texts used for highlighting. */ tvar_text = (char *) my_malloc (j_buf + 1, ERR_NO_MEMORY_AVAILABLE, __FILE__, ((long) __LINE__) - 2L, "tvar_text", 0); l = x = 0; LOOP { if (*(ptr_buf + l)) { if (*(ptr_buf + l) == RC_SPECIAL_TEXT_CHAR) { l++; switch (*(ptr_buf + l)) { case RC_HLS1S_CHAR: case RC_HLS1E_CHAR: case RC_HLS2S_CHAR: case RC_HLS2E_CHAR: case RC_HLS3S_CHAR: case RC_HLS3E_CHAR: case RC_HLS4S_CHAR: case RC_HLS4E_CHAR: case RC_HLS5S_CHAR: case RC_HLS5E_CHAR: if (quote) { quote = FALSE; x--; tvar_text[x++] = *(ptr_buf + l - 1); tvar_text[x++] = *(ptr_buf + l); } else num_hls++; break; default: tvar_text[x++] = *(ptr_buf + l - 1); tvar_text[x++] = *(ptr_buf + l); } } else { if (*(ptr_buf + l) == QUOTE_CHAR) quote = TRUE; else quote = FALSE; tvar_text[x++] = *(ptr_buf + l); } l++; } else { tvar_text[x] = '\0'; break; } } free (tvar_text); if (highlight_flag && (ehls1s.len == 1)) { fwidth += num_hls; j = MAX (fwidth, j_buf); } else { j_buf = x; j = MAX (fwidth, j_buf); j += (num_hls << 1); } } } else j = j_buf; if (j) { while ((Uint) k + j >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + n; } if (fwidth != SPECIAL_VALUE) (void) use_format (&s5, k, buf, atol (buf), is_sign | is_lzero | is_suffix, is_cformat, is_lformat, is_sign, is_lzero, is_suffix, is_fformat, fstyle, fwidth, j_buf); else strcat (s5, buf); } /* Skip TVAR name. */ len += (flen + 1); if (j) k += j; else /* If TVAR is "empty", remove a possibly obsolete whitespace. */ if (isspace (s5[k - 1]) && isspace (tvar[1])) s5[--k] = '\0'; } else restore_tvar = TRUE; } else restore_tvar = TRUE; /* If TVAR isn't defined, or quoted, or an invalid TVAR name is found, don't touch it. */ if (restore_tvar) { if ((Uint) k + 1 >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + n; } s5[k++] = RC_TVAR_CHAR; len++; if (*tvar && (flen == 1)) { if ((Uint) k + 1 >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + n; } s5[k++] = *tvar; len++; } s5[k] = '\0'; } n += len; ptr_char += len; ptr_tvar = strchr (ptr_char, RC_TVAR_CHAR); flen = 1; restore_tvar = is_quoted = FALSE; } while (ptr_tvar != (char *) NULL); /* Add possibly trailing ordinary text. */ if (*ptr_char) { k += (int) strlen (ptr_char); while ((Uint) k >= maxlen_max) { resize_all_strings (maxlen_max << 1, TRUE, __FILE__, (long) __LINE__); ptr_char = *line_buffer + n; } strcat (s5, ptr_char); } i = k++; strcpy (*line_buffer, s5); /* If the expansion results to a text variable assignment or operation, skip the expansion loop and perform the assignment/operation. */ if ((**line_buffer == RC_TVAR_CHAR) && isalpha (*(*line_buffer + 1)) && (*(*line_buffer + 2) == *RC_VAR_ASSIGN || *(*line_buffer + 2) == *RC_TVAR_ICMD_ASSIGN || *(*line_buffer + 2) == *RC_TVAR_UCMD_ASSIGN || *(*line_buffer + 2) == *RC_VAR_ADD || *(*line_buffer + 2) == *RC_VAR_SUB)) *is_tvar = ok = TRUE; /* Now check whether we have to analyse the line again in case text variables were expanded to texts which contain unquoted references of other text variables. */ n = 0; ptr_tvar = strchr (*line_buffer, RC_TVAR_CHAR); if (ptr_tvar != (char *) NULL) { do { if (!n && (**line_buffer != RC_TVAR_CHAR)) ptr_tvar--; else if (n) ptr_tvar--; *tvar = *ptr_tvar; if (!n && (**line_buffer != RC_TVAR_CHAR)) ptr_tvar++; else if (n) ptr_tvar++; ptr_tvar++; /* Check for a TVAR format. */ flen = decode_format (ptr_tvar, 0, &is_cformat, &is_lformat, &is_sign, &is_lzero, &is_suffix, &is_fformat, &fstyle, &fwidth); if (fwidth != SPECIAL_VALUE) ptr_tvar += flen; /* Check if a text variable reference is found which needs to be expanded again. */ if ((*tvar != QUOTE_CHAR) && isalpha (*ptr_tvar) && (rc_tvar[IDX (*ptr_tvar)].tvar_local. tvar_text != (char *) NULL || rc_tvar[IDX (*ptr_tvar)].tvar_global. tvar_text != (char *) NULL)) { /* Check if expansion results to invalid recursion. */ if (*ptr_tvar == the_tvar) ok = TRUE; else flen = 1; /* Text variable reference found which needs to be expanded again. */ break; } n = 1; while (*ptr_tvar == RC_TVAR_CHAR) ptr_tvar++; if (*ptr_tvar) ptr_tvar = strchr (ptr_tvar, RC_TVAR_CHAR); else ptr_tvar = (char *) NULL; } while (ptr_tvar != (char *) NULL); if (ptr_tvar == (char *) NULL) ok = TRUE; } else /* All text variable references already expanded. */ ok = TRUE; } else /* No text variable references found. */ ok = TRUE; /* If the expansion results to an include directive, skip the expansion loop and perform the assignment. */ if (**line_buffer == *RC_INCL_STMENT) *is_include = ok = TRUE; else /* If the expansion results to a date variable assignment, skip the expansion loop and perform the assignment. */ if (isalpha (**line_buffer)) *is_dvar = ok = TRUE; } while (!ok); } /* Check for a local date variable DVAR definition. */ if (*is_dvar) set_dvar (*line_buffer, lptrs3, filename, *line_number, LOcal); /* Check for a local text variable TVAR definition. */ if (*is_tvar) set_tvar (*line_buffer, filename, *line_number, LOcal); } #endif if (is_error) { #if USE_RC if (mode == REsource) /* Error, invalid date-"part" given. */ i = ERR_INVALID_DATE_FIELD; else #endif /* Error, illegal NUL character found in file. */ i = ERR_ILLEGAL_CHAR_IN_FILE; my_error (i, filename, *line_number, *line_buffer, 0); } if (ch == '\n') *line_length = i - 1; else *line_length = i; return (ptr_pool); } char **insert_response_file (fp, filename, opt_list, my_argc_max, my_argc, my_argv) FILE *fp; char *filename; const char *opt_list; Uint *my_argc_max; int *my_argc; char *my_argv[]; /*! Tries to manage a response file @FILE argument given in the command line. Inserts the options and commands found in file @FILE (name delivered in `filename' and its file pointer in `fp') into `my_argv[]' and sets delivered `&my_argc' and perhaps `&my_argc_max' to according "new" values. Uses the global text buffer `s1' internally. Returns the build `my_argv[]' ptr vector. */ { auto long line_number = 0L; auto int line_length; auto int in_pool = 0; auto char *pool = (char *) NULL; auto char *ptr_pool = (char *) NULL; auto Bool b_dummy; /* Necessary dummy for `file_read_line()' function. */ pool = (char *) my_malloc (BUF_LEN + 1, ERR_NO_MEMORY_AVAILABLE, __FILE__, ((long) __LINE__) - 1L, "pool", 0); while ((ptr_pool = file_read_line (fp, &s1, &in_pool, pool, ptr_pool, filename, &line_number, &line_length, REsponse, &b_dummy, &b_dummy, &b_dummy)) != (char *) NULL) if (*s1) { if ((*s1 == *SWITCH || *s1 == *SWITCH2) && s1[1] && (s1[1] != *SWITCH)) /* Short-style option found. */ if ((strchr (opt_list, s1[1]) != (char *) NULL) && isspace (s1[2])) { register int spaces = 1; /* Short-style option requires an argument, which could be separated by whitespace characters from the option character; respect this! This means all separating whitespace characters between the option character and argument will be eliminated. */ line_length = 2; while (s1[line_length + spaces] && isspace (s1[line_length + spaces])) /* Count the separating whitespace characters. */ spaces++; /* Store needed argument of option adjacent to option character. */ while (s1[line_length + spaces]) { s1[line_length] = s1[line_length + spaces]; line_length++; } s1[line_length] = '\0'; } /* Avoid one or two letter combinations of '-', '/' or '%' characters only! */ if (((line_length == 1) && (*s1 == *SWITCH #if USE_RC || *s1 == RC_ADATE_CHAR #endif || *s1 == *SWITCH2)) || ((line_length == 2) && (*s1 == *SWITCH #if USE_RC || *s1 == RC_ADATE_CHAR #endif || *s1 == *SWITCH2) && (s1[1] == *SWITCH #if USE_RC || s1[1] == RC_ADATE_CHAR #endif || s1[1] == *SWITCH2))) ; /* Void, don't allocate memory */ else { if ((Uint) * my_argc >= *my_argc_max) { /* Resize the `my_argv[]' table. */ *my_argc_max <<= 1; if (*my_argc_max * sizeof (char *) > testval) (*my_argc_max)--; my_argv = (char **) my_realloc ((VOID_PTR) my_argv, *my_argc_max * sizeof (char *), ERR_NO_MEMORY_AVAILABLE, __FILE__, ((long) __LINE__) - 3L, "my_argv[my_argc_max]", *my_argc_max); } my_argv[*my_argc] = (char *) my_malloc (line_length + 1, ERR_NO_MEMORY_AVAILABLE, __FILE__, ((long) __LINE__) - 2L, "my_argv[my_argc]", *my_argc); strcpy (my_argv[(*my_argc)++], s1); } } free (pool); return (my_argv); } void write_log_file (filename, mode, mode_txt, created_txt, argc, argv) const char *filename; const Fmode_enum mode; const char *mode_txt; const char *created_txt; const int argc; char *argv[]; /*! Writes the contents of the environment variable $GCAL, which is already stored in `argc' and the arguments of command line either into a response file (MODE==REsponse) or into a shell script (MODE==SCript); other settings to `mode' will `abort()' the program immediately. */ { auto FILE *fp = (FILE *) NULL; auto int len = 0; register int i = 0; fp = fopen (filename, "w"); if (fp != (FILE *) NULL) { switch (mode) { case REsponse: len = fprintf (fp, "%c `%s' %s `%s' --- %s %02d-%s-%04d %02d%s%02d%s%02d", REM_CHAR, prgr_name, mode_txt, filename, created_txt, true_day, short_month_name (true_month), true_year, act_hour, time_sep, act_min, time_sep, act_sec); if (tz != (char *) NULL) len = fprintf (fp, " %s", tz); len = fprintf (fp, "\n%c\n", REM_CHAR); break; #ifdef GCAL_SHELL case SCript: # if HAVE_SYS_INTERPRETER len = fprintf (fp, "%c%s\n%c\n%c `%s' %s `%s' --- %s %02d-%s-%04d %02d%s%02d%s%02d", *SHL_REM, SHELL, *SHL_REM, *SHL_REM, prgr_name, mode_txt, filename, created_txt, true_day, short_month_name (true_month), true_year, act_hour, time_sep, act_min, time_sep, act_sec); # else /* !HAVE_SYS_INTERPRETER */ len = fprintf (fp, "%c `%s' %s `%s' --- %s %02d-%s-%04 %02d%s%02d%s%02d", *SHL_REM, prgr_name, mode_txt, filename, created_txt, true_day, short_month_name (true_month), true_year, act_hour, time_sep, act_min, time_sep, act_sec); # endif /* !HAVE_SYS_INTERPRETER */ if (tz != (char *) NULL) len = fprintf (fp, " %s", tz); len = fprintf (fp, "\n%c\n%s %c\n", *SHL_REM, prgr_name, *SHL_ESC); break; #endif /* GCAL_SHELL */ default: /* This case MUST be an internal error! */ abort (); } if (len != EOF) { for (i = 1; i < argc; i++) { /* Don't write the name of a response file or of a shell script into the response file! */ if (*argv[i] == *SWITCH || *argv[i] == *SWITCH2) { /* If the short-style option -R<NAME> or -S<NAME> is given, skip it! */ if (*(argv[i] + 1) == 'R' #ifdef GCAL_SHELL || *(argv[i] + 1) == 'S' #endif ) continue; if (*(argv[i] + 1) == *SWITCH) { /* Detect whether the long-style option `--response-file=ARG' or `--shell-script=ARG' is given and if found, don't write this option itself into the response file! */ strcpy (s4, argv[i] + 2); (void) eval_longopt (s4, &len); if (len == SYM_RESPONSE_FILE) continue; #ifdef GCAL_SHELL if (len == SYM_SCRIPT_FILE) continue; #endif } } if (*argv[i] == RSP_CHAR) /* Avoid to write a response file @FILE argument into the resulting file. */ continue; switch (mode) { case REsponse: len = fprintf (fp, "%s\n", argv[i]); break; #ifdef GCAL_SHELL case SCript: len = fprintf (fp, "'%s' %c\n", argv[i], *SHL_ESC); break; #endif default: /* This case can't occur anymore, if so, it MUST be an internal error! */ abort (); } if (len == EOF) break; } #ifdef GCAL_SHELL if (mode == SCript) len = fprintf (fp, " $*\n"); #endif i = fclose (fp); } } else len = EOF; if (i == EOF) len = EOF; if (((len != EOF) && (warning_level == 1)) || ((len == EOF) && (warning_level == 2)) || warning_level > 2) { i = (int) strlen (filename) + MAX (ehls1s.len, ehls2s.len) + MAX (ehls1e.len, ehls2e.len) + LEN_SINGLE_LINE; if ((Uint) i >= maxlen_max) resize_all_strings (i + 1, FALSE, __FILE__, (long) __LINE__); sprintf (s4, _("Try to write %s `%s'... %s%s%s"), mode_txt, filename, (ehls1s.len != 1) ? ((len == EOF) ? ehls2s.seq : ehls1s.seq) : "", (len == EOF) ? _("failed") : _("success"), (ehls1s.len != 1) ? ((len == EOF) ? ehls2e.seq : ehls1e.seq) : ""); print_text (stderr, s4); /* Terminate the program in case the file can't be written! */ if ((len == EOF) && (warning_level >= WARN_LVL_MAX)) my_error (ERR_WRITE_FILE, __FILE__, (long) __LINE__, filename, 0); } #ifdef GCAL_SHELL if ((mode == SCript) && (len != EOF)) { /* Try to make the created shell script executable! */ i = (int) strlen (filename) + strlen (CHMOD_PRGR) + strlen (CHMOD_OPTS) + 2; if ((Uint) i >= maxlen_max) resize_all_strings (i + 1, FALSE, __FILE__, (long) __LINE__); sprintf (s4, "%s %s %s", CHMOD_PRGR, CHMOD_OPTS, filename); /* And ignore any errors... */ (void) my_system (s4); } #endif /* GCAL_SHELL */ } static void make_absolute_filename (absolute_filename, directory, filename) char **absolute_filename; const char *directory; const char *filename; /*! Creates an absolute file name (directory+file name) of a delivered file name and directory and returns it in delivered `&absolute_filename'. */ { register int dir_len = (int) strlen (directory); register int fil_len = (int) strlen (filename); if (directory[dir_len - 1] != *DIR_SEP) dir_len++; if ((Uint) dir_len + fil_len >= maxlen_max) resize_all_strings (dir_len + fil_len + 1, FALSE, __FILE__, (long) __LINE__); strcpy (*absolute_filename, directory); if (directory[dir_len - 1] != *DIR_SEP) strcat (*absolute_filename, DIR_SEP); strcat (*absolute_filename, filename); } static FILE *get_file_ptr (fp, filename, level, mode, is_first) FILE *fp; const char *filename; const int level; const Fmode_enum mode; Bool *is_first; /*! Tries to open the file (with optional diagnostic messages on STDERR channel in case the `--debug[=0...WARN_LVL_MAX]' option is set) and returns a valid file pointer of that file, or NULL if this fails. */ { #if HAVE_SYS_STAT_H && defined(S_IFMT) && defined(S_IFREG) auto struct stat statbuf; fp = (FILE *) NULL; /* Check whether STDIN channel is wanted. */ if ((*filename == '-') && (strlen (filename) == 1)) fp = stdin; else /* Test if the file is a regular file, if not, ignore it! */ if (!stat (filename, &statbuf)) if ((statbuf.st_mode & S_IFMT) == S_IFREG) fp = fopen (filename, "r"); #else /* !HAVE_SYS_STAT_H || !S_IFMT || !S_IFREG */ if ((*filename == '-') && (strlen (filename) == 1)) fp = stdin; else fp = fopen (filename, "r"); #endif /* !HAVE_SYS_STAT_H || !S_IFMT || !S_IFREG */ if ((warning_level >= 0) && (mode != REsponse) && (mode != COmmon)) #if USE_RC { if (((fp != (FILE *) NULL) && (warning_level == 1)) || ((fp == (FILE *) NULL) && (warning_level == 2)) || warning_level > 2) { register int i; /* If this function is entered the first time: Print a leading NEWLINE character before any information texts. */ if (*is_first) { *is_first = FALSE; *s4 = '\0'; print_text (stderr, s4); } i = (int) strlen (filename) + MAX (ehls1s.len, ehls2s.len) + MAX (ehls1e.len, ehls2e.len) + LEN_SINGLE_LINE; if ((Uint) i >= maxlen_max) resize_all_strings (i + 1, FALSE, __FILE__, (long) __LINE__); if (mode == REsource || mode == HEre) sprintf (s4, _("Try to open%sresource file `%s'... %s%s%s"), (mode == REsource) ? " " : _(" `HERE' "), filename, (ehls1s.len != 1) ? ((fp == (FILE *) NULL) ? ehls2s.seq : ehls1s.seq) : "", (fp == (FILE *) NULL) ? _("failed") : _("success"), (ehls1s.len != 1) ? ((fp == (FILE *) NULL) ? ehls2e.seq : ehls1e. seq) : ""); else sprintf (s4, _ ("Try to open (level: %02d) include file `%s'... %s%s%s"), level, filename, (ehls1s.len != 1) ? ((fp == (FILE *) NULL) ? ehls2s.seq : ehls1s.seq) : "", (fp == (FILE *) NULL) ? _("failed") : _("success"), (ehls1s.len != 1) ? ((fp == (FILE *) NULL) ? ehls2e.seq : ehls1e. seq) : ""); print_text (stderr, s4); } } #else /* !USE_RC */ ; /* Void, no text to display */ #endif /* !USE_RC */ return (fp); }
26.000582
91
0.552449
[ "vector" ]
d98023f55503881c3d7e177b1112686f0ef8b5c0
20,896
c
C
kernel/2.6.32/arch/arm/mach-pxa/spitz.c
haizhenhan/Kepler
d15293a7ef69f44b1fe61d5cdeceb0bd73f0d315
[ "BSD-3-Clause" ]
55
2015-01-20T00:09:45.000Z
2021-08-19T05:40:27.000Z
linux/linux-2.6.32/arch/arm/mach-pxa/spitz.c
jwegan/TCP-RST-Guard
8734350ef09b0cd79e72797ffa009d75441886bb
[ "MIT" ]
1
2017-04-22T18:17:57.000Z
2017-09-15T11:28:26.000Z
linux/linux-2.6.32/arch/arm/mach-pxa/spitz.c
jwegan/TCP-RST-Guard
8734350ef09b0cd79e72797ffa009d75441886bb
[ "MIT" ]
36
2015-02-13T00:58:22.000Z
2021-08-19T08:08:07.000Z
/* * Support for Sharp SL-Cxx00 Series of PDAs * Models: SL-C3000 (Spitz), SL-C1000 (Akita) and SL-C3100 (Borzoi) * * Copyright (c) 2005 Richard Purdie * * Based on Sharp's 2.4 kernel patches/lubbock.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/gpio_keys.h> #include <linux/gpio.h> #include <linux/leds.h> #include <linux/mtd/physmap.h> #include <linux/i2c.h> #include <linux/i2c/pca953x.h> #include <linux/spi/spi.h> #include <linux/spi/ads7846.h> #include <linux/spi/corgi_lcd.h> #include <linux/mtd/sharpsl.h> #include <linux/input/matrix_keypad.h> #include <asm/setup.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/sharpsl_param.h> #include <asm/hardware/scoop.h> #include <mach/pxa27x.h> #include <mach/pxa27x-udc.h> #include <mach/reset.h> #include <plat/i2c.h> #include <mach/irda.h> #include <mach/mmc.h> #include <mach/ohci.h> #include <mach/pxafb.h> #include <mach/pxa2xx_spi.h> #include <mach/spitz.h> #include "generic.h" #include "devices.h" #include "sharpsl.h" static unsigned long spitz_pin_config[] __initdata = { /* Chip Selects */ GPIO78_nCS_2, /* SCOOP #2 */ GPIO79_nCS_3, /* NAND */ GPIO80_nCS_4, /* SCOOP #1 */ /* LCD - 16bpp Active TFT */ GPIO58_LCD_LDD_0, GPIO59_LCD_LDD_1, GPIO60_LCD_LDD_2, GPIO61_LCD_LDD_3, GPIO62_LCD_LDD_4, GPIO63_LCD_LDD_5, GPIO64_LCD_LDD_6, GPIO65_LCD_LDD_7, GPIO66_LCD_LDD_8, GPIO67_LCD_LDD_9, GPIO68_LCD_LDD_10, GPIO69_LCD_LDD_11, GPIO70_LCD_LDD_12, GPIO71_LCD_LDD_13, GPIO72_LCD_LDD_14, GPIO73_LCD_LDD_15, GPIO74_LCD_FCLK, GPIO75_LCD_LCLK, GPIO76_LCD_PCLK, /* PC Card */ GPIO48_nPOE, GPIO49_nPWE, GPIO50_nPIOR, GPIO51_nPIOW, GPIO85_nPCE_1, GPIO54_nPCE_2, GPIO55_nPREG, GPIO56_nPWAIT, GPIO57_nIOIS16, GPIO104_PSKTSEL, /* I2S */ GPIO28_I2S_BITCLK_OUT, GPIO29_I2S_SDATA_IN, GPIO30_I2S_SDATA_OUT, GPIO31_I2S_SYNC, /* MMC */ GPIO32_MMC_CLK, GPIO112_MMC_CMD, GPIO92_MMC_DAT_0, GPIO109_MMC_DAT_1, GPIO110_MMC_DAT_2, GPIO111_MMC_DAT_3, /* GPIOs */ GPIO9_GPIO, /* SPITZ_GPIO_nSD_DETECT */ GPIO81_GPIO, /* SPITZ_GPIO_nSD_WP */ GPIO41_GPIO, /* SPITZ_GPIO_USB_CONNECT */ GPIO37_GPIO, /* SPITZ_GPIO_USB_HOST */ GPIO35_GPIO, /* SPITZ_GPIO_USB_DEVICE */ GPIO22_GPIO, /* SPITZ_GPIO_HSYNC */ GPIO94_GPIO, /* SPITZ_GPIO_CF_CD */ GPIO105_GPIO, /* SPITZ_GPIO_CF_IRQ */ GPIO106_GPIO, /* SPITZ_GPIO_CF2_IRQ */ /* GPIO matrix keypad */ GPIO88_GPIO, /* column 0 */ GPIO23_GPIO, /* column 1 */ GPIO24_GPIO, /* column 2 */ GPIO25_GPIO, /* column 3 */ GPIO26_GPIO, /* column 4 */ GPIO27_GPIO, /* column 5 */ GPIO52_GPIO, /* column 6 */ GPIO103_GPIO, /* column 7 */ GPIO107_GPIO, /* column 8 */ GPIO108_GPIO, /* column 9 */ GPIO114_GPIO, /* column 10 */ GPIO12_GPIO, /* row 0 */ GPIO17_GPIO, /* row 1 */ GPIO91_GPIO, /* row 2 */ GPIO34_GPIO, /* row 3 */ GPIO36_GPIO, /* row 4 */ GPIO38_GPIO, /* row 5 */ GPIO39_GPIO, /* row 6 */ /* I2C */ GPIO117_I2C_SCL, GPIO118_I2C_SDA, GPIO1_GPIO | WAKEUP_ON_EDGE_RISE, }; /* * Spitz SCOOP Device #1 */ static struct resource spitz_scoop_resources[] = { [0] = { .start = 0x10800000, .end = 0x10800fff, .flags = IORESOURCE_MEM, }, }; static struct scoop_config spitz_scoop_setup = { .io_dir = SPITZ_SCP_IO_DIR, .io_out = SPITZ_SCP_IO_OUT, .suspend_clr = SPITZ_SCP_SUS_CLR, .suspend_set = SPITZ_SCP_SUS_SET, .gpio_base = SPITZ_SCP_GPIO_BASE, }; struct platform_device spitzscoop_device = { .name = "sharp-scoop", .id = 0, .dev = { .platform_data = &spitz_scoop_setup, }, .num_resources = ARRAY_SIZE(spitz_scoop_resources), .resource = spitz_scoop_resources, }; /* * Spitz SCOOP Device #2 */ static struct resource spitz_scoop2_resources[] = { [0] = { .start = 0x08800040, .end = 0x08800fff, .flags = IORESOURCE_MEM, }, }; static struct scoop_config spitz_scoop2_setup = { .io_dir = SPITZ_SCP2_IO_DIR, .io_out = SPITZ_SCP2_IO_OUT, .suspend_clr = SPITZ_SCP2_SUS_CLR, .suspend_set = SPITZ_SCP2_SUS_SET, .gpio_base = SPITZ_SCP2_GPIO_BASE, }; struct platform_device spitzscoop2_device = { .name = "sharp-scoop", .id = 1, .dev = { .platform_data = &spitz_scoop2_setup, }, .num_resources = ARRAY_SIZE(spitz_scoop2_resources), .resource = spitz_scoop2_resources, }; #define SPITZ_PWR_SD 0x01 #define SPITZ_PWR_CF 0x02 /* Power control is shared with between one of the CF slots and SD */ static void spitz_card_pwr_ctrl(int device, unsigned short new_cpr) { unsigned short cpr = read_scoop_reg(&spitzscoop_device.dev, SCOOP_CPR); if (new_cpr & 0x0007) { gpio_set_value(SPITZ_GPIO_CF_POWER, 1); if (!(cpr & 0x0002) && !(cpr & 0x0004)) mdelay(5); if (device == SPITZ_PWR_CF) cpr |= 0x0002; if (device == SPITZ_PWR_SD) cpr |= 0x0004; write_scoop_reg(&spitzscoop_device.dev, SCOOP_CPR, cpr | new_cpr); } else { if (device == SPITZ_PWR_CF) cpr &= ~0x0002; if (device == SPITZ_PWR_SD) cpr &= ~0x0004; if (!(cpr & 0x0002) && !(cpr & 0x0004)) { write_scoop_reg(&spitzscoop_device.dev, SCOOP_CPR, 0x0000); mdelay(1); gpio_set_value(SPITZ_GPIO_CF_POWER, 0); } else { write_scoop_reg(&spitzscoop_device.dev, SCOOP_CPR, cpr | new_cpr); } } } static void spitz_pcmcia_pwr(struct device *scoop, unsigned short cpr, int nr) { /* Only need to override behaviour for slot 0 */ if (nr == 0) spitz_card_pwr_ctrl(SPITZ_PWR_CF, cpr); else write_scoop_reg(scoop, SCOOP_CPR, cpr); } static struct scoop_pcmcia_dev spitz_pcmcia_scoop[] = { { .dev = &spitzscoop_device.dev, .irq = SPITZ_IRQ_GPIO_CF_IRQ, .cd_irq = SPITZ_IRQ_GPIO_CF_CD, .cd_irq_str = "PCMCIA0 CD", },{ .dev = &spitzscoop2_device.dev, .irq = SPITZ_IRQ_GPIO_CF2_IRQ, .cd_irq = -1, }, }; static struct scoop_pcmcia_config spitz_pcmcia_config = { .devs = &spitz_pcmcia_scoop[0], .num_devs = 2, .power_ctrl = spitz_pcmcia_pwr, }; EXPORT_SYMBOL(spitzscoop_device); EXPORT_SYMBOL(spitzscoop2_device); /* * Spitz Keyboard Device */ #define SPITZ_KEY_CALENDAR KEY_F1 #define SPITZ_KEY_ADDRESS KEY_F2 #define SPITZ_KEY_FN KEY_F3 #define SPITZ_KEY_CANCEL KEY_F4 #define SPITZ_KEY_EXOK KEY_F5 #define SPITZ_KEY_EXCANCEL KEY_F6 #define SPITZ_KEY_EXJOGDOWN KEY_F7 #define SPITZ_KEY_EXJOGUP KEY_F8 #define SPITZ_KEY_JAP1 KEY_LEFTALT #define SPITZ_KEY_JAP2 KEY_RIGHTCTRL #define SPITZ_KEY_SYNC KEY_F9 #define SPITZ_KEY_MAIL KEY_F10 #define SPITZ_KEY_OK KEY_F11 #define SPITZ_KEY_MENU KEY_F12 static const uint32_t spitzkbd_keymap[] = { KEY(0, 0, KEY_LEFTCTRL), KEY(0, 1, KEY_1), KEY(0, 2, KEY_3), KEY(0, 3, KEY_5), KEY(0, 4, KEY_6), KEY(0, 5, KEY_7), KEY(0, 6, KEY_9), KEY(0, 7, KEY_0), KEY(0, 8, KEY_BACKSPACE), KEY(0, 9, SPITZ_KEY_EXOK), /* EXOK */ KEY(0, 10, SPITZ_KEY_EXCANCEL), /* EXCANCEL */ KEY(1, 1, KEY_2), KEY(1, 2, KEY_4), KEY(1, 3, KEY_R), KEY(1, 4, KEY_Y), KEY(1, 5, KEY_8), KEY(1, 6, KEY_I), KEY(1, 7, KEY_O), KEY(1, 8, KEY_P), KEY(1, 9, SPITZ_KEY_EXJOGDOWN), /* EXJOGDOWN */ KEY(1, 10, SPITZ_KEY_EXJOGUP), /* EXJOGUP */ KEY(2, 0, KEY_TAB), KEY(2, 1, KEY_Q), KEY(2, 2, KEY_E), KEY(2, 3, KEY_T), KEY(2, 4, KEY_G), KEY(2, 5, KEY_U), KEY(2, 6, KEY_J), KEY(2, 7, KEY_K), KEY(3, 0, SPITZ_KEY_ADDRESS), /* ADDRESS */ KEY(3, 1, KEY_W), KEY(3, 2, KEY_S), KEY(3, 3, KEY_F), KEY(3, 4, KEY_V), KEY(3, 5, KEY_H), KEY(3, 6, KEY_M), KEY(3, 7, KEY_L), KEY(3, 9, KEY_RIGHTSHIFT), KEY(4, 0, SPITZ_KEY_CALENDAR), /* CALENDAR */ KEY(4, 1, KEY_A), KEY(4, 2, KEY_D), KEY(4, 3, KEY_C), KEY(4, 4, KEY_B), KEY(4, 5, KEY_N), KEY(4, 6, KEY_DOT), KEY(4, 8, KEY_ENTER), KEY(4, 9, KEY_LEFTSHIFT), KEY(5, 0, SPITZ_KEY_MAIL), /* MAIL */ KEY(5, 1, KEY_Z), KEY(5, 2, KEY_X), KEY(5, 3, KEY_MINUS), KEY(5, 4, KEY_SPACE), KEY(5, 5, KEY_COMMA), KEY(5, 7, KEY_UP), KEY(5, 10, SPITZ_KEY_FN), /* FN */ KEY(6, 0, KEY_SYSRQ), KEY(6, 1, SPITZ_KEY_JAP1), /* JAP1 */ KEY(6, 2, SPITZ_KEY_JAP2), /* JAP2 */ KEY(6, 3, SPITZ_KEY_CANCEL), /* CANCEL */ KEY(6, 4, SPITZ_KEY_OK), /* OK */ KEY(6, 5, SPITZ_KEY_MENU), /* MENU */ KEY(6, 6, KEY_LEFT), KEY(6, 7, KEY_DOWN), KEY(6, 8, KEY_RIGHT), }; static const struct matrix_keymap_data spitzkbd_keymap_data = { .keymap = spitzkbd_keymap, .keymap_size = ARRAY_SIZE(spitzkbd_keymap), }; static const uint32_t spitzkbd_row_gpios[] = { 12, 17, 91, 34, 36, 38, 39 }; static const uint32_t spitzkbd_col_gpios[] = { 88, 23, 24, 25, 26, 27, 52, 103, 107, 108, 114 }; static struct matrix_keypad_platform_data spitzkbd_pdata = { .keymap_data = &spitzkbd_keymap_data, .row_gpios = spitzkbd_row_gpios, .col_gpios = spitzkbd_col_gpios, .num_row_gpios = ARRAY_SIZE(spitzkbd_row_gpios), .num_col_gpios = ARRAY_SIZE(spitzkbd_col_gpios), .col_scan_delay_us = 10, .debounce_ms = 10, .wakeup = 1, }; static struct platform_device spitzkbd_device = { .name = "matrix-keypad", .id = -1, .dev = { .platform_data = &spitzkbd_pdata, }, }; static struct gpio_keys_button spitz_gpio_keys[] = { { .type = EV_PWR, .code = KEY_SUSPEND, .gpio = SPITZ_GPIO_ON_KEY, .desc = "On/Off", .wakeup = 1, }, /* Two buttons detecting the lid state */ { .type = EV_SW, .code = 0, .gpio = SPITZ_GPIO_SWA, .desc = "Display Down", }, { .type = EV_SW, .code = 1, .gpio = SPITZ_GPIO_SWB, .desc = "Lid Closed", }, }; static struct gpio_keys_platform_data spitz_gpio_keys_platform_data = { .buttons = spitz_gpio_keys, .nbuttons = ARRAY_SIZE(spitz_gpio_keys), }; static struct platform_device spitz_gpio_keys_device = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &spitz_gpio_keys_platform_data, }, }; /* * Spitz LEDs */ static struct gpio_led spitz_gpio_leds[] = { { .name = "spitz:amber:charge", .default_trigger = "sharpsl-charge", .gpio = SPITZ_GPIO_LED_ORANGE, }, { .name = "spitz:green:hddactivity", .default_trigger = "ide-disk", .gpio = SPITZ_GPIO_LED_GREEN, }, }; static struct gpio_led_platform_data spitz_gpio_leds_info = { .leds = spitz_gpio_leds, .num_leds = ARRAY_SIZE(spitz_gpio_leds), }; static struct platform_device spitzled_device = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &spitz_gpio_leds_info, }, }; #if defined(CONFIG_SPI_PXA2XX) || defined(CONFIG_SPI_PXA2XX_MODULE) static struct pxa2xx_spi_master spitz_spi_info = { .num_chipselect = 3, }; static void spitz_wait_for_hsync(void) { while (gpio_get_value(SPITZ_GPIO_HSYNC)) cpu_relax(); while (!gpio_get_value(SPITZ_GPIO_HSYNC)) cpu_relax(); } static struct ads7846_platform_data spitz_ads7846_info = { .model = 7846, .vref_delay_usecs = 100, .x_plate_ohms = 419, .y_plate_ohms = 486, .pressure_max = 1024, .gpio_pendown = SPITZ_GPIO_TP_INT, .wait_for_sync = spitz_wait_for_hsync, }; static struct pxa2xx_spi_chip spitz_ads7846_chip = { .gpio_cs = SPITZ_GPIO_ADS7846_CS, }; static void spitz_bl_kick_battery(void) { void (*kick_batt)(void); kick_batt = symbol_get(sharpsl_battery_kick); if (kick_batt) { kick_batt(); symbol_put(sharpsl_battery_kick); } } static struct corgi_lcd_platform_data spitz_lcdcon_info = { .init_mode = CORGI_LCD_MODE_VGA, .max_intensity = 0x2f, .default_intensity = 0x1f, .limit_mask = 0x0b, .gpio_backlight_cont = SPITZ_GPIO_BACKLIGHT_CONT, .gpio_backlight_on = SPITZ_GPIO_BACKLIGHT_ON, .kick_battery = spitz_bl_kick_battery, }; static struct pxa2xx_spi_chip spitz_lcdcon_chip = { .gpio_cs = SPITZ_GPIO_LCDCON_CS, }; static struct pxa2xx_spi_chip spitz_max1111_chip = { .gpio_cs = SPITZ_GPIO_MAX1111_CS, }; static struct spi_board_info spitz_spi_devices[] = { { .modalias = "ads7846", .max_speed_hz = 1200000, .bus_num = 2, .chip_select = 0, .platform_data = &spitz_ads7846_info, .controller_data= &spitz_ads7846_chip, .irq = gpio_to_irq(SPITZ_GPIO_TP_INT), }, { .modalias = "corgi-lcd", .max_speed_hz = 50000, .bus_num = 2, .chip_select = 1, .platform_data = &spitz_lcdcon_info, .controller_data= &spitz_lcdcon_chip, }, { .modalias = "max1111", .max_speed_hz = 450000, .bus_num = 2, .chip_select = 2, .controller_data= &spitz_max1111_chip, }, }; static void __init spitz_init_spi(void) { if (machine_is_akita()) { spitz_lcdcon_info.gpio_backlight_cont = AKITA_GPIO_BACKLIGHT_CONT; spitz_lcdcon_info.gpio_backlight_on = AKITA_GPIO_BACKLIGHT_ON; } pxa2xx_set_spi_info(2, &spitz_spi_info); spi_register_board_info(ARRAY_AND_SIZE(spitz_spi_devices)); } #else static inline void spitz_init_spi(void) {} #endif /* * MMC/SD Device * * The card detect interrupt isn't debounced so we delay it by 250ms * to give the card a chance to fully insert/eject. */ static void spitz_mci_setpower(struct device *dev, unsigned int vdd) { struct pxamci_platform_data* p_d = dev->platform_data; if (( 1 << vdd) & p_d->ocr_mask) spitz_card_pwr_ctrl(SPITZ_PWR_SD, 0x0004); else spitz_card_pwr_ctrl(SPITZ_PWR_SD, 0x0000); } static struct pxamci_platform_data spitz_mci_platform_data = { .ocr_mask = MMC_VDD_32_33|MMC_VDD_33_34, .setpower = spitz_mci_setpower, .gpio_card_detect = SPITZ_GPIO_nSD_DETECT, .gpio_card_ro = SPITZ_GPIO_nSD_WP, .gpio_power = -1, }; /* * USB Host (OHCI) */ static int spitz_ohci_init(struct device *dev) { int err; err = gpio_request(SPITZ_GPIO_USB_HOST, "USB_HOST"); if (err) return err; /* Only Port 2 is connected * Setup USB Port 2 Output Control Register */ UP2OCR = UP2OCR_HXS | UP2OCR_HXOE | UP2OCR_DPPDE | UP2OCR_DMPDE; return gpio_direction_output(SPITZ_GPIO_USB_HOST, 1); } static void spitz_ohci_exit(struct device *dev) { gpio_free(SPITZ_GPIO_USB_HOST); } static struct pxaohci_platform_data spitz_ohci_platform_data = { .port_mode = PMM_NPS_MODE, .init = spitz_ohci_init, .exit = spitz_ohci_exit, .flags = ENABLE_PORT_ALL | NO_OC_PROTECTION, .power_budget = 150, }; /* * Irda */ static struct pxaficp_platform_data spitz_ficp_platform_data = { /* .gpio_pwdown is set in spitz_init() and akita_init() accordingly */ .transceiver_cap = IR_SIRMODE | IR_OFF, }; /* * Spitz PXA Framebuffer */ static struct pxafb_mode_info spitz_pxafb_modes[] = { { .pixclock = 19231, .xres = 480, .yres = 640, .bpp = 16, .hsync_len = 40, .left_margin = 46, .right_margin = 125, .vsync_len = 3, .upper_margin = 1, .lower_margin = 0, .sync = 0, },{ .pixclock = 134617, .xres = 240, .yres = 320, .bpp = 16, .hsync_len = 20, .left_margin = 20, .right_margin = 46, .vsync_len = 2, .upper_margin = 1, .lower_margin = 0, .sync = 0, }, }; static struct pxafb_mach_info spitz_pxafb_info = { .modes = &spitz_pxafb_modes[0], .num_modes = 2, .fixed_modes = 1, .lcd_conn = LCD_COLOR_TFT_16BPP | LCD_ALTERNATE_MAPPING, }; static struct mtd_partition sharpsl_nand_partitions[] = { { .name = "System Area", .offset = 0, .size = 7 * 1024 * 1024, }, { .name = "Root Filesystem", .offset = 7 * 1024 * 1024, }, { .name = "Home Filesystem", .offset = MTDPART_OFS_APPEND, .size = MTDPART_SIZ_FULL, }, }; static uint8_t scan_ff_pattern[] = { 0xff, 0xff }; static struct nand_bbt_descr sharpsl_bbt = { .options = 0, .offs = 4, .len = 2, .pattern = scan_ff_pattern }; static struct sharpsl_nand_platform_data sharpsl_nand_platform_data = { .badblock_pattern = &sharpsl_bbt, .partitions = sharpsl_nand_partitions, .nr_partitions = ARRAY_SIZE(sharpsl_nand_partitions), }; static struct resource sharpsl_nand_resources[] = { { .start = 0x0C000000, .end = 0x0C000FFF, .flags = IORESOURCE_MEM, }, }; static struct platform_device sharpsl_nand_device = { .name = "sharpsl-nand", .id = -1, .resource = sharpsl_nand_resources, .num_resources = ARRAY_SIZE(sharpsl_nand_resources), .dev.platform_data = &sharpsl_nand_platform_data, }; static struct mtd_partition sharpsl_rom_parts[] = { { .name ="Boot PROM Filesystem", .offset = 0x00140000, .size = MTDPART_SIZ_FULL, }, }; static struct physmap_flash_data sharpsl_rom_data = { .width = 2, .nr_parts = ARRAY_SIZE(sharpsl_rom_parts), .parts = sharpsl_rom_parts, }; static struct resource sharpsl_rom_resources[] = { { .start = 0x00000000, .end = 0x007fffff, .flags = IORESOURCE_MEM, }, }; static struct platform_device sharpsl_rom_device = { .name = "physmap-flash", .id = -1, .resource = sharpsl_rom_resources, .num_resources = ARRAY_SIZE(sharpsl_rom_resources), .dev.platform_data = &sharpsl_rom_data, }; static struct platform_device *devices[] __initdata = { &spitzscoop_device, &spitzkbd_device, &spitz_gpio_keys_device, &spitzled_device, &sharpsl_nand_device, &sharpsl_rom_device, }; static void spitz_poweroff(void) { arm_machine_restart('g', NULL); } static void spitz_restart(char mode, const char *cmd) { /* Bootloader magic for a reboot */ if((MSC0 & 0xffff0000) == 0x7ff00000) MSC0 = (MSC0 & 0xffff) | 0x7ee00000; spitz_poweroff(); } static void __init common_init(void) { init_gpio_reset(SPITZ_GPIO_ON_RESET, 1, 0); pm_power_off = spitz_poweroff; arm_pm_restart = spitz_restart; if (machine_is_spitz()) { sharpsl_nand_partitions[1].size = 5 * 1024 * 1024; } else if (machine_is_akita()) { sharpsl_nand_partitions[1].size = 58 * 1024 * 1024; } else if (machine_is_borzoi()) { sharpsl_nand_partitions[1].size = 32 * 1024 * 1024; } PMCR = 0x00; /* Stop 3.6MHz and drive HIGH to PCMCIA and CS */ PCFR |= PCFR_OPDE; pxa2xx_mfp_config(ARRAY_AND_SIZE(spitz_pin_config)); spitz_init_spi(); platform_add_devices(devices, ARRAY_SIZE(devices)); spitz_mci_platform_data.detect_delay = msecs_to_jiffies(250); pxa_set_mci_info(&spitz_mci_platform_data); pxa_set_ohci_info(&spitz_ohci_platform_data); pxa_set_ficp_info(&spitz_ficp_platform_data); set_pxa_fb_info(&spitz_pxafb_info); pxa_set_i2c_info(NULL); } #if defined(CONFIG_MACH_AKITA) || defined(CONFIG_MACH_BORZOI) static struct nand_bbt_descr sharpsl_akita_bbt = { .options = 0, .offs = 4, .len = 1, .pattern = scan_ff_pattern }; static struct nand_ecclayout akita_oobinfo = { .eccbytes = 24, .eccpos = { 0x5, 0x1, 0x2, 0x3, 0x6, 0x7, 0x15, 0x11, 0x12, 0x13, 0x16, 0x17, 0x25, 0x21, 0x22, 0x23, 0x26, 0x27, 0x35, 0x31, 0x32, 0x33, 0x36, 0x37}, .oobfree = {{0x08, 0x09}} }; #endif #if defined(CONFIG_MACH_SPITZ) || defined(CONFIG_MACH_BORZOI) static void __init spitz_init(void) { spitz_ficp_platform_data.gpio_pwdown = SPITZ_GPIO_IR_ON; #ifdef CONFIG_MACH_BORZOI if (machine_is_borzoi()) { sharpsl_nand_platform_data.badblock_pattern = &sharpsl_akita_bbt; sharpsl_nand_platform_data.ecc_layout = &akita_oobinfo; } #endif platform_scoop_config = &spitz_pcmcia_config; common_init(); platform_device_register(&spitzscoop2_device); } #endif #ifdef CONFIG_MACH_AKITA /* * Akita IO Expander */ static struct pca953x_platform_data akita_ioexp = { .gpio_base = AKITA_IOEXP_GPIO_BASE, }; static struct i2c_board_info akita_i2c_board_info[] = { { .type = "max7310", .addr = 0x18, .platform_data = &akita_ioexp, }, }; static void __init akita_init(void) { spitz_ficp_platform_data.gpio_pwdown = AKITA_GPIO_IR_ON; sharpsl_nand_platform_data.badblock_pattern = &sharpsl_akita_bbt; sharpsl_nand_platform_data.ecc_layout = &akita_oobinfo; /* We just pretend the second element of the array doesn't exist */ spitz_pcmcia_config.num_devs = 1; platform_scoop_config = &spitz_pcmcia_config; i2c_register_board_info(0, ARRAY_AND_SIZE(akita_i2c_board_info)); common_init(); } #endif static void __init fixup_spitz(struct machine_desc *desc, struct tag *tags, char **cmdline, struct meminfo *mi) { sharpsl_save_param(); mi->nr_banks = 1; mi->bank[0].start = 0xa0000000; mi->bank[0].node = 0; mi->bank[0].size = (64*1024*1024); } #ifdef CONFIG_MACH_SPITZ MACHINE_START(SPITZ, "SHARP Spitz") .phys_io = 0x40000000, .io_pg_offst = (io_p2v(0x40000000) >> 18) & 0xfffc, .fixup = fixup_spitz, .map_io = pxa_map_io, .init_irq = pxa27x_init_irq, .init_machine = spitz_init, .timer = &pxa_timer, MACHINE_END #endif #ifdef CONFIG_MACH_BORZOI MACHINE_START(BORZOI, "SHARP Borzoi") .phys_io = 0x40000000, .io_pg_offst = (io_p2v(0x40000000) >> 18) & 0xfffc, .fixup = fixup_spitz, .map_io = pxa_map_io, .init_irq = pxa27x_init_irq, .init_machine = spitz_init, .timer = &pxa_timer, MACHINE_END #endif #ifdef CONFIG_MACH_AKITA MACHINE_START(AKITA, "SHARP Akita") .phys_io = 0x40000000, .io_pg_offst = (io_p2v(0x40000000) >> 18) & 0xfffc, .fixup = fixup_spitz, .map_io = pxa_map_io, .init_irq = pxa27x_init_irq, .init_machine = akita_init, .timer = &pxa_timer, MACHINE_END #endif
23.269488
78
0.703723
[ "model" ]
d990b9f6364e984021a237f803bde84bdbfd5b24
1,618
h
C
mindspore/ccsrc/plugin/device/ascend/hal/device/distribute/mpi_pycc.h
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
1
2022-03-05T02:59:21.000Z
2022-03-05T02:59:21.000Z
mindspore/ccsrc/plugin/device/ascend/hal/device/distribute/mpi_pycc.h
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/plugin/device/ascend/hal/device/distribute/mpi_pycc.h
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_DISTRIBUTE_MPI_PYCC_H #define MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_DISTRIBUTE_MPI_PYCC_H #include <string> #include <vector> #include "plugin/device/ascend/hal/device/distribute/collective_group_wrapper.h" namespace mindspore { namespace device { namespace ascend { namespace collective { class MpiPycc { public: MpiPycc(MpiPycc const &) = delete; MpiPycc &operator=(const MpiPycc &) = delete; static MpiPycc &instance(); static int GetDeviceID(); static int GetRankId(const std::string &group); static int GetRankSize(const std::string &group); static void CreateGroup(const std::string &group, const std::vector<unsigned int> &ranks); private: MpiPycc() = default; ~MpiPycc() = default; }; } // namespace collective } // namespace ascend } // namespace device } // namespace mindspore #endif // MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_DISTRIBUTE_MPI_PYCC_H
34.425532
93
0.743511
[ "vector" ]
d9926b7089fc0dfb55c9d31353a7be17a2bfa654
5,287
h
C
Export/macos/obj/include/lime/_internal/graphics/ImageCanvasUtil.h
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/include/lime/_internal/graphics/ImageCanvasUtil.h
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
Export/macos/obj/include/lime/_internal/graphics/ImageCanvasUtil.h
TrilateralX/TrilateralLimeTriangle
219d8e54fc3861dc1ffeb3da25da6eda349847c1
[ "MIT" ]
null
null
null
// Generated by Haxe 4.2.0-rc.1+cb30bd580 #ifndef INCLUDED_lime__internal_graphics_ImageCanvasUtil #define INCLUDED_lime__internal_graphics_ImageCanvasUtil #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS2(haxe,io,Bytes) HX_DECLARE_CLASS3(lime,_internal,graphics,ImageCanvasUtil) HX_DECLARE_CLASS2(lime,graphics,Image) HX_DECLARE_CLASS2(lime,graphics,ImageChannel) HX_DECLARE_CLASS2(lime,math,Rectangle) HX_DECLARE_CLASS2(lime,math,Vector2) HX_DECLARE_CLASS2(lime,_hx_system,Endian) HX_DECLARE_CLASS2(lime,utils,ArrayBufferView) HX_DECLARE_CLASS2(lime,utils,BytePointerData) namespace lime{ namespace _internal{ namespace graphics{ class HXCPP_CLASS_ATTRIBUTES ImageCanvasUtil_obj : public ::hx::Object { public: typedef ::hx::Object super; typedef ImageCanvasUtil_obj OBJ_; ImageCanvasUtil_obj(); public: enum { _hx_ClassId = 0x608a0907 }; void __construct(); inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="lime._internal.graphics.ImageCanvasUtil") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,false,"lime._internal.graphics.ImageCanvasUtil"); } inline static ::hx::ObjectPtr< ImageCanvasUtil_obj > __new() { ::hx::ObjectPtr< ImageCanvasUtil_obj > __this = new ImageCanvasUtil_obj(); __this->__construct(); return __this; } inline static ::hx::ObjectPtr< ImageCanvasUtil_obj > __alloc(::hx::Ctx *_hx_ctx) { ImageCanvasUtil_obj *__this = (ImageCanvasUtil_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(ImageCanvasUtil_obj), false, "lime._internal.graphics.ImageCanvasUtil")); *(void **)__this = ImageCanvasUtil_obj::_hx_vtable; return __this; } static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~ImageCanvasUtil_obj(); HX_DO_RTTI_ALL; static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp); static void __register(); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("ImageCanvasUtil",15,30,04,51); } static void colorTransform( ::lime::graphics::Image image, ::lime::math::Rectangle rect, ::lime::utils::ArrayBufferView colorMatrix); static ::Dynamic colorTransform_dyn(); static void convertToCanvas( ::lime::graphics::Image image,::hx::Null< bool > clear); static ::Dynamic convertToCanvas_dyn(); static void convertToData( ::lime::graphics::Image image,::hx::Null< bool > clear); static ::Dynamic convertToData_dyn(); static void copyChannel( ::lime::graphics::Image image, ::lime::graphics::Image sourceImage, ::lime::math::Rectangle sourceRect, ::lime::math::Vector2 destPoint, ::lime::graphics::ImageChannel sourceChannel, ::lime::graphics::ImageChannel destChannel); static ::Dynamic copyChannel_dyn(); static void copyPixels( ::lime::graphics::Image image, ::lime::graphics::Image sourceImage, ::lime::math::Rectangle sourceRect, ::lime::math::Vector2 destPoint, ::lime::graphics::Image alphaImage, ::lime::math::Vector2 alphaPoint,::hx::Null< bool > mergeAlpha); static ::Dynamic copyPixels_dyn(); static void createCanvas( ::lime::graphics::Image image,int width,int height); static ::Dynamic createCanvas_dyn(); static void createImageData( ::lime::graphics::Image image); static ::Dynamic createImageData_dyn(); static void fillRect( ::lime::graphics::Image image, ::lime::math::Rectangle rect,int color,int format); static ::Dynamic fillRect_dyn(); static void floodFill( ::lime::graphics::Image image,int x,int y,int color,int format); static ::Dynamic floodFill_dyn(); static int getPixel( ::lime::graphics::Image image,int x,int y,int format); static ::Dynamic getPixel_dyn(); static int getPixel32( ::lime::graphics::Image image,int x,int y,int format); static ::Dynamic getPixel32_dyn(); static ::haxe::io::Bytes getPixels( ::lime::graphics::Image image, ::lime::math::Rectangle rect,int format); static ::Dynamic getPixels_dyn(); static void merge( ::lime::graphics::Image image, ::lime::graphics::Image sourceImage, ::lime::math::Rectangle sourceRect, ::lime::math::Vector2 destPoint,int redMultiplier,int greenMultiplier,int blueMultiplier,int alphaMultiplier); static ::Dynamic merge_dyn(); static void resize( ::lime::graphics::Image image,int newWidth,int newHeight); static ::Dynamic resize_dyn(); static void scroll( ::lime::graphics::Image image,int x,int y); static ::Dynamic scroll_dyn(); static void setPixel( ::lime::graphics::Image image,int x,int y,int color,int format); static ::Dynamic setPixel_dyn(); static void setPixel32( ::lime::graphics::Image image,int x,int y,int color,int format); static ::Dynamic setPixel32_dyn(); static void setPixels( ::lime::graphics::Image image, ::lime::math::Rectangle rect, ::lime::utils::BytePointerData bytePointer,int format, ::lime::_hx_system::Endian endian); static ::Dynamic setPixels_dyn(); static void sync( ::lime::graphics::Image image,bool clear); static ::Dynamic sync_dyn(); }; } // end namespace lime } // end namespace _internal } // end namespace graphics #endif /* INCLUDED_lime__internal_graphics_ImageCanvasUtil */
41.629921
264
0.748818
[ "object" ]
d995c9c15f01db356c9943311b920edb42cc2e34
5,508
c
C
Gstreamer-Applications/gst_transform/transform_display.c
rbmistry/sample-apps-for-Qualcomm-Robotics-RB5-platform
aa56f3a806b5ad5fbac4aafd276b1e79eb8a462f
[ "BSD-3-Clause-Clear" ]
30
2020-10-01T07:53:25.000Z
2022-03-25T07:36:32.000Z
Gstreamer-Applications/gst_transform/transform_display.c
rbmistry/sample-apps-for-Qualcomm-Robotics-RB5-platform
aa56f3a806b5ad5fbac4aafd276b1e79eb8a462f
[ "BSD-3-Clause-Clear" ]
43
2020-10-13T01:39:42.000Z
2022-03-29T02:13:43.000Z
Gstreamer-Applications/gst_transform/transform_display.c
rbmistry/sample-apps-for-Qualcomm-Robotics-RB5-platform
aa56f3a806b5ad5fbac4aafd276b1e79eb8a462f
[ "BSD-3-Clause-Clear" ]
19
2020-10-19T19:28:12.000Z
2022-03-30T07:08:22.000Z
/* * Copyright (c) 2020 Qualcomm Innovation Center, Inc. All Rights Reserved. * * SPDX-License-Identifier: BSD-3-Clause-Clear */ /* * transform_display.c: * * A sample app based on gstreamer * The purpose is helping users to learn how to implement the * transform funtions of ISP camera with gstreamer on the * Qualcomm platform through this sample app. * * This sample should be run in weston display. */ #include <gst/gst.h> #include <glib.h> static void usage(const char *argv0) { g_print("Usage: %s [camera id: 0|1|2|3] [Operation]\n", argv0); g_print(" Operation:\n"); g_print(" flip v|h (v:vertical, h:horizontal)\n"); g_print(" rotate 1|2|3 (1:90CW, 2:90CCW, 3:180)\n"); g_print(" crop x y width height\n"); g_print(" Example:\n"); g_print(" %s 0 flip v\n", argv0); g_print(" %s 0 flip h\n", argv0); g_print(" %s 0 rotate 2\n", argv0); g_print(" %s 0 crop 10 10 200 100\n", argv0); } static gboolean bus_callback(GstBus *bus, GstMessage *msg, gpointer data) { GMainLoop *loop = (GMainLoop *)data; int type = GST_MESSAGE_TYPE(msg); if (type == GST_MESSAGE_ERROR) { gchar *debug; GError *error; gst_message_parse_error(msg, &error, &debug); g_free(debug); g_printerr("Error: %s\n", error->message); g_error_free(error); g_main_loop_quit(loop); } return TRUE; } int main(int argc, char *argv[]) { GMainLoop *loop; GstElement *pipeline, *source, *framefilter, *transform, *sink; GstBus *bus; guint bus_id; gint8 camera_id; gint8 rotate_type; gst_init (&argc, &argv); loop = g_main_loop_new(NULL, FALSE); if (argc < 3) { usage(argv[0]); return -1; } camera_id = atoi(argv[1]); if (camera_id < 0 || camera_id > 3) { g_printerr("camera id incorrect.\n"); usage(argv[0]); return -1; } if (!strncmp(argv[2], "flip", 8)) { if (argc == 4) { if (strncmp(argv[3], "v", 8) && strncmp(argv[3], "h", 8)) { g_printerr("flip should specify v or h.\n"); usage(argv[0]); return -1; } } else { g_printerr("flip should specify v or h.\n"); usage(argv[0]); return -1; } } else if (!strncmp(argv[2], "rotate", 8)) { if (argc == 4) { rotate_type = atoi(argv[3]); if (rotate_type < 1 || rotate_type > 3) { g_printerr("rotate type incorrect. (1|2|3)\n"); usage(argv[0]); return -1; } } else { g_printerr("rotate type (1|2|3) needs to be specified.\n"); usage(argv[0]); return -1; } } else if (!strncmp(argv[2], "crop", 8)) { if (argc != 7) { g_printerr("crop position and size (x y w h) need to be specified.\n"); usage(argv[0]); return -1; } } else { g_printerr("Unknown operation: %s.\n", argv[2]); usage(argv[0]); return -1; } pipeline = gst_pipeline_new("video-display"); source = gst_element_factory_make("qtiqmmfsrc", "qmmf-source"); framefilter = gst_element_factory_make("capsfilter", "frame-filter"); transform = gst_element_factory_make("qtivtransform","transform"); sink = gst_element_factory_make("waylandsink", "display"); if (!pipeline || !source || !framefilter || !transform || !sink) { g_printerr("Element create failed.\n"); return -1; } g_object_set(G_OBJECT(source), "camera", camera_id, NULL); if (camera_id == 0) { g_object_set(G_OBJECT(framefilter), "caps", gst_caps_from_string("video/x-raw,format=NV12,framerate=30/1,width=1920,height=1080"), NULL); } else { g_object_set(G_OBJECT(framefilter), "caps", gst_caps_from_string("video/x-raw,format=NV12,framerate=30/1,width=1280,height=720"), NULL); } if (!strncmp(argv[2], "flip", 8)) { if (!strncmp(argv[3], "v", 8)) { g_object_set (G_OBJECT(transform), "flip-vertical", 1, NULL); } else if (!strncmp(argv[3], "h", 8)) { g_object_set (G_OBJECT(transform), "flip-horizontal", 1, NULL); } } else if (!strncmp(argv[2], "rotate", 8)) { g_object_set (G_OBJECT(transform), "rotate", atoi(argv[3]), NULL); } else if (!strncmp(argv[2], "crop", 8)) { g_object_set (G_OBJECT(transform), "crop-x", atoi(argv[3]), "crop-y", atoi(argv[4]), "crop-width", atoi(argv[5]), "crop-height", atoi(argv[6]), NULL); } g_object_set(G_OBJECT(sink), "x", 0, "y", 600, "width", 640, "height", 360, NULL); bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline)); bus_id = gst_bus_add_watch(bus, bus_callback, loop); gst_object_unref(bus); gst_bin_add_many(GST_BIN(pipeline), source, framefilter, transform, sink, NULL); gst_element_link_many(source, framefilter, transform, sink, NULL); gst_element_set_state(pipeline, GST_STATE_PLAYING); g_print("Start\n"); g_main_loop_run(loop); g_print("Stop\n"); gst_element_set_state(pipeline, GST_STATE_NULL); gst_object_unref(GST_OBJECT(pipeline)); g_source_remove(bus_id); g_main_loop_unref(loop); gst_deinit(); return 0; }
30.94382
121
0.56663
[ "transform" ]
d9968b00b2425910b3cbfd06eb5ff67d85698547
4,297
h
C
mindspore/ccsrc/runtime/framework/actor/copy_actor.h
ATestGroup233/mindspore
5d81221b5896cf7d7c6adb44daef28d92cb43352
[ "Apache-2.0" ]
1
2021-06-01T12:34:37.000Z
2021-06-01T12:34:37.000Z
mindspore/ccsrc/runtime/framework/actor/copy_actor.h
ATestGroup233/mindspore
5d81221b5896cf7d7c6adb44daef28d92cb43352
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/runtime/framework/actor/copy_actor.h
ATestGroup233/mindspore
5d81221b5896cf7d7c6adb44daef28d92cb43352
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDSPORE_CCSRC_RUNTIME_FRAMEWORK_ACTOR_COPY_ACTOR_H_ #define MINDSPORE_CCSRC_RUNTIME_FRAMEWORK_ACTOR_COPY_ACTOR_H_ #include <vector> #include <string> #include <memory> #include <utility> #include <unordered_map> #include "runtime/framework/actor/actor_common.h" #include "runtime/framework/actor/memory_aware_actor.h" #include "runtime/hardware/device_context.h" #include "runtime/framework/device_tensor_store.h" namespace mindspore { namespace runtime { using mindspore::device::DeviceContext; // The copy actor is used to receive the device tensors and control info to copy data between input device tensor and // output device tensor. The processing flow is RunOpData/RunOpControl -> CheckCopyCondition -> SendMemoryAllocReq // -> OnMemoryAllocFinish -> Copy -> SendMemoryFreeReq -> SendOutput. class CopyActor : public MemoryAwareActor { public: CopyActor(const std::string &name, const AID &memory_manager_aid) : MemoryAwareActor(name), memory_manager_aid_(memory_manager_aid), input_datas_num_(0), input_controls_num_(0), output_(nullptr) {} ~CopyActor() override = default; void Init() override; // The copy actor run when receive the input data. void RunOpData(OpData<DeviceTensor> *input_data, OpContext<DeviceTensor> *context) override; // The copy actor run when receive the input control. void RunOpControl(AID *input_control, OpContext<DeviceTensor> *context) override; // The memory related operation interface. void SendMemoryAllocReq(OpContext<DeviceTensor> *context) override; void SendMemoryFreeReq(OpContext<DeviceTensor> *context) override; // The copy processing after memory alloc finished. void OnMemoryAllocFinish(OpContext<DeviceTensor> *context) override; private: friend class GraphScheduler; // Check whether satisfy the condition for copy. bool CheckCopyCondition(OpContext<DeviceTensor> *context) const; // Fetch the device tensor for copy. void FetchDeviceTensor(OpContext<DeviceTensor> *context); // Copy data from src_device_tensor to dst_device_tensor. bool Copy(DeviceTensor *dst_device_tensor, const DeviceTensor *src_device_tensor); // Send output data and output controls when finish copy. void SendOutput(OpContext<DeviceTensor> *context) const; // Erase input data and input controls when finish copy. void EraseInput(OpContext<DeviceTensor> *context); // The id of memory manager actor. Send message to it for alloc and free memory during the copy. const AID memory_manager_aid_; // The dependent input data number. size_t input_datas_num_; // The dependent input controls number. size_t input_controls_num_; // Pair<index, anfNode> points to the dependent device tensor store, anfNode is the key of the device tensor store. std::pair<size_t, AnfNode *> device_tensor_store_key_; // The device interface for copy. const DeviceContext *input_device_context_; const DeviceContext *output_device_context_; // The input device tensor is saved from the input data or fetched by device_tensor_store_key_. std::vector<DeviceTensor *> input_device_tensor_; // The output device tensor is saved from the output or fetched by device_tensor_store_key_. std::vector<DeviceTensor *> output_device_tensor_; // The output_data_ corresponds to the output_data_arrows_ one by one. std::vector<OpDataUniquePtr<DeviceTensor>> output_data_; // The output is created in the copy actor build, so can't be the raw pointer. DeviceTensorPtr output_; }; using CopyActorPtr = std::shared_ptr<CopyActor>; } // namespace runtime } // namespace mindspore #endif // MINDSPORE_CCSRC_RUNTIME_FRAMEWORK_ACTOR_COPY_ACTOR_H_
40.158879
117
0.774494
[ "vector" ]
d9a48dd7664feb225407a7c7a0935c84e0c2db28
737
c
C
lib/wizards/walla/area/bazaar12.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/walla/area/bazaar12.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/walla/area/bazaar12.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
#include "room.h" #undef EXTRA_RESET #define EXTRA_RESET\ extra_reset(); object monster; extra_reset() { set_not_out(3); if (!monster) { monster = clone_object("/wizards/walla/area/monsters/bazaarman"); move_object(monster, this_object()); } } THREE_EXIT("wizards/walla/area/bazaar11", "west", "wizards/walla/area/bazaar13", "east", "wizards/walla/area/bazaar22", "south", "In the bazaar of Jericho", "You are in the northern part of the bazaar.\n" + "This is the place where the people of Jericho meet to discuss their problems.\n" + "Shopkeepers scream out their products what their heads can take. \n" + "Everyone seems happy. \n", 3)
25.413793
92
0.639077
[ "object" ]
d9aa7cc0f917b2067741a7ede44ad35920a9bd0d
922
h
C
src/updaters/equationOfMotion.h
DanielMSussman/dDimensionalSimulation
d2d9ebea34bc23243b47a68d9bf17539b933120f
[ "BSL-1.0" ]
null
null
null
src/updaters/equationOfMotion.h
DanielMSussman/dDimensionalSimulation
d2d9ebea34bc23243b47a68d9bf17539b933120f
[ "BSL-1.0" ]
null
null
null
src/updaters/equationOfMotion.h
DanielMSussman/dDimensionalSimulation
d2d9ebea34bc23243b47a68d9bf17539b933120f
[ "BSL-1.0" ]
null
null
null
#ifndef EQUATIONOFMOTION_H #define EQUATIONOFMOTION_H #include "baseUpdater.h" /*! \file equationOfMotion.h */ //! child class just need to implement the CPU and GPU functions class equationOfMotion : public updater { public: virtual void performUpdate(){integrateEquationOfMotion();}; virtual void integrateEquationOfMotion() { if (model->getNumberOfParticles() != Ndof) initializeFromModel(); if (useGPU) integrateEOMGPU(); else integrateEOMCPU(); }; virtual void integrateEOMGPU(){}; virtual void integrateEOMCPU(){}; virtual void initializeFromModel() { Ndof = model->getNumberOfParticles(); displacement.resize(Ndof); }; //!an array of displacements GPUArray<dVec> displacement; }; #endif
27.117647
67
0.584599
[ "model" ]
d9b03dd6ceaf96b4f2fd7b3c3e85de144cdcd37c
1,082
h
C
ParticleSpawner.h
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
ParticleSpawner.h
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
ParticleSpawner.h
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
#pragma once /// <summary> /// Has its own vector of particles and manages them in Update loop; /// </summary> #include <iostream>; #include "Vector2.h"; #include "Sprite.h"; #include <vector>; #include <stdlib.h> #include <time.h> #include "Particle.h"; #include "SpriteRenderer.h"; class ParticleSpawner: public GameObject { public: ParticleSpawner(std::string textureName, int spawnRate, float minimalParticleLifeTime, float maximalParticleLifeTime, Vector2 minimalVelocity, Vector2 maximalVelocity, float minimalRotationSpeed, float maximalRotationSpeed, int minimalParticleSize, int maximalParticleSize, float x, float y); ~ParticleSpawner(); std::vector<Particle*> particles; std::string textureName; int spawnRate; float minimalParticleLifeTime; float maximalParticleLifeTime; Vector2 minimalVelocity; Vector2 maximalVelocity; float minimalRotationSpeed; float maximalRotationSpeed; int minimalParticleSize; int maximalParticleSize; void Update(float dt, std::vector<GameObject*>& objects); void Render(); private: float timeUntilNextSpawn; };
27.05
68
0.778189
[ "render", "vector" ]
d9b5e3b7d3b386bcee9f861bb70986001157e9d2
8,029
h
C
osx/MameController.h
clobber/MAME-OS-X
ca11d0e946636bda042b6db55c82113e5722fc08
[ "MIT" ]
15
2015-03-03T23:15:57.000Z
2021-11-12T07:09:24.000Z
osx/MameController.h
clobber/MAME-OS-X
ca11d0e946636bda042b6db55c82113e5722fc08
[ "MIT" ]
null
null
null
osx/MameController.h
clobber/MAME-OS-X
ca11d0e946636bda042b6db55c82113e5722fc08
[ "MIT" ]
8
2015-07-07T16:40:44.000Z
2020-08-18T06:57:29.000Z
/* * Copyright (c) 2006-2007 Dave Dribin * * 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. */ #import <Cocoa/Cocoa.h> #import <QuartzCore/QuartzCore.h> #import <Quartz/Quartz.h> #import "JRLog.h" #if defined(__cplusplus) extern "C++" { #endif #include "osdepend.h" #include "render.h" #if defined(__cplusplus) } #endif @class PreferencesWindowController; @class MameView; @class MameConfiguration; @class VersionChecker; @class AudioEffectWindowController; @class BackgroundUpdater; @class RBSplitSubview; @class GroupMO; @interface MameController : NSObject <JRLogLogger> { IBOutlet MameView * mMameView; IBOutlet NSDrawer * mDrawer; IBOutlet NSWindow * mOpenPanel; IBOutlet VersionChecker *mVersionChecker; IBOutlet NSMenu * mEffectsMenu; IBOutlet NSMenu * mGameFilterMenu; IBOutlet NSToolbar * mToolbar; IBOutlet QCView * mScreenshotView; IBOutlet NSProgressIndicator * mProgressIndicator; IBOutlet NSImageView * mDragView; IBOutlet RBSplitSubview * mGameSplit; IBOutlet RBSplitSubview * mScreenshotSplit; IBOutlet NSPanel * mMameLogPanel; IBOutlet NSTextView * mMameLogView; IBOutlet NSArrayController * mAllGamesController; IBOutlet NSTableView * mGamesTable; IBOutlet NSTableColumn * mFavoriteColumn; IBOutlet NSView * mAuditTableSubstitutionView; IBOutlet NSPanel * mInfoPanel; IBOutlet NSTextView * mInfoAuditNotes; // Size of other elements around the view NSSize mExtraWindowSize; NSRect mOriginalOpenFrame; PreferencesWindowController * mPreferencesController; AudioEffectWindowController * mAudioEffectsController; MameConfiguration * mConfiguration; BOOL mMameIsRunning; NSMutableArray * mEffectNames; NSMutableDictionary * mEffectPathsByName; BOOL mVisualEffectEnabled; int mCurrentEffectIndex; NSString * mGameName; NSString * mLoadingMessage; NSMutableArray * mPreviousGames; BOOL mGameLoading; BOOL mGameRunning; BOOL mTerminateOnGameExit; BOOL mTerminateReplyOnGameExit; NSDictionary * mLogAttributes; NSDictionary * mLogErrorAttributes; NSDictionary * mLogWarningAttributes; NSDictionary * mLogInfoAttributes; NSDictionary * mLogDebugAttributes; id<JRLogLogger> mOriginalLogger; NSPersistentStoreCoordinator * persistentStoreCoordinator; NSManagedObjectModel * managedObjectModel; NSManagedObjectContext * managedObjectContext; BOOL mFreshPersistentStore; NSArray * mGameSortDescriptors; NSString * mFilterString; int mGameFilterIndex; BackgroundUpdater * mUpdater; BOOL mShowClones; NSString * mStatusText; } #pragma mark - #pragma mark Core Data - (void) handleCoreDataError: (NSError *) error; - (NSManagedObjectModel *) managedObjectModel; - (NSPersistentStoreCoordinator *) persistentStoreCoordinator; - (NSManagedObjectContext *) managedObjectContext; - (IBAction) saveAction: (id) sender; #pragma mark - - (NSArray *) gameSortDescriptors; - (void) setGameSortDescriptors: (NSArray *) theGameSortDescriptors; - (void) setFilterString: (NSString *) filterString; - (NSString *) filterString; - (IBAction) gameFilterAction: (id) sender; - (void) setGameFilterIndex: (int) gameFilterIndex; - (int) gameFilterIndex; - (BOOL) showClones; - (void) setShowClones: (BOOL) flag; - (IBAction) toggleFavorite: (id) sender; - (IBAction) exportFavorites: (id) sender; - (IBAction) importFavorites: (id) sender; - (void) restoreFavorites; - (NSArray *) selectedGames; - (IBAction) refreshGames: (id) sender; - (void) rearrangeGames; - (NSString *) statusText; - (void) setStatusText: (NSString *) theStatusText; #pragma mark - #pragma mark State - (BOOL) canAuditGames; - (BOOL) canAbortAudit; - (unsigned) selectionCount; - (BOOL) hasSelection; - (BOOL) hasNoSelection; - (BOOL) hasOneSelection; - (BOOL) hasMultipleSelection; #pragma mark - #pragma mark Background Callbacks - (void) backgroundUpdateWillStart; - (void) backgroundUpdateWillBeginAudits: (unsigned) totalAudits; - (void) backgroundUpdateAuditStatus: (unsigned) numberCompleted; - (void) backgroundUpdateWillFinish; - (IBAction) toggleScreenshot: (id) sender; - (IBAction) restoreOpenFrame: (id) sender; #pragma mark - - (MameView *) mameView; - (BOOL) visualEffectEnabled; - (void) setVisualEffectEnabled: (BOOL) flag; - (int) currentEffectIndex; - (void) setCurrentEffectIndex: (int) currentEffectIndex; - (void) setCurrentVisualEffectName: (NSString *) effectName; - (NSArray *) visualEffectNames; - (IBAction) nextVisualEffect: (id) sender; - (IBAction) previousVisualEffects: (id) sender; - (IBAction) visualEffectsMenuChanged: (id) sender; - (IBAction) toggleThrottled: (id) sender; - (IBAction) toggleSubstitution: (id) sender; - (BOOL) isTableSubstitutionHidden; - (void) setTableSubstitionHidden: (BOOL) hidden; - (BOOL) syncToRefresh; - (void) setSyncToRefresh: (BOOL) flag; - (BOOL) fullScreen; - (void) setFullScreen: (BOOL) fullScreen; - (BOOL) linearFilter; - (void) setLinearFilter: (BOOL) linearFilter; - (BOOL) audioEffectEnabled; - (void) setAudioEffectEnabled: (BOOL) flag; - (IBAction) showAudioEffectsPanel: (id) sender; - (BOOL) isGameLoading; - (BOOL) isGameRunning; - (NSString *) loadingMessage; - (NSArray *) previousGames; - (IBAction) showPreferencesPanel: (id) sender; - (IBAction) togglePause: (id) sender; - (IBAction) nullAction: (id) sender; - (IBAction) raiseOpenPanel: (id) sender; - (IBAction) endOpenPanel: (id) sender; - (IBAction) cancelOpenPanel: (id) sender; - (IBAction) hideOpenPanel: (id) sender; - (IBAction) resizeToActualSize: (id) sender; - (IBAction) resizeToDoubleSize: (id) sender; - (IBAction) resizeToOptimalSize: (id) sender; - (IBAction) resizeToMaximumIntegralSize: (id) sender; - (IBAction) resizeToMaximumSize: (id) sender; - (IBAction) auditRoms: (id) sender; - (IBAction) auditSelectedGames: (id) sender; - (IBAction) auditAllGames: (id) sender; - (IBAction) auditUnauditedGames: (id) sender; - (IBAction) abortAudit: (id) sender; - (IBAction) resetAuditStatus: (id) sender; - (IBAction) showLogWindow: (id) sender; - (IBAction) clearLogWindow: (id) sender; - (IBAction) showReleaseNotes: (id) sender; - (IBAction) showWhatsNew: (id) sender; - (void) logWithLevel: (JRLogLevel) callerLevel instance: (NSString*) instance file: (const char*) file line: (unsigned) line function: (const char*) function message: (NSString*) message; #pragma mark - #pragma mark MameView delegates - (void) mameWillStartGame: (NSNotification *) notification; - (void) mameDidFinishGame: (NSNotification *) notification; - (void) mameErrorMessage: (NSString *) message; - (void) mameWarningMessage: (NSString *) message; - (void) mameInfoMessage: (NSString *) message; - (void) mameDebugMessage: (NSString *) message; - (void) mameLogMessage: (NSString *) message; @end
27.878472
70
0.732843
[ "render" ]
d9b9df1788404f58de3a8f7096fc1fdf205334ec
1,122
h
C
Glop/net/MockRouter.h
zorbathut/glop
762d4f1e070ce9c7180a161b521b05c45bde4a63
[ "BSD-3-Clause" ]
1
2016-06-28T18:19:30.000Z
2016-06-28T18:19:30.000Z
Glop/net/MockRouter.h
zorbathut/glop
762d4f1e070ce9c7180a161b521b05c45bde4a63
[ "BSD-3-Clause" ]
null
null
null
Glop/net/MockRouter.h
zorbathut/glop
762d4f1e070ce9c7180a161b521b05c45bde4a63
[ "BSD-3-Clause" ]
null
null
null
#ifndef GLOP_NET_MOCK_ROUTER_H__ #define GLOP_NET_MOCK_ROUTER_H__ #include "NetworkManagerInterface.h" #include <map> #include <set> #include <string> #include <vector> using namespace std; typedef int RouterKey; class MockRouter { public: MockRouter(); RouterKey GetKey(int port); void Connect(RouterKey key, GlopNetworkAddress gna); void Disconnect(RouterKey key, GlopNetworkAddress gna); vector<GlopNetworkAddress> GetConnections(RouterKey key) const; void SendData(RouterKey key, GlopNetworkAddress gna, const string& data); bool ReceiveData(RouterKey key, GlopNetworkAddress* gna, string* data); void StartHosting(RouterKey key, const string& data); void StopHosting(RouterKey key); vector<pair<GlopNetworkAddress, string> > AvailableHosts(int port) const; private: map<RouterKey, GlopNetworkAddress> key_to_gna_; map<GlopNetworkAddress, RouterKey> gna_to_key_; map<RouterKey, set<GlopNetworkAddress> > connections_; map<RouterKey, List<pair<GlopNetworkAddress, string> > > sent_data_; map<RouterKey, string> hosts_; RouterKey next_key_; }; #endif // GLOP_NET_MOCK_ROUTER_H__
29.526316
75
0.783422
[ "vector" ]
8acc7603293d23f4dbccf8f298e963a09c45ae35
637
h
C
include/symphony_lake_dataset/Pose.h
cedricpradalier/SymphonyLakeDataset
5366560263b660b0151844a297effa517480991a
[ "Apache-2.0" ]
2
2020-03-31T03:19:32.000Z
2020-03-31T03:19:48.000Z
include/symphony_lake_dataset/Pose.h
cedricpradalier/SymphonyLakeDataset
5366560263b660b0151844a297effa517480991a
[ "Apache-2.0" ]
null
null
null
include/symphony_lake_dataset/Pose.h
cedricpradalier/SymphonyLakeDataset
5366560263b660b0151844a297effa517480991a
[ "Apache-2.0" ]
null
null
null
#ifndef LSM_POSE_H #define LSM_POSE_H #ifdef NDEBUG #undef NDEBUG #endif #include <stdio.h> #include <vector> namespace symphony_lake_dataset { struct Pose { int kf; double t; double xm,ym,thetam; // SE2 pose w.r.t. map double xg,yg,thetag; // SE2 pose w.r.t. gps bool loadFromString(const std::string & s) { if (sscanf(s.c_str(),"%d, %le, %le, %le, %le, %le, %le, %le",&kf,&t, &xm,&ym,&thetam, &xg, &yg, &thetag) != 8) { return false; } return true; } }; typedef std::vector<Pose> PoseVector; }; #endif // LSM_POSE_H
20.548387
124
0.544741
[ "vector" ]
8acf550fce0c71023c8c5d9c34051a1ef75ef2f9
12,405
c
C
extern/libtomcrypt/demos/openssl-enc.c
thenerdie/etterna
341b7c506c785e3a15e7af18814791aefff5c958
[ "MIT" ]
551
2017-06-02T05:14:54.000Z
2022-03-31T03:43:51.000Z
extern/libtomcrypt/demos/openssl-enc.c
thenerdie/etterna
341b7c506c785e3a15e7af18814791aefff5c958
[ "MIT" ]
799
2017-06-11T12:30:26.000Z
2022-03-31T23:56:48.000Z
extern/libtomcrypt/demos/openssl-enc.c
thenerdie/etterna
341b7c506c785e3a15e7af18814791aefff5c958
[ "MIT" ]
177
2017-06-02T03:41:39.000Z
2022-03-14T06:22:08.000Z
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ /* * Demo to do the rough equivalent of: * * openssl enc -aes-256-cbc -pass pass:foobar -in infile -out outfile -p * * Compilation: * * $(CC) -I /path/to/headers -L .../libs \ * -o openssl-enc \ * openssl-enc.c -ltomcrypt * * Usage: * * ./openssl-enc <enc|dec> infile outfile "passphrase" [salt] * * If provided, the salt must be EXACTLY a 16-char hex string. * * Demo is an example of: * * - (When decrypting) yanking salt out of the OpenSSL "Salted__..." header * - OpenSSL-compatible key derivation (in OpenSSL's modified PKCS#5v1 approach) * - Grabbing an Initialization Vector from the key generator * - Performing simple block encryption using AES * - PKCS#7-type padding (which hopefully can get ripped out of this demo and * made a libtomcrypt thing someday). * * This program is free for all purposes without any express guarantee it * works. If you really want to see a license here, assume the WTFPL :-) * * BJ Black, bblack@barracuda.com, https://wjblack.com * * BUGS: * Passing a password on a command line is a HORRIBLE idea. Don't use * this program for serious work! */ #include <tomcrypt.h> #ifndef LTC_RIJNDAEL #error Cannot compile this demo; Rijndael (AES) required #endif #ifndef LTC_CBC_MODE #error Cannot compile this demo; CBC mode required #endif #ifndef LTC_PKCS_5 #error Cannot compile this demo; PKCS5 required #endif #ifndef LTC_RNG_GET_BYTES #error Cannot compile this demo; random generator required #endif #ifndef LTC_MD5 #error Cannot compile this demo; MD5 required #endif /* OpenSSL by default only runs one hash round */ #define OPENSSL_ITERATIONS 1 /* Use aes-256-cbc, so 256 bits of key, 128 of IV */ #define KEY_LENGTH (256>>3) #define IV_LENGTH (128>>3) /* PKCS#5v1 requires exactly an 8-byte salt */ #define SALT_LENGTH 8 /* The header OpenSSL puts on an encrypted file */ static char salt_header[] = { 'S', 'a', 'l', 't', 'e', 'd', '_', '_' }; #include <errno.h> #include <stdio.h> #include <string.h> /* A simple way to handle the possibility that a block may increase in size after padding. */ union paddable { unsigned char unpad[1024]; unsigned char pad[1024+MAXBLOCKSIZE]; }; /* * Print usage and exit with a bad status (and perror() if any errno). * * Input: argv[0] and the error string * Output: <no return> * Side Effects: print messages and barf (does exit(3)) */ void barf(const char *pname, const char *err) { printf("Usage: %s <enc|dec> infile outfile passphrase [salt]\n", pname); printf("\n"); printf(" # encrypts infile->outfile, random salt\n"); printf(" %s enc infile outfile \"passphrase\"\n", pname); printf("\n"); printf(" # encrypts infile->outfile, salt from cmdline\n"); printf(" %s enc infile outfile pass 0123456789abcdef\n", pname); printf("\n"); printf(" # decrypts infile->outfile, pulls salt from infile\n"); printf(" %s dec infile outfile pass\n", pname); printf("\n"); printf(" # decrypts infile->outfile, salt specified\n"); printf(" # (don't try to read the salt from infile)\n"); printf(" %s dec infile outfile pass 0123456789abcdef" "\n", pname); printf("\n"); printf("Application Error: %s\n", err); if(errno) perror(" System Error"); exit(-1); } /* * Parse a salt value passed in on the cmdline. * * Input: string passed in and a buf to put it in (exactly 8 bytes!) * Output: CRYPT_OK if parsed OK, CRYPT_ERROR if not * Side Effects: none */ int parse_hex_salt(unsigned char *in, unsigned char *out) { int idx; for(idx=0; idx<SALT_LENGTH; idx++) if(sscanf((char*)in+idx*2, "%02hhx", out+idx) != 1) return CRYPT_ERROR; return CRYPT_OK; } /* * Parse the Salted__[+8 bytes] from an OpenSSL-compatible file header. * * Input: file to read from and a to put the salt in (exactly 8 bytes!) * Output: CRYPT_OK if parsed OK, CRYPT_ERROR if not * Side Effects: infile's read pointer += 16 */ int parse_openssl_header(FILE *in, unsigned char *out) { unsigned char tmp[SALT_LENGTH]; if(fread(tmp, 1, sizeof(tmp), in) != sizeof(tmp)) return CRYPT_ERROR; if(memcmp(tmp, salt_header, sizeof(tmp))) return CRYPT_ERROR; if(fread(tmp, 1, sizeof(tmp), in) != sizeof(tmp)) return CRYPT_ERROR; memcpy(out, tmp, sizeof(tmp)); return CRYPT_OK; } /* * Dump a hexed stream of bytes (convenience func). * * Input: buf to read from, length * Output: none * Side Effects: bytes printed as a hex blob, no lf at the end */ void dump_bytes(unsigned char *in, unsigned long len) { unsigned long idx; for(idx=0; idx<len; idx++) printf("%02hhX", *(in+idx)); } /* * Pad or unpad a message using PKCS#7 padding. * Padding will add 1-(blocksize) bytes and unpadding will remove that amount. * Set is_padding to 1 to pad, 0 to unpad. * * Input: paddable buffer, size read, block length of cipher, mode * Output: number of bytes after padding resp. after unpadding * Side Effects: none */ size_t pkcs7_pad(union paddable *buf, size_t nb, int block_length, int is_padding) { unsigned char padval; off_t idx; if(is_padding) { /* We are PADDING this block (and therefore adding bytes) */ /* The pad value in PKCS#7 is the number of bytes remaining in the block, so for a 16-byte block and 3 bytes left, it's 0x030303. In the oddball case where nb is an exact multiple multiple of block_length, set the padval to blocksize (i.e. add one full block) */ padval = (unsigned char) (block_length - (nb % block_length)); padval = padval ? padval : block_length; memset(buf->pad+nb, padval, padval); return nb+padval; } else { /* We are UNPADDING this block (and removing bytes) We really just need to verify that the pad bytes are correct, so start at the end of the string and work backwards. */ /* Figure out what the padlength should be by looking at the last byte */ idx = nb-1; padval = buf->pad[idx]; /* padval must be nonzero and <= block length */ if(padval <= 0 || padval > block_length) return 0; /* First byte's accounted for; do the rest */ idx--; while(idx >= (off_t)(nb-padval)) if(buf->pad[idx] != padval) return 0; else idx--; /* If we got here, the pad checked out, so return a smaller number of bytes than nb (basically where we left off+1) */ return idx+1; } } /* * Perform an encrypt/decrypt operation to/from files using AES+CBC+PKCS7 pad. * Set encrypt to 1 to encrypt, 0 to decrypt. * * Input: in/out files, key, iv, and mode * Output: CRYPT_OK if no error * Side Effects: bytes slurped from infile, pushed to outfile, fds updated. */ int do_crypt(FILE *infd, FILE *outfd, unsigned char *key, unsigned char *iv, int encrypt) { union paddable inbuf, outbuf; int cipher, ret; symmetric_CBC cbc; size_t nb; /* Register your cipher! */ cipher = register_cipher(&aes_desc); if(cipher == -1) return CRYPT_INVALID_CIPHER; /* Start a CBC session with cipher/key/val params */ ret = cbc_start(cipher, iv, key, KEY_LENGTH, 0, &cbc); if( ret != CRYPT_OK ) return -1; do { /* Get bytes from the source */ nb = fread(inbuf.unpad, 1, sizeof(inbuf.unpad), infd); if(!nb) return encrypt ? CRYPT_OK : CRYPT_ERROR; /* Barf if we got a read error */ if(ferror(infd)) return CRYPT_ERROR; if(encrypt) { /* We're encrypting, so pad first (if at EOF) and then crypt */ if(feof(infd)) nb = pkcs7_pad(&inbuf, nb, aes_desc.block_length, 1); ret = cbc_encrypt(inbuf.pad, outbuf.pad, nb, &cbc); if(ret != CRYPT_OK) return ret; } else { /* We're decrypting, so decrypt and then unpad if at EOF */ ret = cbc_decrypt(inbuf.unpad, outbuf.unpad, nb, &cbc); if( ret != CRYPT_OK ) return ret; if( feof(infd) ) nb = pkcs7_pad(&outbuf, nb, aes_desc.block_length, 0); if(nb == 0) /* The file didn't decrypt correctly */ return CRYPT_ERROR; } /* Push bytes to outfile */ if(fwrite(outbuf.unpad, 1, nb, outfd) != nb) return CRYPT_ERROR; } while(!feof(infd)); /* Close up */ cbc_done(&cbc); return CRYPT_OK; } /* Convenience macro for the various barfable places below */ #define BARF(a) { \ if(infd) fclose(infd); \ if(outfd) { fclose(outfd); remove(argv[3]); } \ barf(argv[0], a); \ } /* * The main routine. Mostly validate cmdline params, open files, run the KDF, * and do the crypt. */ int main(int argc, char *argv[]) { unsigned char salt[SALT_LENGTH]; FILE *infd = NULL, *outfd = NULL; int encrypt = -1; int hash = -1; int ret; unsigned char keyiv[KEY_LENGTH + IV_LENGTH]; unsigned long keyivlen = (KEY_LENGTH + IV_LENGTH); unsigned char *key, *iv; /* Check proper number of cmdline args */ if(argc < 5 || argc > 6) BARF("Invalid number of arguments"); /* Check proper mode of operation */ if (!strncmp(argv[1], "enc", 3)) encrypt = 1; else if(!strncmp(argv[1], "dec", 3)) encrypt = 0; else BARF("Bad command name"); /* Check we can open infile/outfile */ infd = fopen(argv[2], "rb"); if(infd == NULL) BARF("Could not open infile"); outfd = fopen(argv[3], "wb"); if(outfd == NULL) BARF("Could not open outfile"); /* Get the salt from wherever */ if(argc == 6) { /* User-provided */ if(parse_hex_salt((unsigned char*) argv[5], salt) != CRYPT_OK) BARF("Bad user-specified salt"); } else if(!strncmp(argv[1], "enc", 3)) { /* Encrypting; get from RNG */ if(rng_get_bytes(salt, sizeof(salt), NULL) != sizeof(salt)) BARF("Not enough random data"); } else { /* Parse from infile (decrypt only) */ if(parse_openssl_header(infd, salt) != CRYPT_OK) BARF("Invalid OpenSSL header in infile"); } /* Fetch the MD5 hasher for PKCS#5 */ hash = register_hash(&md5_desc); if(hash == -1) BARF("Could not register MD5 hash"); /* Set things to a sane initial state */ zeromem(keyiv, sizeof(keyiv)); key = keyiv + 0; /* key comes first */ iv = keyiv + KEY_LENGTH; /* iv comes next */ /* Run the key derivation from the provided passphrase. This gets us the key and iv. */ ret = pkcs_5_alg1_openssl((unsigned char*)argv[4], strlen(argv[4]), salt, OPENSSL_ITERATIONS, hash, keyiv, &keyivlen ); if(ret != CRYPT_OK) BARF("Could not derive key/iv from passphrase"); /* Display the salt/key/iv like OpenSSL cmdline does when -p */ printf("salt="); dump_bytes(salt, sizeof(salt)); printf("\n"); printf("key="); dump_bytes(key, KEY_LENGTH); printf("\n"); printf("iv ="); dump_bytes(iv, IV_LENGTH ); printf("\n"); /* If we're encrypting, write the salt header as OpenSSL does */ if(!strncmp(argv[1], "enc", 3)) { if(fwrite(salt_header, 1, sizeof(salt_header), outfd) != sizeof(salt_header) ) BARF("Error writing salt header to outfile"); if(fwrite(salt, 1, sizeof(salt), outfd) != sizeof(salt)) BARF("Error writing salt to outfile"); } /* At this point, the files are open, the salt has been figured out, and we're ready to pump data through crypt. */ /* Do the crypt operation */ if(do_crypt(infd, outfd, key, iv, encrypt) != CRYPT_OK) BARF("Error during crypt operation"); /* Clean up */ fclose(infd); fclose(outfd); return 0; } /* ref: tag: v1.18.2, master */ /* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */ /* commit time: 2018-07-01 22:49:01 +0200 */
31.168342
80
0.620314
[ "vector" ]
8ad00b8b78a5942fbb4f48ee45f0b42207bbb081
6,744
h
C
dwl/dwl/utils/RigidBodyDynamics.h
EricWang1hitsz/dwl
b45e6babfcace928af2601f3d453e3f27e2e76c8
[ "BSD-3-Clause" ]
65
2018-01-18T08:26:18.000Z
2022-01-27T03:31:22.000Z
dwl/dwl/utils/RigidBodyDynamics.h
EricWang1hitsz/dwl
b45e6babfcace928af2601f3d453e3f27e2e76c8
[ "BSD-3-Clause" ]
4
2018-09-27T16:06:11.000Z
2022-01-27T03:31:11.000Z
dwl/dwl/utils/RigidBodyDynamics.h
EricWang1hitsz/dwl
b45e6babfcace928af2601f3d453e3f27e2e76c8
[ "BSD-3-Clause" ]
28
2018-01-24T14:07:31.000Z
2022-01-27T03:31:25.000Z
#ifndef DWL__RBD__RIGID_BODY_DYNAMICS__H #define DWL__RBD__RIGID_BODY_DYNAMICS__H #include <rbdl/rbdl.h> #include <dwl/utils/Math.h> namespace dwl { namespace rbd { enum Component {Linear, Angular, Full}; typedef Eigen::Matrix<double,6,1> Vector6d; typedef Eigen::Matrix<double,6,6> Matrix6d; typedef std::vector<std::string> BodySelector; typedef std::map<std::string,unsigned int> BodyID; typedef std::map<std::string,Eigen::Vector3d> BodyVector3d; typedef std::map<std::string,Eigen::VectorXd> BodyVectorXd; typedef std::map<std::string,Vector6d> BodyVector6d; /** * @brief Vector coordinates * Constants to index either 6d or 3d coordinate vectors. */ enum Coords3d {X = 0, Y, Z}; std::string coord3dToName(enum Coords3d coord); enum Coords6d {AX = 0, AY, AZ, LX, LY, LZ}; std::string coord6dToName(enum Coords6d coord); /** * @brief The 3-coordinate vector with the angular components (angular velocity or torque) of the * given spatial vector */ Eigen::Vector3d angularPart(Vector6d& vector); /** * @brief The 3-coordinate vector with the linear components (linear * velocity or force) of the given spatial vector. */ Eigen::Vector3d linearPart(Vector6d& vector); /** @brief The translation vector of a homogeneous transform */ Eigen::Vector3d translationVector(Eigen::Matrix4d& hom_transform); /** @brief The rotation matrix of a homogeneous transform */ Eigen::Matrix3d rotationMatrix(Eigen::MatrixBase<Eigen::Matrix4d>& hom_transform); /** * @brief Gets list of bodies (movable and fixed) of the rigid-body system * @param Body& Body ids * @param const RigidBodyDynamics::Model& Model of the rigid-body system */ void getListOfBodies(BodyID& list_body_id, const RigidBodyDynamics::Model& model); /** @brief Print the model information */ void printModelInfo(const RigidBodyDynamics::Model& model); /** * @brief Converts an applied velocity acting at a certain point to spatial velocity * @param Vector6d& Velocity * @param const Eigen::Vector3d& Point * @return Vector6d Spatial velocity */ Vector6d convertPointVelocityToSpatialVelocity(Vector6d& velocity, const Eigen::Vector3d& point); /** * @brief Converts an applied force acting at a certain point to spatial force * @param Vector6d& Force * @param const Eigen::Vector3d& Point * @return Vector6d Spatial force */ Vector6d convertPointForceToSpatialForce(Vector6d& force, const Eigen::Vector3d& point); /** * @brief Computes the Jacobian in certain point of a specific body * @param const RigidBodyDynamics::Model& Model of the rigid-body system * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint position * @param unsigned int Body id * @param const RigidBodyDynamics::Math::Vector3d& 3d Position of the point * @param RigidBodyDynamics::Math::MatrixNd& Jacobian * @param bool Update kinematic state */ void computePointJacobian(RigidBodyDynamics::Model& model, const RigidBodyDynamics::Math::VectorNd &Q, unsigned int body_id, const RigidBodyDynamics::Math::Vector3d& point_position, RigidBodyDynamics::Math::MatrixNd& jacobian, bool update_kinematics); /** * @brief Computes the velocity in certain point of a specific body * @param RigidBodyDynamics::Model& Model of the rigid-body system * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint position * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint velocity * @param unsigned int Body id * @param const Eigen::Vector3d& 3d Position of the point * @param bool Update kinematic state */ rbd::Vector6d computePointVelocity(RigidBodyDynamics::Model& model, const RigidBodyDynamics::Math::VectorNd& Q, const RigidBodyDynamics::Math::VectorNd& QDot, unsigned int body_id, const RigidBodyDynamics::Math::Vector3d point_position, bool update_kinematics); /** * @brief Computes the acceleration in certain point of a specific body * @param RigidBodyDynamics::Model& Model of the rigid-body system * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint position * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint velocity * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint acceleration * @param unsigned int Body id * @param const Eigen::Vector3d& 3d Position of the point * @param bool Update kinematic state */ rbd::Vector6d computePointAcceleration(RigidBodyDynamics::Model& model, const RigidBodyDynamics::Math::VectorNd& Q, const RigidBodyDynamics::Math::VectorNd& QDot, const RigidBodyDynamics::Math::VectorNd& QDDot, unsigned int body_id, const Eigen::Vector3d point_position, bool update_kinematics); /** * @brief Computes the floating-base inverse dynamics * @param RigidBodyDynamcis::Model& Model of the rigid-body system * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint position * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint velocity * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint acceleration * @param RigidBodyDynamics::Math::VectorNd& Joint forces * @param std::vector<RigidBodyDynamcis::Math::SpatialVector>* Applied external forces */ void FloatingBaseInverseDynamics(RigidBodyDynamics::Model& model, const RigidBodyDynamics::Math::VectorNd &Q, const RigidBodyDynamics::Math::VectorNd &QDot, const RigidBodyDynamics::Math::VectorNd &QDDot, RigidBodyDynamics::Math::SpatialVector& base_acc, RigidBodyDynamics::Math::VectorNd &Tau, std::vector<RigidBodyDynamics::Math::SpatialVector> *f_ext = NULL); /** * @brief Computes the floating-base inverse dynamics * @param RigidBodyDynamcis::Model& Model of the rigid-body system * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint position * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint velocity * @param const RigidBodyDynamics::Math::VectorNd& Generalized joint acceleration * @param RigidBodyDynamics::Math::VectorNd& Joint forces * @param std::vector<RigidBodyDynamcis::Math::SpatialVector>* Applied external forces */ void FloatingBaseInverseDynamics(RigidBodyDynamics::Model& model, unsigned int base_dof, const RigidBodyDynamics::Math::VectorNd &Q, const RigidBodyDynamics::Math::VectorNd &QDot, const RigidBodyDynamics::Math::VectorNd &QDDot, RigidBodyDynamics::Math::SpatialVector& base_acc, RigidBodyDynamics::Math::VectorNd &Tau, std::vector<RigidBodyDynamics::Math::SpatialVector> *f_ext = NULL);// TODO experimental } //@namespace rbd } //@namespace dwl #endif
39.438596
97
0.742289
[ "vector", "model", "transform", "3d" ]
8ae6be2cc1e7b2d36ab5a940fbe3abdc4f56c375
12,043
h
C
sdk/xpcom/include/nsIEventQueue.h
rogerdahl/vbox-remote-keyboard
526a9597ccff145becf921b907a93d886cd1a5c9
[ "MIT" ]
null
null
null
sdk/xpcom/include/nsIEventQueue.h
rogerdahl/vbox-remote-keyboard
526a9597ccff145becf921b907a93d886cd1a5c9
[ "MIT" ]
null
null
null
sdk/xpcom/include/nsIEventQueue.h
rogerdahl/vbox-remote-keyboard
526a9597ccff145becf921b907a93d886cd1a5c9
[ "MIT" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /home/vbox/tinderbox/5.1-sdk/src/libs/xpcom18a4/xpcom/threads/nsIEventQueue.idl */ #ifndef __gen_nsIEventQueue_h__ #define __gen_nsIEventQueue_h__ #ifndef __gen_nsIEventTarget_h__ #include "nsIEventTarget.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif #include "prthread.h" // {13D86C61-00A9-11d3-9F2A-00400553EEF0} #define NS_EVENTQUEUE_CID \ { 0x13d86c61, 0xa9, 0x11d3, { 0x9f, 0x2a, 0x0, 0x40, 0x5, 0x53, 0xee, 0xf0 } } #define NS_EVENTQUEUE_CONTRACTID "@mozilla.org/event-queue;1" #define NS_EVENTQUEUE_CLASSNAME "Event Queue" /* starting interface: nsIEventQueue */ #define NS_IEVENTQUEUE_IID_STR "176afb41-00a4-11d3-9f2a-00400553eef0" #define NS_IEVENTQUEUE_IID \ {0x176afb41, 0x00a4, 0x11d3, \ { 0x9f, 0x2a, 0x00, 0x40, 0x05, 0x53, 0xee, 0xf0 }} class NS_NO_VTABLE nsIEventQueue : public nsIEventTarget { public: NS_DEFINE_STATIC_IID_ACCESSOR(NS_IEVENTQUEUE_IID) /* [noscript] void initEvent (in PLEventPtr aEvent, in voidPtr owner, in PLHandleEventProc handler, in PLDestroyEventProc destructor); */ NS_IMETHOD InitEvent(PLEvent * aEvent, void * owner, PLHandleEventProc handler, PLDestroyEventProc destructor) = 0; /* [noscript] void postSynchronousEvent (in PLEventPtr aEvent, out voidPtr aResult); */ NS_IMETHOD PostSynchronousEvent(PLEvent * aEvent, void * *aResult) = 0; /* boolean pendingEvents (); */ NS_IMETHOD PendingEvents(PRBool *_retval) = 0; /* void processPendingEvents (); */ NS_IMETHOD ProcessPendingEvents(void) = 0; /* void eventLoop (); */ NS_IMETHOD EventLoop(void) = 0; /* [noscript] void eventAvailable (in PRBoolRef aResult); */ NS_IMETHOD EventAvailable(PRBool & aResult) = 0; /* [noscript] PLEventPtr getEvent (); */ NS_IMETHOD GetEvent(PLEvent * *_retval) = 0; /* [noscript] void handleEvent (in PLEventPtr aEvent); */ NS_IMETHOD HandleEvent(PLEvent * aEvent) = 0; /* [noscript] PLEventPtr waitForEvent (); */ NS_IMETHOD WaitForEvent(PLEvent * *_retval) = 0; /* [notxpcom] PRInt32 getEventQueueSelectFD (); */ NS_IMETHOD_(PRInt32) GetEventQueueSelectFD(void) = 0; /* void init (in boolean aNative); */ NS_IMETHOD Init(PRBool aNative) = 0; /* [noscript] void initFromPRThread (in PRThreadPtr thread, in boolean aNative); */ NS_IMETHOD InitFromPRThread(PRThread * thread, PRBool aNative) = 0; /* [noscript] void initFromPLQueue (in PLEventQueuePtr aQueue); */ NS_IMETHOD InitFromPLQueue(PLEventQueue * aQueue) = 0; /* void enterMonitor (); */ NS_IMETHOD EnterMonitor(void) = 0; /* void exitMonitor (); */ NS_IMETHOD ExitMonitor(void) = 0; /* [noscript] void revokeEvents (in voidPtr owner); */ NS_IMETHOD RevokeEvents(void * owner) = 0; /* [noscript] PLEventQueuePtr getPLEventQueue (); */ NS_IMETHOD GetPLEventQueue(PLEventQueue * *_retval) = 0; /* boolean isQueueNative (); */ NS_IMETHOD IsQueueNative(PRBool *_retval) = 0; /* void stopAcceptingEvents (); */ NS_IMETHOD StopAcceptingEvents(void) = 0; }; /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIEVENTQUEUE \ NS_IMETHOD InitEvent(PLEvent * aEvent, void * owner, PLHandleEventProc handler, PLDestroyEventProc destructor); \ NS_IMETHOD PostSynchronousEvent(PLEvent * aEvent, void * *aResult); \ NS_IMETHOD PendingEvents(PRBool *_retval); \ NS_IMETHOD ProcessPendingEvents(void); \ NS_IMETHOD EventLoop(void); \ NS_IMETHOD EventAvailable(PRBool & aResult); \ NS_IMETHOD GetEvent(PLEvent * *_retval); \ NS_IMETHOD HandleEvent(PLEvent * aEvent); \ NS_IMETHOD WaitForEvent(PLEvent * *_retval); \ NS_IMETHOD_(PRInt32) GetEventQueueSelectFD(void); \ NS_IMETHOD Init(PRBool aNative); \ NS_IMETHOD InitFromPRThread(PRThread * thread, PRBool aNative); \ NS_IMETHOD InitFromPLQueue(PLEventQueue * aQueue); \ NS_IMETHOD EnterMonitor(void); \ NS_IMETHOD ExitMonitor(void); \ NS_IMETHOD RevokeEvents(void * owner); \ NS_IMETHOD GetPLEventQueue(PLEventQueue * *_retval); \ NS_IMETHOD IsQueueNative(PRBool *_retval); \ NS_IMETHOD StopAcceptingEvents(void); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIEVENTQUEUE(_to) \ NS_IMETHOD InitEvent(PLEvent * aEvent, void * owner, PLHandleEventProc handler, PLDestroyEventProc destructor) { return _to InitEvent(aEvent, owner, handler, destructor); } \ NS_IMETHOD PostSynchronousEvent(PLEvent * aEvent, void * *aResult) { return _to PostSynchronousEvent(aEvent, aResult); } \ NS_IMETHOD PendingEvents(PRBool *_retval) { return _to PendingEvents(_retval); } \ NS_IMETHOD ProcessPendingEvents(void) { return _to ProcessPendingEvents(); } \ NS_IMETHOD EventLoop(void) { return _to EventLoop(); } \ NS_IMETHOD EventAvailable(PRBool & aResult) { return _to EventAvailable(aResult); } \ NS_IMETHOD GetEvent(PLEvent * *_retval) { return _to GetEvent(_retval); } \ NS_IMETHOD HandleEvent(PLEvent * aEvent) { return _to HandleEvent(aEvent); } \ NS_IMETHOD WaitForEvent(PLEvent * *_retval) { return _to WaitForEvent(_retval); } \ NS_IMETHOD_(PRInt32) GetEventQueueSelectFD(void) { return _to GetEventQueueSelectFD(); } \ NS_IMETHOD Init(PRBool aNative) { return _to Init(aNative); } \ NS_IMETHOD InitFromPRThread(PRThread * thread, PRBool aNative) { return _to InitFromPRThread(thread, aNative); } \ NS_IMETHOD InitFromPLQueue(PLEventQueue * aQueue) { return _to InitFromPLQueue(aQueue); } \ NS_IMETHOD EnterMonitor(void) { return _to EnterMonitor(); } \ NS_IMETHOD ExitMonitor(void) { return _to ExitMonitor(); } \ NS_IMETHOD RevokeEvents(void * owner) { return _to RevokeEvents(owner); } \ NS_IMETHOD GetPLEventQueue(PLEventQueue * *_retval) { return _to GetPLEventQueue(_retval); } \ NS_IMETHOD IsQueueNative(PRBool *_retval) { return _to IsQueueNative(_retval); } \ NS_IMETHOD StopAcceptingEvents(void) { return _to StopAcceptingEvents(); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIEVENTQUEUE(_to) \ NS_IMETHOD InitEvent(PLEvent * aEvent, void * owner, PLHandleEventProc handler, PLDestroyEventProc destructor) { return !_to ? NS_ERROR_NULL_POINTER : _to->InitEvent(aEvent, owner, handler, destructor); } \ NS_IMETHOD PostSynchronousEvent(PLEvent * aEvent, void * *aResult) { return !_to ? NS_ERROR_NULL_POINTER : _to->PostSynchronousEvent(aEvent, aResult); } \ NS_IMETHOD PendingEvents(PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->PendingEvents(_retval); } \ NS_IMETHOD ProcessPendingEvents(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->ProcessPendingEvents(); } \ NS_IMETHOD EventLoop(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->EventLoop(); } \ NS_IMETHOD EventAvailable(PRBool & aResult) { return !_to ? NS_ERROR_NULL_POINTER : _to->EventAvailable(aResult); } \ NS_IMETHOD GetEvent(PLEvent * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetEvent(_retval); } \ NS_IMETHOD HandleEvent(PLEvent * aEvent) { return !_to ? NS_ERROR_NULL_POINTER : _to->HandleEvent(aEvent); } \ NS_IMETHOD WaitForEvent(PLEvent * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->WaitForEvent(_retval); } \ NS_IMETHOD_(PRInt32) GetEventQueueSelectFD(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetEventQueueSelectFD(); } \ NS_IMETHOD Init(PRBool aNative) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(aNative); } \ NS_IMETHOD InitFromPRThread(PRThread * thread, PRBool aNative) { return !_to ? NS_ERROR_NULL_POINTER : _to->InitFromPRThread(thread, aNative); } \ NS_IMETHOD InitFromPLQueue(PLEventQueue * aQueue) { return !_to ? NS_ERROR_NULL_POINTER : _to->InitFromPLQueue(aQueue); } \ NS_IMETHOD EnterMonitor(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnterMonitor(); } \ NS_IMETHOD ExitMonitor(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->ExitMonitor(); } \ NS_IMETHOD RevokeEvents(void * owner) { return !_to ? NS_ERROR_NULL_POINTER : _to->RevokeEvents(owner); } \ NS_IMETHOD GetPLEventQueue(PLEventQueue * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPLEventQueue(_retval); } \ NS_IMETHOD IsQueueNative(PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsQueueNative(_retval); } \ NS_IMETHOD StopAcceptingEvents(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->StopAcceptingEvents(); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsEventQueue : public nsIEventQueue { public: NS_DECL_ISUPPORTS NS_DECL_NSIEVENTQUEUE nsEventQueue(); private: ~nsEventQueue(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsEventQueue, nsIEventQueue) nsEventQueue::nsEventQueue() { /* member initializers and constructor code */ } nsEventQueue::~nsEventQueue() { /* destructor code */ } /* [noscript] void initEvent (in PLEventPtr aEvent, in voidPtr owner, in PLHandleEventProc handler, in PLDestroyEventProc destructor); */ NS_IMETHODIMP nsEventQueue::InitEvent(PLEvent * aEvent, void * owner, PLHandleEventProc handler, PLDestroyEventProc destructor) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void postSynchronousEvent (in PLEventPtr aEvent, out voidPtr aResult); */ NS_IMETHODIMP nsEventQueue::PostSynchronousEvent(PLEvent * aEvent, void * *aResult) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean pendingEvents (); */ NS_IMETHODIMP nsEventQueue::PendingEvents(PRBool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void processPendingEvents (); */ NS_IMETHODIMP nsEventQueue::ProcessPendingEvents() { return NS_ERROR_NOT_IMPLEMENTED; } /* void eventLoop (); */ NS_IMETHODIMP nsEventQueue::EventLoop() { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void eventAvailable (in PRBoolRef aResult); */ NS_IMETHODIMP nsEventQueue::EventAvailable(PRBool & aResult) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] PLEventPtr getEvent (); */ NS_IMETHODIMP nsEventQueue::GetEvent(PLEvent * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void handleEvent (in PLEventPtr aEvent); */ NS_IMETHODIMP nsEventQueue::HandleEvent(PLEvent * aEvent) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] PLEventPtr waitForEvent (); */ NS_IMETHODIMP nsEventQueue::WaitForEvent(PLEvent * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* [notxpcom] PRInt32 getEventQueueSelectFD (); */ NS_IMETHODIMP_(PRInt32) nsEventQueue::GetEventQueueSelectFD() { return NS_ERROR_NOT_IMPLEMENTED; } /* void init (in boolean aNative); */ NS_IMETHODIMP nsEventQueue::Init(PRBool aNative) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void initFromPRThread (in PRThreadPtr thread, in boolean aNative); */ NS_IMETHODIMP nsEventQueue::InitFromPRThread(PRThread * thread, PRBool aNative) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void initFromPLQueue (in PLEventQueuePtr aQueue); */ NS_IMETHODIMP nsEventQueue::InitFromPLQueue(PLEventQueue * aQueue) { return NS_ERROR_NOT_IMPLEMENTED; } /* void enterMonitor (); */ NS_IMETHODIMP nsEventQueue::EnterMonitor() { return NS_ERROR_NOT_IMPLEMENTED; } /* void exitMonitor (); */ NS_IMETHODIMP nsEventQueue::ExitMonitor() { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void revokeEvents (in voidPtr owner); */ NS_IMETHODIMP nsEventQueue::RevokeEvents(void * owner) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] PLEventQueuePtr getPLEventQueue (); */ NS_IMETHODIMP nsEventQueue::GetPLEventQueue(PLEventQueue * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isQueueNative (); */ NS_IMETHODIMP nsEventQueue::IsQueueNative(PRBool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void stopAcceptingEvents (); */ NS_IMETHODIMP nsEventQueue::StopAcceptingEvents() { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIEventQueue_h__ */
38.599359
208
0.750727
[ "object" ]
8aeb6e1513e02793ac71ea64d4673c39fe25175e
868
h
C
ScriptViewer/Components/Component.h
pongo1231/V_ScriptViewer
70fcbb8ef9cdc3adacca2656c00eafc577f8dc51
[ "MIT" ]
9
2021-04-29T15:32:41.000Z
2021-12-26T16:14:02.000Z
ScriptViewer/Components/Component.h
SuperCoolNinja/V_ScriptViewer
70fcbb8ef9cdc3adacca2656c00eafc577f8dc51
[ "MIT" ]
null
null
null
ScriptViewer/Components/Component.h
SuperCoolNinja/V_ScriptViewer
70fcbb8ef9cdc3adacca2656c00eafc577f8dc51
[ "MIT" ]
2
2021-05-02T04:34:12.000Z
2021-12-11T22:05:57.000Z
#pragma once #include <vector> typedef unsigned long long DWORD64; class Component; namespace rage { class scrThread; } inline std::vector<Component*> g_rgpComponents; class Component { public: bool m_bIsOpen = false; Component() { g_rgpComponents.push_back(this); } virtual ~Component() { g_rgpComponents.erase(std::find(g_rgpComponents.begin(), g_rgpComponents.end(), this)); } Component(const Component&) = delete; Component& operator=(const Component&) = delete; Component(Component&& component) noexcept : Component() { m_bIsOpen = component.m_bIsOpen; } Component& operator=(Component&&) = delete; virtual bool RunHook(rage::scrThread* pScrThread) { return true; } virtual void RunCallback(rage::scrThread* pScrThread, DWORD64 qwExecutionTime) { } virtual void RunImGui() { } virtual void RunScript() { } };
14.229508
89
0.713134
[ "vector" ]
8aee68e717c6bf9a8f3eaaa3458854ed9efe6023
7,951
h
C
iai/include/tencentcloud/iai/v20180301/model/FaceQualityCompleteness.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
iai/include/tencentcloud/iai/v20180301/model/FaceQualityCompleteness.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
iai/include/tencentcloud/iai/v20180301/model/FaceQualityCompleteness.h
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_IAI_V20180301_MODEL_FACEQUALITYCOMPLETENESS_H_ #define TENCENTCLOUD_IAI_V20180301_MODEL_FACEQUALITYCOMPLETENESS_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Iai { namespace V20180301 { namespace Model { /** * 五官遮挡分,评价眉毛(Eyebrow)、眼睛(Eye)、鼻子(Nose)、脸颊(Cheek)、嘴巴(Mouth)、下巴(Chin)的被遮挡程度。 */ class FaceQualityCompleteness : public AbstractModel { public: FaceQualityCompleteness(); ~FaceQualityCompleteness() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取眉毛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @return Eyebrow 眉毛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t GetEyebrow() const; /** * 设置眉毛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @param Eyebrow 眉毛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ void SetEyebrow(const int64_t& _eyebrow); /** * 判断参数 Eyebrow 是否已赋值 * @return Eyebrow 是否已赋值 */ bool EyebrowHasBeenSet() const; /** * 获取眼睛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @return Eye 眼睛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t GetEye() const; /** * 设置眼睛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @param Eye 眼睛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ void SetEye(const int64_t& _eye); /** * 判断参数 Eye 是否已赋值 * @return Eye 是否已赋值 */ bool EyeHasBeenSet() const; /** * 获取鼻子的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,60]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @return Nose 鼻子的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,60]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t GetNose() const; /** * 设置鼻子的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,60]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @param Nose 鼻子的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,60]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ void SetNose(const int64_t& _nose); /** * 判断参数 Nose 是否已赋值 * @return Nose 是否已赋值 */ bool NoseHasBeenSet() const; /** * 获取脸颊的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @return Cheek 脸颊的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t GetCheek() const; /** * 设置脸颊的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @param Cheek 脸颊的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ void SetCheek(const int64_t& _cheek); /** * 判断参数 Cheek 是否已赋值 * @return Cheek 是否已赋值 */ bool CheekHasBeenSet() const; /** * 获取嘴巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,50]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @return Mouth 嘴巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,50]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t GetMouth() const; /** * 设置嘴巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,50]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @param Mouth 嘴巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,50]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ void SetMouth(const int64_t& _mouth); /** * 判断参数 Mouth 是否已赋值 * @return Mouth 是否已赋值 */ bool MouthHasBeenSet() const; /** * 获取下巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @return Chin 下巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t GetChin() const; /** * 设置下巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 * @param Chin 下巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ void SetChin(const int64_t& _chin); /** * 判断参数 Chin 是否已赋值 * @return Chin 是否已赋值 */ bool ChinHasBeenSet() const; private: /** * 眉毛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_eyebrow; bool m_eyebrowHasBeenSet; /** * 眼睛的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,80]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_eye; bool m_eyeHasBeenSet; /** * 鼻子的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,60]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_nose; bool m_noseHasBeenSet; /** * 脸颊的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_cheek; bool m_cheekHasBeenSet; /** * 嘴巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,50]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_mouth; bool m_mouthHasBeenSet; /** * 下巴的遮挡分数[0,100],分数越高遮挡越少。 参考范围:[0,70]表示发生遮挡。 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_chin; bool m_chinHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_IAI_V20180301_MODEL_FACEQUALITYCOMPLETENESS_H_
30.347328
116
0.47843
[ "vector", "model" ]
8af42d4cc79b82278379f92e3438816ef77742b2
9,203
c
C
thirdparty/glut/progs/demos/skyfly/perfdraw.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
1
2019-01-11T13:55:53.000Z
2019-01-11T13:55:53.000Z
thirdparty/glut/progs/demos/skyfly/perfdraw.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
1
2018-08-10T19:11:58.000Z
2018-08-10T19:12:17.000Z
thirdparty/glut/progs/demos/skyfly/perfdraw.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
null
null
null
/* * perfdraw.c - $Revision: 1.4 $ */ #include <GL/glut.h> #include <math.h> #include <stdio.h> #include "skyfly.h" #if !defined(GL_VERSION_1_1) #if defined(GL_EXT_texture_object) #define glBindTexture(A,B) glBindTextureEXT(A,B) #define glGenTextures(A,B) glGenTexturesEXT(A,B) #define glDeleteTextures(A,B) glDeleteTexturesEXT(A,B) #else #define glBindTexture(A,B) #define glGenTextures(A,B) #define glDeleteTextures(A,B) #endif #endif /* static routine decls */ extern int clouds; static void drawlitmesh_11(float *objdata); static void drawcolrtexmesh_10(float *objdata); static void drawclouds(float *objdata); void drawperfobj(perfobj_t *perfobj) { float *vdata_ptr =(float *) perfobj->vdata; extern void texenv(int), lightpos(void); unsigned int *flagsptr = perfobj->flags; float *dp; for (;;) { switch (*flagsptr) { /* * A paper plane is a single tmesh folded on itself so the orientations * of some triangles in the mesh are incorrect with respect to * their normals. This is solved by drawing the tmesh twice; * first draw only backfaces, then only frontfaces. */ case PD_DRAW_PAPER_PLANE: flagsptr += 1; glCullFace(GL_FRONT); drawlitmesh_11(vdata_ptr); glCullFace(GL_BACK); drawlitmesh_11((float *)((perfobj_vert_t *) vdata_ptr + 11)); glPopMatrix(); break; case PD_DRAW_TERRAIN_CELL: dp = *(float **) (flagsptr + 1); flagsptr += 2; drawcolrtexmesh_10(dp); break; case PD_DRAW_CLOUDS: if (rgbmode) { #if 0 glColor3ub(0x30, 0x40, 0xb0); #else glColor3f(1.0f, 1.0f, 1.0f); #endif } glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); /*texenv(2);*/ drawclouds(vdata_ptr); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); flagsptr += 1; break; case PD_PAPER_PLANE_MODE: switch (*(flagsptr + 1)) { case PLANES_START: glShadeModel(GL_FLAT); glEnable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); if (fog && !rgbmode) glDisable(GL_FOG); break; case PLANES_END: glShadeModel(GL_SMOOTH); glDisable(GL_LIGHTING); if (fog && !rgbmode && FOG_LEVELS > 1) glEnable(GL_FOG); break; } flagsptr += 2; break; case PD_PAPER_PLANE_POS: /* contains the pushmatrix */ glPushMatrix(); glTranslatef(*(vdata_ptr), *(vdata_ptr + 1), *(vdata_ptr + 2)); glRotatef(*(vdata_ptr + 3), 0.0, 0.0, 1.0); glRotatef(*(vdata_ptr + 4), 0.0, 1.0, 0.0); glRotatef(*(vdata_ptr + 5), 1.0, 0.0, 0.0); flagsptr += 1; break; case PD_VIEWER_POS: glLoadIdentity(); glRotatef(-90., 1.0, 0., 0.); glRotatef(*(vdata_ptr + 3) * RAD_TO_DEG, 0.0, 0.0, 1.0); /* yaw */ lightpos(); glTranslatef(-*(vdata_ptr), -*(vdata_ptr + 1), -*(vdata_ptr + 2)); flagsptr += 1; break; case PD_TEXTURE_BIND: glBindTexture(GL_TEXTURE_2D, *(flagsptr + 1)); texenv(*(flagsptr + 1)); glEnable(GL_TEXTURE_2D); flagsptr += 2; break; case PD_END: return; default: fprintf(stderr, "Bad PD primitive %d\n", *flagsptr); flagsptr++; break; } } } /* * Notice how the following routines unwind loops and pre-compute indexes * at compile time. This is crucial in obtaining the maximum data transfer * from cpu to the graphics pipe. */ static void drawlitmesh_11(float *op) { glBegin(GL_TRIANGLE_STRIP); /* one */ glNormal3fv((op + PD_V_NORMAL)); glVertex3fv((op + PD_V_POINT)); /* two */ glNormal3fv((op + (PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (PD_V_SIZE + PD_V_POINT))); /* three */ glNormal3fv((op + (2 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (2 * PD_V_SIZE + PD_V_POINT))); /* four */ glNormal3fv((op + (3 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (3 * PD_V_SIZE + PD_V_POINT))); /* five */ glNormal3fv((op + (4 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (4 * PD_V_SIZE + PD_V_POINT))); /* six */ glNormal3fv((op + (5 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (5 * PD_V_SIZE + PD_V_POINT))); /* seven */ glNormal3fv((op + (6 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (6 * PD_V_SIZE + PD_V_POINT))); /* eight */ glNormal3fv((op + (7 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (7 * PD_V_SIZE + PD_V_POINT))); /* nine */ glNormal3fv((op + (8 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (8 * PD_V_SIZE + PD_V_POINT))); /* ten */ glNormal3fv((op + (9 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (9 * PD_V_SIZE + PD_V_POINT))); /* eleven */ glNormal3fv((op + (10 * PD_V_SIZE + PD_V_NORMAL))); glVertex3fv((op + (10 * PD_V_SIZE + PD_V_POINT))); glEnd(); } static void drawcolrtexmesh_10(float *op) { glBegin(GL_TRIANGLE_STRIP); /* one */ glTexCoord2fv((op + PD_V_TEX)); glColor3fv((op + PD_V_COLOR)); glVertex3fv((op + PD_V_POINT)); /* two */ glTexCoord2fv((op + (PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (PD_V_SIZE + PD_V_POINT))); /* three */ glTexCoord2fv((op + (2 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (2 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (2 * PD_V_SIZE + PD_V_POINT))); /* four */ glTexCoord2fv((op + (3 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (3 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (3 * PD_V_SIZE + PD_V_POINT))); /* five */ glTexCoord2fv((op + (4 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (4 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (4 * PD_V_SIZE + PD_V_POINT))); /* six */ glTexCoord2fv((op + (5 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (5 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (5 * PD_V_SIZE + PD_V_POINT))); /* seven */ glTexCoord2fv((op + (6 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (6 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (6 * PD_V_SIZE + PD_V_POINT))); /* eight */ glTexCoord2fv((op + (7 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (7 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (7 * PD_V_SIZE + PD_V_POINT))); /* nine */ glTexCoord2fv((op + (8 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (8 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (8 * PD_V_SIZE + PD_V_POINT))); /* ten */ glTexCoord2fv((op + (9 * PD_V_SIZE + PD_V_TEX))); glColor3fv((op + (9 * PD_V_SIZE + PD_V_COLOR))); glVertex3fv((op + (9 * PD_V_SIZE + PD_V_POINT))); glEnd(); } static void drawclouds(float *op) { #define SKY_STRIPS 24 /* Break into quad strips so cheap fog works better */ if (0 == clouds) { GLfloat *vc0, *vc1, *vc2; GLfloat *tc0, *tc1, *tc2; GLfloat sky_s0, sky_s1, sky_t0, sky_t1; GLfloat sky_x0, sky_x1, sky_y0, sky_y1, sky_z; int ii, jj; GLfloat s0, s1, t0, t1; GLfloat x0, x1, y0, y1, z0; vc0 = op + PD_V_POINT; vc1 = op + PD_V_POINT + PD_V_SIZE; vc2 = op + PD_V_POINT + PD_V_SIZE * 2; tc0 = op + PD_V_TEX; tc1 = op + PD_V_TEX + PD_V_SIZE; tc2 = op + PD_V_TEX + PD_V_SIZE * 2; sky_s0 = tc0[0]; sky_s1 = tc1[0]; sky_t0 = tc0[1]; sky_t1 = tc2[1]; sky_x0 = vc0[0]; sky_x1 = vc1[0]; sky_y0 = vc0[1]; sky_y1 = vc2[1]; sky_z = vc0[2]; clouds = glGenLists(1); glNewList(clouds, GL_COMPILE); s1 = (1.0f / SKY_STRIPS) * (sky_s1 - sky_s0); t1 = (1.0f / SKY_STRIPS) * (sky_t1 - sky_t0); x1 = (1.0f / SKY_STRIPS) * (sky_x1 - sky_x0); y1 = (1.0f / SKY_STRIPS) * (sky_y1 - sky_y0); z0 = sky_z; s0 = sky_s0; x0 = sky_x0; for (ii = 0; ii < SKY_STRIPS; ii++, s0 += s1, x0 += x1) { t0 = sky_t0; y0 = sky_y0; glBegin(GL_QUAD_STRIP); glTexCoord2f(s0, t0); glVertex3f(x0, y0, z0); glTexCoord2f(s0 + s1, t0); glVertex3f(x0 + x1, y0, z0); for (jj = 0; jj < SKY_STRIPS; jj++, t0 += t1, y0 += y1) { glTexCoord2f(s0 + s1, t0 + t1); glVertex3f(x0 + x1, y0 + y1, z0); glTexCoord2f(s0, t0 + t1); glVertex3f(x0, y0 + y1, z0); } glEnd(); } glEndList(); } glCallList(clouds); } void putv3fdata(float *v, perfobj_vert_t *ptr) { ptr->vert[0] = v[0]; ptr->vert[1] = v[1]; ptr->vert[2] = v[2]; } void putc3fdata(float *c, perfobj_vert_t *ptr) { ptr->color[0] = c[0]; ptr->color[1] = c[1]; ptr->color[2] = c[2]; } void putn3fdata(float *n, perfobj_vert_t *ptr) { ptr->normal[0] = n[0]; ptr->normal[1] = n[1]; ptr->normal[2] = n[2]; } void putt2fdata(float *t, perfobj_vert_t *ptr) { ptr->texture[0] = t[0]; ptr->texture[1] = t[1]; }
27.71988
75
0.561882
[ "mesh" ]
8af750ad4e32694de1e5eb205635726914f06530
16,957
c
C
rtsARM/rts.c
nordlander/timberc
291ed8feeea14305c8a6845a8789ea8c0e14a9f3
[ "BSD-3-Clause" ]
null
null
null
rtsARM/rts.c
nordlander/timberc
291ed8feeea14305c8a6845a8789ea8c0e14a9f3
[ "BSD-3-Clause" ]
null
null
null
rtsARM/rts.c
nordlander/timberc
291ed8feeea14305c8a6845a8789ea8c0e14a9f3
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2009, Per Lindgren, Johan Eriksson, Johan Nordlander, * Simon Aittamaa. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Luleå University of Technology nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "rts.h" #include <lpc2468_registers.h> // Context switching ------------------------------------------------------------------------------ #define ARM7_CONTEXT_SAVE() \ __asm__ __volatile__ (\ /* r0 & r1 is used as a temporary register, we need lr in swi mode. */\ "stmfd sp!, {r0,r1,lr}\n"\ /* Disable interrupts */\ "mrs r0, cpsr\n"\ "orr r0, r0, #0xc0\n"\ "msr cpsr_c, r0\n"\ /* Get the user mode stack pointer value. */\ "stmdb sp, {sp}^\n"\ "nop\n"\ "ldmdb sp, {r0}\n"\ /* Store the return address at the first/highest address. */\ "sub lr, lr, #4\n"\ "stmfd r0!, {lr}\n"\ /* Start using lr and restore old r0. */\ "mov lr, r0\n"\ "ldmfd sp, {r0}\n"\ /* Save all user mode registers. */\ "stmfd lr, {r0-r14}^\n"\ "nop\n"\ "sub lr, lr, #60\n"\ /* Save the saved process register. */\ "mrs r0, SPSR\n"\ "stmfd lr!, {r0}\n"\ /* Save the stack pointer to the the current_thread variable. */\ "ldr r0, =current_thread\n"\ "ldr r0, [r0]\n"\ "str lr, [r0]\n"\ /* Check the context cookie. */\ "ldr r0, [r0, #4]\n"\ "ldr r0, [r0]\n"\ "ldr r1, =context_cookie\n"\ "ldr r1, [r1]\n"\ "cmp r0, r1\n"\ "bne context_panic\n"\ /* \ * Restore the old r0 _again_, this is so we can use this macro\ * in the software interrupt as well. Don't forget the original\ * lr as well for interrupt id.\ */\ "ldmfd sp!, {r0,r1,lr}\n"\ ) #define ARM7_CONTEXT_RESTORE() \ __asm__ __volatile__ (\ /* Load the current context stack pointer. */\ "ldr r0, =current_thread\n"\ "ldr r0, [r0]\n"\ "ldr lr, [r0]\n"\ /* Check the context cookie. */\ "ldr r0, [r0, #4]\n"\ "ldr r0, [r0]\n"\ "ldr r1, =context_cookie\n"\ "ldr r1, [r1]\n"\ "cmp r0, r1\n"\ "bne context_panic\n"\ /* Restore the saved saved process status. */\ "ldmfd lr!, {r0}\n"\ "msr SPSR, r0\n"\ /* Restore the user context. */\ "ldmfd lr, {r0-r14}^\n"\ "nop\n"\ "add lr, lr, #60\n"\ /* Get the return address and return(leaves interrupt..). */\ "ldmfd lr, {pc}^\n"\ ) __attribute__((naked)) void dispatch( Thread next ) { // Note: parameter 'next' is vital -- goes into r0 // See swi_handler() below. asm volatile( "swi 0\n" "mov pc, lr\n" ); } // Macros ---------------------------------------------------------------------------------------- #define NTHREADS 5 #define STACKSIZE WORDS(0x10000) // 0x10000 bytes = 64 kB #define SLEEP() /* not yet defined */ #define TDELTA 1 #define TIMERINIT() { T0TCR = 0; T0TCR = 1; /* stop & reset clock */ \ T0IR = (1<<0); /* MR0 int en */ \ T0PR = (576 -1); /* 1tick = 10uS , at MCLK = 57.6Mhz*/ \ T0MCR = (1<<0); \ VICVectAddr4 = (unsigned long)timer0_interrupt; \ VICIntEnable |= (1<<4); \ } #define TIMERGET(x) { x.tv_usec = T0TC; x.tv_sec = x.tv_usec / 100000; x.tv_usec = (x.tv_usec % 100000) * 10; } #define TIMERSET(x,now) { T0MR0 = (x).tv_sec*100000 + (x).tv_usec / 10; \ if ((T0MR0 < T0TC)) \ VICSoftInt = 1<<4; \ } #define TIMERACK() { VICSoftIntClr = (1<<4); T0IR = T0IR; } // Globals -------------------------------------------------------------------------------------- struct Msg msg0 = { NULL, NULL, NULL, NULL, NULL, {0, 0}, {0, 0} }; struct Thread threads[NTHREADS]; // the idle (=main) thread struct Thread threadI; Msg savedMsg = NULL; Msg msgQ = NULL; Msg timerQ = NULL; Thread threadPool = &threads[0]; Thread activeStack = &threadI; Thread current_thread = &threadI; extern WORD _end; extern WORD __ram_end; WORD context_cookie = 0x55aa55aa; WORD thestacks[NTHREADS*STACKSIZE]; // Printing & halting ------------------------------------------------------------------------------ void debug_char(char c) { while (!(U0LSR & (1<<5))); U0THR = c; if (c == '\n') { while (!(U0LSR & (1<<5))); U0THR = '\r'; } } void debug(char *msg) { while (*msg) debug_char(*msg++); } void debug_hex(unsigned long value) { static char hex[] = "0123456789abcdef"; while (!(U0LSR & (1<<5))); U0THR = hex[value>>28&0xf]; while (!(U0LSR & (1<<5))); U0THR = hex[value>>24&0xf]; while (!(U0LSR & (1<<5))); U0THR = hex[value>>20&0xf]; while (!(U0LSR & (1<<5))); U0THR = hex[value>>16&0xf]; while (!(U0LSR & (1<<5))); U0THR = hex[value>>12&0xf]; while (!(U0LSR & (1<<5))); U0THR = hex[value>>8&0xf]; while (!(U0LSR & (1<<5))); U0THR = hex[value>>4&0xf]; while (!(U0LSR & (1<<5))); U0THR = hex[value&0xf]; while (!(U0LSR & (1<<5))); } void panic(char *str) { PROTECT(1); debug(str); for (;;); } void context_panic(void) { panic("Context cookie corrupted.\r\n"); } // Memory management -------------------------------------------------------------------------------- #include "gc.c" // Cyclic data handling ----------------------------------------------------------------------------- #include "cyclic.c" // GCINFO definitions for the built-in types ----------------------------------------------------- #include "timber.c" // Queue management ------------------------------------------------------------------------------ void enqueueMsgQ(Msg p) { Msg prev = NULL, q = msgQ; while (q && ABS_LE(q->deadline, p->deadline)) { prev = q; q = q->next; } p->next = q; if (prev == NULL) msgQ = p; else prev->next = p; } void enqueueTimerQ(Msg p) { Msg prev = NULL, q = timerQ; while (q && ABS_LE(q->baseline, p->baseline)) { prev = q; q = q->next; } p->next = q; if (prev == NULL) timerQ = p; else prev->next = p; } void activate(void) { Thread t = threadPool; threadPool = threadPool->next; t->next = activeStack; activeStack = t; } void deactivate(void) { Thread t = activeStack; activeStack = activeStack->next; t->next = threadPool; threadPool = t; } // Major primitives --------------------------------------------------------------------- void IRQ_PROLOGUE(void) { savedMsg = current_thread->msg; current_thread->msg = &msg0; TIMERGET(msg0.baseline); } void IRQ_EPILOGUE(void) { current_thread->msg = savedMsg; Msg topMsg = activeStack->msg; if (msgQ && threadPool && ((!topMsg) || ABS_LT(msgQ->deadline, topMsg->deadline))) { activate(); current_thread = activeStack; } } void RUN(void) { while (1) { Msg this = current_thread->msg = msgQ; msgQ = msgQ->next; PROTECT(0); this->Obj = LOCK(this->Obj); UNIT (*code)(Msg,OID) = this->Code; if (code) code(this, this->Obj); UNLOCK(this->Obj); PROTECT(1); current_thread->msg = NULL; Msg oldMsg = activeStack->next->msg; if (!msgQ || (oldMsg && ABS_LT(oldMsg->deadline, msgQ->deadline))) { deactivate(); Thread t = activeStack; // can't be NULL, may be &threadI while (t->waitsFor) t = ((Ref)t->waitsFor)->ownedBy; dispatch(t); } } } Msg ASYNC( Msg m, Time bl, Time dl ) { if (bl) { m->baseline = current_thread->msg->baseline; ABS_ADD(m->baseline, bl); if (dl) { m->deadline = m->baseline; ABS_ADD(m->deadline, dl); } else if (ABS_LT(m->baseline, current_thread->msg->deadline)) m->deadline = current_thread->msg->deadline; else m->deadline = absInfinity; int status = ISPROTECTED(); PROTECT(1); m->sender = NULL; AbsTime now; TIMERGET(now); if (ABS_LT(now, m->baseline)) { enqueueTimerQ(m); rootsDirty = 1; if (timerQ == m) TIMERSET(timerQ->baseline, now); } else enqueueMsgQ(m); PROTECT(status); } else { m->Obj = LOCK(m->Obj); UNIT (*code)(Msg,OID) = m->Code; if (code) code(m, m->Obj); UNLOCK(m->Obj); } return m; } void INITREF( Ref obj ) { obj->GCINFO = __GC__Ref; obj->wantedBy = 0; obj->ownedBy = 0; obj->STATE = (ADDR)STATEOF(obj); // actually unused, but keep it clean } OID LOCK( OID obj ) { int status = ISPROTECTED(); PROTECT(1); GC_PROLOGUE(obj); Thread t = obj->ownedBy; if (t) { // "obj" is already locked while (t->waitsFor) t = t->waitsFor->ownedBy; if (t == current_thread) // deadlock panic("Deadlock"); if (obj->wantedBy) obj->wantedBy->waitsFor = NULL; obj->wantedBy = current_thread; current_thread->waitsFor = obj; dispatch(t); GC_PROLOGUE(obj); // in case t was the GC } obj->ownedBy = current_thread; PROTECT(status); return obj; } void GC_LOCK( OID obj ) { PROTECT(1); Thread t = obj->ownedBy; if (t) panic("GC found locked object"); obj->ownedBy = current_thread; PROTECT(0); } UNIT UNLOCK( OID obj ) { int status = ISPROTECTED(); PROTECT(1); obj->ownedBy = NULL; Thread t = obj->wantedBy; if (t) { // we have run on someone's behalf obj->wantedBy = NULL; t->waitsFor = NULL; dispatch(t); } GC_EPILOGUE(obj); PROTECT(status); return (UNIT)0; } void GC_UNLOCK( OID obj ) { PROTECT(1); obj->ownedBy = NULL; Thread t = obj->wantedBy; if (t) { // we have run on someone's behalf obj->wantedBy = NULL; t->waitsFor = NULL; dispatch(t); } PROTECT(0); } UNIT ABORT(BITS32 polytag, Msg m, Ref dummy) { m->Code = NULL; ADDR info; do { info = IND0((ADDR)m); if (ISODD(info)) ((Msg)((ADDR)m)[1])->Code = NULL; } while (info != IND0((ADDR)m)); return (UNIT)0; } void RAISE(Int err) { panic("Unhandled exception"); } POLY Raise(BITS32 polyTag, Int err) { RAISE(err); return NULL; } // Arrays --------------------------------------------------------------------------------------------- #include "arrays.c" // Timer ---------------------------------------------------------------------------------------------- #include "timer.c" // Show Float ----------------------------------------------------------------------------------------- int snprintf(char *s, int n, const char *format, ...) { char *p = "<float>"; while (*p) *s++ = *p++; return 7; } #include "float.c" // The timer queue ------------------------------------------------------------------------------------- void scanTimerQ(void) { PROTECT(1); if (timerQ) { timerQ = (Msg)copy((ADDR)timerQ); Msg m = timerQ; PROTECT(0); PROTECT(1); Msg next = m->next; while (next) { m->next = (Msg)copy((ADDR)next); m = m->next; PROTECT(0); PROTECT(1); next = m->next; } } PROTECT(0); } struct Scanner timerQscanner = { scanTimerQ, NULL }; void timer0_interrupt(void) { IRQ_PROLOGUE(); TIMERACK(); while (timerQ && ABS_LE(timerQ->baseline, msg0.baseline)) { Msg m = timerQ; timerQ = timerQ->next; enqueueMsgQ(m); } if (timerQ) TIMERSET(timerQ->baseline, msg0.baseline); IRQ_EPILOGUE(); } // Bare metal exception handlers ---------------------------------------------------------------------- void *bad_pc = 0; __attribute__((naked)) void undef_handler(void) { asm volatile( "ldr r0, =bad_pc\n" "str lr, [r0]\n" ); panic("Undefined instruction exception\r\n"); } __attribute__((naked)) void code_abort_handler(void) { asm volatile( "ldr r0, =bad_pc\n" "str lr, [r0]\n" ); panic("Code abort exception\r\n"); } __attribute__((naked)) void data_abort_handler(void) { asm volatile( "ldr r0, =bad_pc\n" "str lr, [r0]\n" ); panic("Data abort exception\r\n"); } __attribute__((naked)) void fiq_handler(void) { asm volatile( "ldr r0, =bad_pc\n" "str lr, [r0]\n" ); panic("FIQ exception\r\n"); } void *vic_ivr = (void*)&VICVectAddr; __attribute__((naked)) void irq_handler(void) { ARM7_CONTEXT_SAVE(); asm volatile( "ldr r0, =vic_ivr\n" "ldr r0, [r0]\n" "ldr r0, [r0]\n" "mov lr, pc\n" "bx r0\n" "ldr r0, =vic_ivr\n" "ldr r0, [r0]\n" "str r0, [r0]\n" ); ARM7_CONTEXT_RESTORE(); } __attribute__((naked)) void swi_handler(void) { // Adjudt the link register so that we can treat this as a regular // interrupt ie. use save/restore context macros. // Note: expects Thread parameter in r0 asm volatile("add lr, lr, #4\n"); ARM7_CONTEXT_SAVE(); asm volatile( "ldr r4, =current_thread\n" "str r0, [r4]\n" ); ARM7_CONTEXT_RESTORE(); } // Startup ----------------------------------------------------------------------------------------- void idle(void) { while (1) { PROTECT(1); if (heapLevel(16) > 13) gc(0); PROTECT(0); SLEEP(); } } void startup(Time_Time_to_Msg prog) { prog->Code(prog, Inherit, Inherit); current_thread->msg = NULL; if (msgQ) { activate(); dispatch(activeStack); } idle(); } // Initialization ------------------------------------------------------------------------------------- void thread_init(int i) { int j; arm7_context_t *context = &threads[i].context; context->cookie = &thestacks[i*STACKSIZE]; *context->cookie = context_cookie; context->sp = &thestacks[(i+1)*STACKSIZE]; ADDR sp = context->sp; // Push the return address *(--context->sp) = (WORD)RUN; // Push a bogus link register *(--context->sp) = 0x00000000; // Push the stack pointer *(--context->sp) = (WORD)sp; // Push some fake registers for (j=13; j>0; j--) *(--context->sp) = 0x00000000; // Push the SPSR (system mode, all interrupts disabled) *(--context->sp) = 0xdf; } void init_threads(void) { int i; for (i=0; i<NTHREADS; i++) { threads[i].next = i == NTHREADS-1 ? NULL : &threads[i+1]; threads[i].waitsFor = NULL; threads[i].msg = NULL; threads[i].placeholders = 0; threads[i].thread_no = i; thread_init(i); } if (&__ram_end - &_end < STACKSIZE) panic("Not enough stack for startup/idle thread"); threadI.next = NULL; threadI.thread_no = -1; threadI.waitsFor = NULL; threadI.msg = NULL; threadI.placeholders = 0; threadI.context.cookie = &_end; *threadI.context.cookie = context_cookie; } void init_rts(int argc, char **argv) { PROTECT(1); TIMERINIT(); gcInit(); addRootScanner(&timerQscanner); init_threads(); current_thread->msg = &msg0; TIMERGET(msg0.baseline); }
25.770517
115
0.520375
[ "object" ]
8af7e7a6389fef4de8196f98a24d9bd5a85c8806
60,332
c
C
sys/bus/cam/scsi/scsi_da.c
grimreaper/dragonflybsd
c8995a5576b2484635166f81e8ba4a3e830d8551
[ "BSD-3-Clause" ]
1
2019-01-23T07:03:52.000Z
2019-01-23T07:03:52.000Z
sys/bus/cam/scsi/scsi_da.c
grimreaper/dragonflybsd
c8995a5576b2484635166f81e8ba4a3e830d8551
[ "BSD-3-Clause" ]
null
null
null
sys/bus/cam/scsi/scsi_da.c
grimreaper/dragonflybsd
c8995a5576b2484635166f81e8ba4a3e830d8551
[ "BSD-3-Clause" ]
null
null
null
/* * Implementation of SCSI Direct Access Peripheral driver for CAM. * * Copyright (c) 1997 Justin T. Gibbs. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification, immediately at the beginning of the file. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/sys/cam/scsi/scsi_da.c,v 1.42.2.46 2003/10/21 22:18:19 thomas Exp $ */ #include <sys/param.h> #ifdef _KERNEL #include <sys/systm.h> #include <sys/kernel.h> #include <sys/buf.h> #include <sys/sysctl.h> #include <sys/taskqueue.h> #include <sys/lock.h> #include <sys/conf.h> #include <sys/devicestat.h> #include <sys/disk.h> #include <sys/dtype.h> #include <sys/eventhandler.h> #include <sys/malloc.h> #include <sys/cons.h> #include <sys/proc.h> #include <sys/ioctl_compat.h> #include <sys/buf2.h> #include <sys/thread2.h> #endif /* _KERNEL */ #ifdef _KERNEL #include <vm/pmap.h> #endif #ifndef _KERNEL #include <stdio.h> #include <string.h> #endif /* _KERNEL */ #include <sys/camlib.h> #include "../cam.h" #include "../cam_ccb.h" #include "../cam_extend.h" #include "../cam_periph.h" #include "../cam_xpt_periph.h" #include "../cam_sim.h" #include "scsi_message.h" #ifndef _KERNEL #include "scsi_da.h" #endif /* !_KERNEL */ #ifdef _KERNEL typedef enum { DA_STATE_PROBE, DA_STATE_PROBE2, DA_STATE_NORMAL } da_state; typedef enum { DA_FLAG_PACK_INVALID = 0x001, DA_FLAG_NEW_PACK = 0x002, DA_FLAG_PACK_LOCKED = 0x004, DA_FLAG_PACK_REMOVABLE = 0x008, DA_FLAG_TAGGED_QUEUING = 0x010, DA_FLAG_RETRY_UA = 0x080, DA_FLAG_OPEN = 0x100, DA_FLAG_SCTX_INIT = 0x200, DA_FLAG_RD_LIMIT = 0x400, DA_FLAG_WR_LIMIT = 0x800, DA_FLAG_CAN_TRIM = 0x1000 } da_flags; typedef enum { DA_Q_NONE = 0x00, DA_Q_NO_SYNC_CACHE = 0x01, DA_Q_NO_6_BYTE = 0x02, DA_Q_NO_PREVENT = 0x04 } da_quirks; typedef enum { DA_CCB_POLLED = 0x00, DA_CCB_PROBE = 0x01, DA_CCB_PROBE2 = 0x02, DA_CCB_BUFFER_IO = 0x03, DA_CCB_WAITING = 0x04, DA_CCB_DUMP = 0x05, DA_CCB_TRIM = 0x06, DA_CCB_TYPE_MASK = 0x0F, DA_CCB_RETRY_UA = 0x10 } da_ccb_state; /* Offsets into our private area for storing information */ #define ccb_state ppriv_field0 #define ccb_bio ppriv_ptr1 struct disk_params { u_int8_t heads; u_int32_t cylinders; u_int8_t secs_per_track; u_int32_t secsize; /* Number of bytes/sector */ u_int64_t sectors; /* total number sectors */ }; #define TRIM_MAX_BLOCKS 8 #define TRIM_MAX_RANGES TRIM_MAX_BLOCKS * 64 struct trim_request { uint8_t data[TRIM_MAX_RANGES * 8]; struct bio *bios[TRIM_MAX_RANGES]; }; struct da_softc { struct bio_queue_head bio_queue_rd; struct bio_queue_head bio_queue_wr; struct bio_queue_head bio_queue_trim; struct devstat device_stats; SLIST_ENTRY(da_softc) links; LIST_HEAD(, ccb_hdr) pending_ccbs; da_state state; da_flags flags; da_quirks quirks; int minimum_cmd_size; int outstanding_cmds_rd; int outstanding_cmds_wr; int trim_max_ranges; int trim_running; int trim_enabled; struct disk_params params; struct disk disk; union ccb saved_ccb; struct task sysctl_task; struct sysctl_ctx_list sysctl_ctx; struct sysctl_oid *sysctl_tree; struct trim_request trim_req; }; struct da_quirk_entry { struct scsi_inquiry_pattern inq_pat; da_quirks quirks; }; static const char quantum[] = "QUANTUM"; static const char microp[] = "MICROP"; static struct da_quirk_entry da_quirk_table[] = { /* SPI, FC devices */ { /* * Fujitsu M2513A MO drives. * Tested devices: M2513A2 firmware versions 1200 & 1300. * (dip switch selects whether T_DIRECT or T_OPTICAL device) * Reported by: W.Scholten <whs@xs4all.nl> */ {T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* See above. */ {T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * This particular Fujitsu drive doesn't like the * synchronize cache command. * Reported by: Tom Jackson <toj@gorilla.net> */ {T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * This drive doesn't like the synchronize cache command * either. Reported by: Matthew Jacob <mjacob@feral.com> * in NetBSD PR kern/6027, August 24, 1998. */ {T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * This drive doesn't like the synchronize cache command * either. Reported by: Hellmuth Michaelis (hm@kts.org) * (PR 8882). */ {T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * Doesn't like the synchronize cache command. * Reported by: Blaz Zupan <blaz@gold.amis.net> */ {T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * Doesn't like the synchronize cache command. * Reported by: Blaz Zupan <blaz@gold.amis.net> */ {T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * Doesn't like the synchronize cache command. */ {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * Doesn't like the synchronize cache command. * Reported by: walter@pelissero.de */ {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * Doesn't work correctly with 6 byte reads/writes. * Returns illegal request, and points to byte 9 of the * 6-byte CDB. * Reported by: Adam McDougall <bsdx@spawnet.com> */ {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"}, /*quirks*/ DA_Q_NO_6_BYTE }, { /* See above. */ {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"}, /*quirks*/ DA_Q_NO_6_BYTE }, { /* * Doesn't like the synchronize cache command. * Reported by: walter@pelissero.de */ {T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * The CISS RAID controllers do not support SYNC_CACHE */ {T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, { /* * The same goes for the mly(4) controllers */ {T_DIRECT, SIP_MEDIA_FIXED, "MLY*", "*", "MYLX"}, /*quirks*/ DA_Q_NO_SYNC_CACHE }, /* * USB mass storage devices supported by umass(4) * * NOTE: USB attachments automatically set DA_Q_NO_SYNC_CACHE so * it does not have to be specified here. */ { /* * Creative Nomad MUVO mp3 player (USB) * PR: kern/53094 */ {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"}, /*quirks*/ DA_Q_NO_PREVENT }, { /* * Sigmatel USB Flash MP3 Player * PR: kern/57046 */ {T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"}, /*quirks*/ DA_Q_NO_PREVENT }, { /* * SEAGRAND NP-900 MP3 Player * PR: kern/64563 */ {T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"}, /*quirks*/ DA_Q_NO_PREVENT }, { /* * Creative MUVO Slim mp3 player (USB) * PR: usb/86131 */ {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim", "*"}, /*quirks*/ DA_Q_NO_PREVENT }, { /* * Philips USB Key Audio KEY013 * PR: usb/68412 */ {T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"}, /*quirks*/ DA_Q_NO_PREVENT }, }; static d_open_t daopen; static d_close_t daclose; static d_strategy_t dastrategy; static d_dump_t dadump; static d_ioctl_t daioctl; static periph_init_t dainit; static void daasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg); static int dacmdsizesysctl(SYSCTL_HANDLER_ARGS); static periph_ctor_t daregister; static periph_dtor_t dacleanup; static periph_start_t dastart; static periph_oninv_t daoninvalidate; static void dadone(struct cam_periph *periph, union ccb *done_ccb); static int daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags); static void daprevent(struct cam_periph *periph, int action); static int dagetcapacity(struct cam_periph *periph); static int dacheckmedia(struct cam_periph *periph); static void dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector); static void daflushbioq(struct bio_queue_head *bioq, int error); static void dashutdown(void *arg, int howto); #ifndef DA_DEFAULT_TIMEOUT #define DA_DEFAULT_TIMEOUT 60 /* Timeout in seconds */ #endif #ifndef DA_DEFAULT_RETRY #define DA_DEFAULT_RETRY 4 #endif static int da_retry_count = DA_DEFAULT_RETRY; static int da_default_timeout = DA_DEFAULT_TIMEOUT; SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0, "CAM Direct Access Disk driver"); SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW, &da_retry_count, 0, "Normal I/O retry count"); TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count); SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW, &da_default_timeout, 0, "Normal I/O timeout (in seconds)"); TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout); static struct periph_driver dadriver = { dainit, "da", TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0 }; PERIPHDRIVER_DECLARE(da, dadriver); static struct dev_ops da_ops = { { "da", 0, D_DISK | D_MPSAFE }, .d_open = daopen, .d_close = daclose, .d_read = physread, .d_write = physwrite, .d_strategy = dastrategy, .d_dump = dadump, .d_ioctl = daioctl }; static struct extend_array *daperiphs; MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers"); static int daioctl(struct dev_ioctl_args *ap) { int unit; int error = 0; struct buf *bp; struct cam_periph *periph; int byte_count; off_t *del_num = (off_t*)ap->a_data; off_t bytes_left; off_t bytes_start; cdev_t dev = ap->a_head.a_dev; unit = dkunit(dev); periph = cam_extend_get(daperiphs, unit); if (periph == NULL) return(ENXIO); switch (ap->a_cmd) { case IOCTLTRIM: { bytes_left = del_num[1]; bytes_start = del_num[0]; /* TRIM occurs on 512-byte sectors. */ KKASSERT((bytes_left % 512) == 0); KKASSERT((bytes_start% 512) == 0); /* Break TRIM up into int-sized commands because of b_bcount */ while(bytes_left) { /* * Rather than than squezing out more blocks in b_bcount * and having to break up the TRIM request in da_start(), * we ensure we can always TRIM this many bytes with one * TRIM command (this happens if the device only * supports one TRIM block). * * With min TRIM blksize of 1, TRIM command free * 4194240 blks(64*65535): each LBA range can address * 65535 blks and there 64 such ranges in a 512-byte * block. And, 4194240 * 512 = 0x7FFF8000 * */ byte_count = MIN(bytes_left,0x7FFF8000); bp = getnewbuf(0, 0, 0, 1); bp->b_cmd = BUF_CMD_FREEBLKS; bp->b_bio1.bio_offset = bytes_start; bp->b_bcount = byte_count; bp->b_bio1.bio_flags |= BIO_SYNC; bp->b_bio1.bio_done = biodone_sync; dev_dstrategy(ap->a_head.a_dev, &bp->b_bio1); if (biowait(&bp->b_bio1, "TRIM")) { kprintf("Error:%d\n", bp->b_error); brelse(bp); return(bp->b_error ? bp->b_error : EIO); } brelse(bp); bytes_left -= byte_count; bytes_start += byte_count; } break; } default: return(EINVAL); } return(error); } static int daopen(struct dev_open_args *ap) { cdev_t dev = ap->a_head.a_dev; struct cam_periph *periph; struct da_softc *softc; struct disk_info info; int unit; int error; unit = dkunit(dev); periph = cam_extend_get(daperiphs, unit); if (periph == NULL) { return (ENXIO); } if (cam_periph_acquire(periph) != CAM_REQ_CMP) { return(ENXIO); } cam_periph_lock(periph); if ((error = cam_periph_hold(periph, PCATCH)) != 0) { cam_periph_unlock(periph); cam_periph_release(periph); return (error); } unit = periph->unit_number; softc = (struct da_softc *)periph->softc; CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("daopen: dev=%s (unit %d)\n", devtoname(dev), unit)); if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) { /* Invalidate our pack information. */ disk_invalidate(&softc->disk); softc->flags &= ~DA_FLAG_PACK_INVALID; } error = dacheckmedia(periph); softc->flags |= DA_FLAG_OPEN; if (error == 0) { struct ccb_getdev cgd; /* Build disk information structure */ bzero(&info, sizeof(info)); info.d_type = DTYPE_SCSI; /* * Grab the inquiry data to get the vendor and product names. * Put them in the typename and packname for the label. */ xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1); cgd.ccb_h.func_code = XPT_GDEV_TYPE; xpt_action((union ccb *)&cgd); /* * Check to see whether or not the blocksize is set yet. * If it isn't, set it and then clear the blocksize * unavailable flag for the device statistics. */ if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0){ softc->device_stats.block_size = softc->params.secsize; softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE; } } if (error == 0) { if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 && (softc->quirks & DA_Q_NO_PREVENT) == 0) daprevent(periph, PR_PREVENT); } else { softc->flags &= ~DA_FLAG_OPEN; cam_periph_release(periph); } cam_periph_unhold(periph, 1); return (error); } static int daclose(struct dev_close_args *ap) { cdev_t dev = ap->a_head.a_dev; struct cam_periph *periph; struct da_softc *softc; int unit; int error; unit = dkunit(dev); periph = cam_extend_get(daperiphs, unit); if (periph == NULL) return (ENXIO); cam_periph_lock(periph); if ((error = cam_periph_hold(periph, 0)) != 0) { cam_periph_unlock(periph); cam_periph_release(periph); return (error); } softc = (struct da_softc *)periph->softc; if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) { union ccb *ccb; ccb = cam_periph_getccb(periph, /*priority*/1); ccb->ccb_h.ccb_state = DA_CCB_POLLED; scsi_synchronize_cache(&ccb->csio, /*retries*/1, /*cbfcnp*/dadone, MSG_SIMPLE_Q_TAG, /*begin_lba*/0,/* Cover the whole disk */ /*lb_count*/0, SSD_FULL_SIZE, 5 * 60 * 1000); cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0, /*sense_flags*/SF_RETRY_UA, &softc->device_stats); if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR) { int asc, ascq; int sense_key, error_code; scsi_extract_sense(&ccb->csio.sense_data, &error_code, &sense_key, &asc, &ascq); if (sense_key != SSD_KEY_ILLEGAL_REQUEST) scsi_sense_print(&ccb->csio); } else { xpt_print(periph->path, "Synchronize cache " "failed, status == 0x%x, scsi status == " "0x%x\n", ccb->csio.ccb_h.status, ccb->csio.scsi_status); } } if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) cam_release_devq(ccb->ccb_h.path, /*relsim_flags*/0, /*reduction*/0, /*timeout*/0, /*getcount_only*/0); xpt_release_ccb(ccb); } if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) { if ((softc->quirks & DA_Q_NO_PREVENT) == 0) daprevent(periph, PR_ALLOW); /* * If we've got removeable media, mark the blocksize as * unavailable, since it could change when new media is * inserted. */ softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE; } /* * Don't compound any ref counting software bugs with more. */ if (softc->flags & DA_FLAG_OPEN) { softc->flags &= ~DA_FLAG_OPEN; cam_periph_release(periph); } else { xpt_print(periph->path, "daclose() called on an already closed device!\n"); } cam_periph_unhold(periph, 1); return (0); } /* * Actually translate the requested transfer into one the physical driver * can understand. The transfer is described by a buf and will include * only one physical transfer. */ static int dastrategy(struct dev_strategy_args *ap) { cdev_t dev = ap->a_head.a_dev; struct bio *bio = ap->a_bio; struct buf *bp = bio->bio_buf; struct cam_periph *periph; struct da_softc *softc; u_int unit; unit = dkunit(dev); periph = cam_extend_get(daperiphs, unit); if (periph == NULL) { bp->b_error = ENXIO; goto bad; } softc = (struct da_softc *)periph->softc; cam_periph_lock(periph); #if 0 /* * check it's not too big a transfer for our adapter */ scsi_minphys(bp, &sd_switch); #endif /* * Mask interrupts so that the pack cannot be invalidated until * after we are in the queue. Otherwise, we might not properly * clean up one of the buffers. */ /* * If the device has been made invalid, error out */ if ((softc->flags & DA_FLAG_PACK_INVALID)) { cam_periph_unlock(periph); bp->b_error = ENXIO; goto bad; } /* * Place it in the queue of disk activities for this disk */ if (bp->b_cmd == BUF_CMD_WRITE || bp->b_cmd == BUF_CMD_FLUSH) bioqdisksort(&softc->bio_queue_wr, bio); else if (bp->b_cmd == BUF_CMD_FREEBLKS) bioqdisksort(&softc->bio_queue_trim, bio); else bioqdisksort(&softc->bio_queue_rd, bio); /* * Schedule ourselves for performing the work. */ xpt_schedule(periph, /* XXX priority */1); cam_periph_unlock(periph); return(0); bad: bp->b_flags |= B_ERROR; /* * Correctly set the buf to indicate a completed xfer */ bp->b_resid = bp->b_bcount; biodone(bio); return(0); } static int dadump(struct dev_dump_args *ap) { cdev_t dev = ap->a_head.a_dev; struct cam_periph *periph; struct da_softc *softc; u_int unit; u_int32_t secsize; struct ccb_scsiio csio; unit = dkunit(dev); periph = cam_extend_get(daperiphs, unit); if (periph == NULL) return (ENXIO); softc = (struct da_softc *)periph->softc; cam_periph_lock(periph); secsize = softc->params.secsize; /* XXX: or ap->a_secsize? */ if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) { cam_periph_unlock(periph); return (ENXIO); } /* * because length == 0 means we are supposed to flush cache, we only * try to write something if length > 0. */ if (ap->a_length > 0) { xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1); csio.ccb_h.flags |= CAM_POLLED; csio.ccb_h.ccb_state = DA_CCB_DUMP; scsi_read_write(&csio, /*retries*/1, dadone, MSG_ORDERED_Q_TAG, /*read*/FALSE, /*byte2*/0, /*minimum_cmd_size*/ softc->minimum_cmd_size, ap->a_offset / secsize, ap->a_length / secsize, /*data_ptr*/(u_int8_t *) ap->a_virtual, /*dxfer_len*/ap->a_length, /*sense_len*/SSD_FULL_SIZE, DA_DEFAULT_TIMEOUT * 1000); xpt_polled_action((union ccb *)&csio); if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { kprintf("Aborting dump due to I/O error.\n"); if ((csio.ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR) scsi_sense_print(&csio); else kprintf("status == 0x%x, scsi status == 0x%x\n", csio.ccb_h.status, csio.scsi_status); return(EIO); } cam_periph_unlock(periph); return 0; } /* * Sync the disk cache contents to the physical media. */ if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) { xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1); csio.ccb_h.ccb_state = DA_CCB_DUMP; scsi_synchronize_cache(&csio, /*retries*/1, /*cbfcnp*/dadone, MSG_SIMPLE_Q_TAG, /*begin_lba*/0,/* Cover the whole disk */ /*lb_count*/0, SSD_FULL_SIZE, 5 * 60 * 1000); xpt_polled_action((union ccb *)&csio); if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { if ((csio.ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR) { int asc, ascq; int sense_key, error_code; scsi_extract_sense(&csio.sense_data, &error_code, &sense_key, &asc, &ascq); if (sense_key != SSD_KEY_ILLEGAL_REQUEST) scsi_sense_print(&csio); } else { xpt_print(periph->path, "Synchronize cache " "failed, status == 0x%x, scsi status == " "0x%x\n", csio.ccb_h.status, csio.scsi_status); } } } cam_periph_unlock(periph); return (0); } static void dainit(void) { cam_status status; /* * Create our extend array for storing the devices we attach to. */ daperiphs = cam_extend_new(); if (daperiphs == NULL) { kprintf("da: Failed to alloc extend array!\n"); return; } /* * Install a global async callback. This callback will * receive async callbacks like "new device found". */ status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL); if (status != CAM_REQ_CMP) { kprintf("da: Failed to attach master async callback " "due to status 0x%x!\n", status); } else { /* Register our shutdown event handler */ if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown, NULL, SHUTDOWN_PRI_SECOND)) == NULL) kprintf("%s: shutdown event registration failed!\n", __func__); } } static void daoninvalidate(struct cam_periph *periph) { struct da_softc *softc; softc = (struct da_softc *)periph->softc; /* * De-register any async callbacks. */ xpt_register_async(0, daasync, periph, periph->path); softc->flags |= DA_FLAG_PACK_INVALID; /* * Return all queued I/O with ENXIO. * XXX Handle any transactions queued to the card * with XPT_ABORT_CCB. */ daflushbioq(&softc->bio_queue_trim, ENXIO); daflushbioq(&softc->bio_queue_wr, ENXIO); daflushbioq(&softc->bio_queue_rd, ENXIO); xpt_print(periph->path, "lost device\n"); } static void daflushbioq(struct bio_queue_head *bioq, int error) { struct bio *q_bio; struct buf *q_bp; while ((q_bio = bioq_first(bioq)) != NULL){ bioq_remove(bioq, q_bio); q_bp = q_bio->bio_buf; q_bp->b_resid = q_bp->b_bcount; q_bp->b_error = error; q_bp->b_flags |= B_ERROR; biodone(q_bio); } } static void dacleanup(struct cam_periph *periph) { struct da_softc *softc; softc = (struct da_softc *)periph->softc; devstat_remove_entry(&softc->device_stats); cam_extend_release(daperiphs, periph->unit_number); xpt_print(periph->path, "removing device entry\n"); /* * If we can't free the sysctl tree, oh well... */ if ((softc->flags & DA_FLAG_SCTX_INIT) != 0 && sysctl_ctx_free(&softc->sysctl_ctx) != 0) { xpt_print(periph->path, "can't remove sysctl context\n"); } periph->softc = NULL; if (softc->disk.d_rawdev) { cam_periph_unlock(periph); disk_destroy(&softc->disk); cam_periph_lock(periph); } kfree(softc, M_DEVBUF); } static void daasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg) { struct cam_periph *periph; periph = (struct cam_periph *)callback_arg; switch (code) { case AC_FOUND_DEVICE: { struct ccb_getdev *cgd; cam_status status; cgd = (struct ccb_getdev *)arg; if (cgd == NULL) break; if (SID_TYPE(&cgd->inq_data) != T_DIRECT && SID_TYPE(&cgd->inq_data) != T_RBC && SID_TYPE(&cgd->inq_data) != T_OPTICAL) break; /* * Don't complain if a valid peripheral is already attached. */ periph = cam_periph_find(cgd->ccb_h.path, "da"); if (periph && (periph->flags & CAM_PERIPH_INVALID) == 0) break; /* * Allocate a peripheral instance for * this device and start the probe * process. */ status = cam_periph_alloc(daregister, daoninvalidate, dacleanup, dastart, "da", CAM_PERIPH_BIO, cgd->ccb_h.path, daasync, AC_FOUND_DEVICE, cgd); if (status != CAM_REQ_CMP && status != CAM_REQ_INPROG) { kprintf("%s: Unable to attach to new device " "due to status 0x%x\n", __func__, status); } break; } case AC_SENT_BDR: case AC_BUS_RESET: { struct da_softc *softc; struct ccb_hdr *ccbh; softc = (struct da_softc *)periph->softc; /* * Don't fail on the expected unit attention * that will occur. */ softc->flags |= DA_FLAG_RETRY_UA; LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le) ccbh->ccb_state |= DA_CCB_RETRY_UA; /* FALLTHROUGH*/ } default: cam_periph_async(periph, code, path, arg); break; } } static void dasysctlinit(void *context, int pending) { struct cam_periph *periph; struct da_softc *softc; char tmpstr[80], tmpstr2[80]; periph = (struct cam_periph *)context; if (cam_periph_acquire(periph) != CAM_REQ_CMP) { return; } softc = (struct da_softc *)periph->softc; ksnprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number); ksnprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number); sysctl_ctx_free(&softc->sysctl_ctx); sysctl_ctx_init(&softc->sysctl_ctx); softc->flags |= DA_FLAG_SCTX_INIT; softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx, SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2, CTLFLAG_RD, 0, tmpstr); if (softc->sysctl_tree == NULL) { kprintf("%s: unable to allocate sysctl tree\n", __func__); cam_periph_release(periph); return; } /* * Now register the sysctl handler, so the user can the value on * the fly. */ SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW, &softc->minimum_cmd_size, 0, dacmdsizesysctl, "I", "Minimum CDB size"); /* Only create the option if the device supports TRIM */ if (softc->disk.d_info.d_trimflag) { SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "trim_enabled", CTLFLAG_RW, &softc->trim_enabled, 0, "Enable TRIM for this device (SSD))"); } cam_periph_release(periph); } static int dacmdsizesysctl(SYSCTL_HANDLER_ARGS) { int error, value; value = *(int *)arg1; error = sysctl_handle_int(oidp, &value, 0, req); if ((error != 0) || (req->newptr == NULL)) return (error); /* * Acceptable values here are 6, 10 or 12, or 16. */ if (value < 6) value = 6; else if ((value > 6) && (value <= 10)) value = 10; else if ((value > 10) && (value <= 12)) value = 12; else if (value > 12) value = 16; *(int *)arg1 = value; return (0); } static cam_status daregister(struct cam_periph *periph, void *arg) { struct da_softc *softc; struct ccb_pathinq cpi; struct ccb_getdev *cgd; char tmpstr[80]; caddr_t match; cgd = (struct ccb_getdev *)arg; if (periph == NULL) { kprintf("%s: periph was NULL!!\n", __func__); return(CAM_REQ_CMP_ERR); } if (cgd == NULL) { kprintf("%s: no getdev CCB, can't register device\n", __func__); return(CAM_REQ_CMP_ERR); } softc = kmalloc(sizeof(*softc), M_DEVBUF, M_INTWAIT | M_ZERO); sysctl_ctx_init(&softc->sysctl_ctx); LIST_INIT(&softc->pending_ccbs); softc->state = DA_STATE_PROBE; bioq_init(&softc->bio_queue_trim); bioq_init(&softc->bio_queue_rd); bioq_init(&softc->bio_queue_wr); if (SID_IS_REMOVABLE(&cgd->inq_data)) softc->flags |= DA_FLAG_PACK_REMOVABLE; if ((cgd->inq_data.flags & SID_CmdQue) != 0) softc->flags |= DA_FLAG_TAGGED_QUEUING; /* Used to get TRIM status from AHCI driver */ if (cgd->inq_data.vendor_specific1[0] == 1) { /* * max number of lba ranges an SSD can handle in a single * TRIM command. vendor_specific1[1] is the num of 512-byte * blocks the SSD reports that can be passed in a TRIM cmd. */ softc->trim_max_ranges = min(cgd->inq_data.vendor_specific1[1] * 64, TRIM_MAX_RANGES); } periph->softc = softc; cam_extend_set(daperiphs, periph->unit_number, periph); /* * See if this device has any quirks. */ match = cam_quirkmatch((caddr_t)&cgd->inq_data, (caddr_t)da_quirk_table, NELEM(da_quirk_table), sizeof(*da_quirk_table), scsi_inquiry_match); if (match != NULL) softc->quirks = ((struct da_quirk_entry *)match)->quirks; else softc->quirks = DA_Q_NONE; /* * Unconditionally disable the synchronize cache command for * usb attachments. It's just impossible to determine if the * device supports it or not and if it doesn't the port can * brick. */ if (strncmp(periph->sim->sim_name, "umass", 4) == 0) { softc->quirks |= DA_Q_NO_SYNC_CACHE; } TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph); /* Check if the SIM does not want 6 byte commands */ bzero(&cpi, sizeof(cpi)); xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1); cpi.ccb_h.func_code = XPT_PATH_INQ; xpt_action((union ccb *)&cpi); if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE)) softc->quirks |= DA_Q_NO_6_BYTE; /* * RBC devices don't have to support READ(6), only READ(10). */ if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC) softc->minimum_cmd_size = 10; else softc->minimum_cmd_size = 6; /* * Load the user's default, if any. */ ksnprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size", periph->unit_number); TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size); /* * 6, 10, 12, and 16 are the currently permissible values. */ if (softc->minimum_cmd_size < 6) softc->minimum_cmd_size = 6; else if ((softc->minimum_cmd_size > 6) && (softc->minimum_cmd_size <= 10)) softc->minimum_cmd_size = 10; else if ((softc->minimum_cmd_size > 10) && (softc->minimum_cmd_size <= 12)) softc->minimum_cmd_size = 12; else if (softc->minimum_cmd_size > 12) softc->minimum_cmd_size = 16; /* * The DA driver supports a blocksize, but * we don't know the blocksize until we do * a read capacity. So, set a flag to * indicate that the blocksize is * unavailable right now. We'll clear the * flag as soon as we've done a read capacity. */ devstat_add_entry(&softc->device_stats, "da", periph->unit_number, 0, DEVSTAT_BS_UNAVAILABLE, SID_TYPE(&cgd->inq_data) | DEVSTAT_TYPE_IF_SCSI, DEVSTAT_PRIORITY_DISK); /* * Register this media as a disk */ CAM_SIM_UNLOCK(periph->sim); disk_create(periph->unit_number, &softc->disk, &da_ops); if (cpi.maxio == 0 || cpi.maxio > MAXPHYS) softc->disk.d_rawdev->si_iosize_max = MAXPHYS; else softc->disk.d_rawdev->si_iosize_max = cpi.maxio; if (bootverbose) { kprintf("%s%d: si_iosize_max:%d\n", periph->periph_name, periph->unit_number, softc->disk.d_rawdev->si_iosize_max); } CAM_SIM_LOCK(periph->sim); /* * Add async callbacks for bus reset and * bus device reset calls. I don't bother * checking if this fails as, in most cases, * the system will function just fine without * them and the only alternative would be to * not attach the device on failure. */ xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE, daasync, periph, periph->path); /* * Take an exclusive refcount on the periph while dastart is called * to finish the probe. The reference will be dropped in dadone at * the end of probe. */ cam_periph_hold(periph, 0); xpt_schedule(periph, /*priority*/5); return(CAM_REQ_CMP); } static void dastart(struct cam_periph *periph, union ccb *start_ccb) { struct da_softc *softc; softc = (struct da_softc *)periph->softc; switch (softc->state) { case DA_STATE_NORMAL: { /* Pull a buffer from the queue and get going on it */ struct bio *bio; struct bio *bio_rd; struct bio *bio_wr; struct buf *bp; u_int8_t tag_code; int limit; /* * See if there is a buf with work for us to do.. */ bio_rd = bioq_first(&softc->bio_queue_rd); bio_wr = bioq_first(&softc->bio_queue_wr); if (periph->immediate_priority <= periph->pinfo.priority) { CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE, ("queuing for immediate ccb\n")); start_ccb->ccb_h.ccb_state = DA_CCB_WAITING; SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h, periph_links.sle); periph->immediate_priority = CAM_PRIORITY_NONE; wakeup(&periph->ccb_list); if (bio_rd || bio_wr) { /* * Have more work to do, so ensure we stay * scheduled */ xpt_schedule(periph, /* XXX priority */1); } break; } /* Run the trim command if not already running */ if (!softc->trim_running && (bio = bioq_first(&softc->bio_queue_trim)) != NULL) { struct trim_request *req = &softc->trim_req; struct bio *bio1; int bps = 0, ranges = 0; softc->trim_running = 1; bzero(req, sizeof(*req)); bio1 = bio; while (1) { uint64_t lba; int count; bp = bio1->bio_buf; count = bp->b_bcount / softc->params.secsize; lba = bio1->bio_offset/softc->params.secsize; kprintf("trim lba:%llu boff:%llu count:%d\n", (unsigned long long) lba, (unsigned long long) bio1->bio_offset, count); bioq_remove(&softc->bio_queue_trim, bio1); while (count > 0) { int c = min(count, 0xffff); int off = ranges * 8; req->data[off + 0] = lba & 0xff; req->data[off + 1] = (lba >> 8) & 0xff; req->data[off + 2] = (lba >> 16) & 0xff; req->data[off + 3] = (lba >> 24) & 0xff; req->data[off + 4] = (lba >> 32) & 0xff; req->data[off + 5] = (lba >> 40) & 0xff; req->data[off + 6] = c & 0xff; req->data[off + 7] = (c >> 8) & 0xff; lba += c; count -= c; ranges++; } /* Try to merge multiple TRIM requests */ req->bios[bps++] = bio1; bio1 = bioq_first(&softc->bio_queue_trim); if (bio1 == NULL || bio1->bio_buf->b_bcount / softc->params.secsize > (softc->trim_max_ranges - ranges) * 0xffff) break; } cam_fill_csio(&start_ccb->csio, 1/*retries*/, dadone, CAM_DIR_OUT, MSG_SIMPLE_Q_TAG, req->data, ((ranges +63)/64)*512, SSD_FULL_SIZE, sizeof(struct scsi_rw_6), da_default_timeout*2); start_ccb->ccb_h.ccb_state = DA_CCB_TRIM; LIST_INSERT_HEAD(&softc->pending_ccbs, &start_ccb->ccb_h, periph_links.le); start_ccb->csio.ccb_h.func_code = XPT_TRIM; start_ccb->ccb_h.ccb_bio = bio; devstat_start_transaction(&softc->device_stats); xpt_action(start_ccb); xpt_schedule(periph, 1); break; } /* * Select a read or write buffer to queue. Limit the number * of tags dedicated to reading or writing, giving reads * precedence. * * Writes to modern hard drives go into the HDs cache and * return completion nearly instantly. That is until the * cache becomes full. When the HDs cache becomes full * write commands will begin to stall. If all available * tags are taken up by writes which saturate the drive * reads will become tag-starved. * * A similar situation can occur with reads. With many * parallel readers all tags can be taken up by reads * and prevent any writes from draining, even if the HD's * cache is not full. */ limit = periph->sim->max_tagged_dev_openings * 2 / 3 + 1; #if 0 /* DEBUGGING */ static int savets; static long savets2; if (1 || time_uptime != savets2 || (ticks != savets && (softc->outstanding_cmds_rd || softc->outstanding_cmds_wr))) { kprintf("%d %d (%d)\n", softc->outstanding_cmds_rd, softc->outstanding_cmds_wr, limit); savets = ticks; savets2 = time_uptime; } #endif if (bio_rd && softc->outstanding_cmds_rd < limit) { bio = bio_rd; bioq_remove(&softc->bio_queue_rd, bio); } else if (bio_wr && softc->outstanding_cmds_wr < limit) { bio = bio_wr; bioq_remove(&softc->bio_queue_wr, bio); } else { if (bio_rd) softc->flags |= DA_FLAG_RD_LIMIT; if (bio_wr) softc->flags |= DA_FLAG_WR_LIMIT; xpt_release_ccb(start_ccb); break; } /* * We can queue new work. */ bp = bio->bio_buf; devstat_start_transaction(&softc->device_stats); tag_code = MSG_SIMPLE_Q_TAG; switch(bp->b_cmd) { case BUF_CMD_READ: case BUF_CMD_WRITE: /* * Block read/write op */ KKASSERT(bio->bio_offset % softc->params.secsize == 0); scsi_read_write( &start_ccb->csio, da_retry_count, /* retries */ dadone, tag_code, (bp->b_cmd == BUF_CMD_READ), 0, /* byte2 */ softc->minimum_cmd_size, bio->bio_offset / softc->params.secsize, bp->b_bcount / softc->params.secsize, bp->b_data, bp->b_bcount, SSD_FULL_SIZE, /* sense_len */ da_default_timeout * 1000 ); break; case BUF_CMD_FLUSH: /* * Silently complete a flush request if the device * cannot handle it. */ if (softc->quirks & DA_Q_NO_SYNC_CACHE) { xpt_release_ccb(start_ccb); start_ccb = NULL; devstat_end_transaction_buf( &softc->device_stats, bp); biodone(bio); } else { scsi_synchronize_cache( &start_ccb->csio, 1, /* retries */ dadone, /* cbfcnp */ MSG_SIMPLE_Q_TAG, 0, /* lba */ 0, /* count (whole disk) */ SSD_FULL_SIZE, da_default_timeout*1000 /* timeout */ ); } break; case BUF_CMD_FREEBLKS: if (softc->disk.d_info.d_trimflag & DA_FLAG_CAN_TRIM){ start_ccb->csio.ccb_h.func_code = XPT_TRIM; break; } default: xpt_release_ccb(start_ccb); start_ccb = NULL; panic("dastart: unrecognized bio cmd %d", bp->b_cmd); break; /* NOT REACHED */ } /* * Block out any asyncronous callbacks * while we touch the pending ccb list. */ if (start_ccb) { start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO; LIST_INSERT_HEAD(&softc->pending_ccbs, &start_ccb->ccb_h, periph_links.le); if (bp->b_cmd == BUF_CMD_WRITE || bp->b_cmd == BUF_CMD_FLUSH) { ++softc->outstanding_cmds_wr; } else { ++softc->outstanding_cmds_rd; } /* We expect a unit attention from this device */ if ((softc->flags & DA_FLAG_RETRY_UA) != 0) { start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA; softc->flags &= ~DA_FLAG_RETRY_UA; } start_ccb->ccb_h.ccb_bio = bio; xpt_action(start_ccb); } /* * Be sure we stay scheduled if we have more work to do. */ if (bioq_first(&softc->bio_queue_rd) || bioq_first(&softc->bio_queue_wr)) { xpt_schedule(periph, 1); } break; } case DA_STATE_PROBE: { struct ccb_scsiio *csio; struct scsi_read_capacity_data *rcap; rcap = kmalloc(sizeof(*rcap), M_SCSIDA, M_INTWAIT | M_ZERO); csio = &start_ccb->csio; scsi_read_capacity(csio, /*retries*/4, dadone, MSG_SIMPLE_Q_TAG, rcap, SSD_FULL_SIZE, /*timeout*/5000); start_ccb->ccb_h.ccb_bio = NULL; start_ccb->ccb_h.ccb_state = DA_CCB_PROBE; xpt_action(start_ccb); break; } case DA_STATE_PROBE2: { struct ccb_scsiio *csio; struct scsi_read_capacity_data_16 *rcaplong; rcaplong = kmalloc(sizeof(*rcaplong), M_SCSIDA, M_INTWAIT | M_ZERO); csio = &start_ccb->csio; scsi_read_capacity_16(csio, /*retries*/ 4, /*cbfcnp*/ dadone, /*tag_action*/ MSG_SIMPLE_Q_TAG, /*lba*/ 0, /*reladr*/ 0, /*pmi*/ 0, rcaplong, /*sense_len*/ SSD_FULL_SIZE, /*timeout*/ 60000); start_ccb->ccb_h.ccb_bio = NULL; start_ccb->ccb_h.ccb_state = DA_CCB_PROBE2; xpt_action(start_ccb); break; } } } static int cmd6workaround(union ccb *ccb) { struct scsi_rw_6 cmd6; struct scsi_rw_10 *cmd10; struct da_softc *softc; u_int8_t *cdb; int frozen; cdb = ccb->csio.cdb_io.cdb_bytes; /* Translation only possible if CDB is an array and cmd is R/W6 */ if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 || (*cdb != READ_6 && *cdb != WRITE_6)) return 0; xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, " "increasing minimum_cmd_size to 10.\n"); softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc; softc->minimum_cmd_size = 10; bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6)); cmd10 = (struct scsi_rw_10 *)cdb; cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10; cmd10->byte2 = 0; scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr); cmd10->reserved = 0; scsi_ulto2b(cmd6.length, cmd10->length); cmd10->control = cmd6.control; ccb->csio.cdb_len = sizeof(*cmd10); /* Requeue request, unfreezing queue if necessary */ frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0; ccb->ccb_h.status = CAM_REQUEUE_REQ; xpt_action(ccb); if (frozen) { cam_release_devq(ccb->ccb_h.path, /*relsim_flags*/0, /*reduction*/0, /*timeout*/0, /*getcount_only*/0); } return (ERESTART); } static void dadone(struct cam_periph *periph, union ccb *done_ccb) { struct da_softc *softc; struct ccb_scsiio *csio; struct disk_info info; softc = (struct da_softc *)periph->softc; csio = &done_ccb->csio; switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) { case DA_CCB_BUFFER_IO: case DA_CCB_TRIM: { struct buf *bp; struct bio *bio; int mustsched = 0; bio = (struct bio *)done_ccb->ccb_h.ccb_bio; bp = bio->bio_buf; if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { int error; int sf; if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0) sf = SF_RETRY_UA; else sf = 0; error = daerror(done_ccb, CAM_RETRY_SELTO, sf); if (error == ERESTART) { /* * A retry was scheuled, so * just return. */ return; } if (error != 0) { if (error == ENXIO) { /* * Catastrophic error. Mark our pack as * invalid. */ /* * XXX See if this is really a media * XXX change first? */ xpt_print(periph->path, "Invalidating pack\n"); softc->flags |= DA_FLAG_PACK_INVALID; } /* * Return all queued write I/O's with EIO * so the client can retry these I/Os in the * proper order should it attempt to recover. * * Leave read I/O's alone. */ daflushbioq(&softc->bio_queue_wr, EIO); bp->b_error = error; bp->b_resid = bp->b_bcount; bp->b_flags |= B_ERROR; } else { bp->b_resid = csio->resid; bp->b_error = 0; if (bp->b_resid != 0) bp->b_flags |= B_ERROR; } if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) cam_release_devq(done_ccb->ccb_h.path, /*relsim_flags*/0, /*reduction*/0, /*timeout*/0, /*getcount_only*/0); } else { if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) panic("REQ_CMP with QFRZN"); bp->b_resid = csio->resid; if (csio->resid > 0) bp->b_flags |= B_ERROR; } /* * Block out any asyncronous callbacks * while we touch the pending ccb list. */ LIST_REMOVE(&done_ccb->ccb_h, periph_links.le); if (bp->b_cmd == BUF_CMD_WRITE || bp->b_cmd == BUF_CMD_FLUSH) { --softc->outstanding_cmds_wr; if (softc->flags & DA_FLAG_WR_LIMIT) { softc->flags &= ~DA_FLAG_WR_LIMIT; mustsched = 1; } } else { --softc->outstanding_cmds_rd; if (softc->flags & DA_FLAG_RD_LIMIT) { softc->flags &= ~DA_FLAG_RD_LIMIT; mustsched = 1; } } devstat_end_transaction_buf(&softc->device_stats, bp); if ((csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) == DA_CCB_TRIM) { struct trim_request *req = (struct trim_request *) csio->data_ptr; int i; for (i = 1; i < softc->trim_max_ranges && req->bios[i]; i++) { struct bio *bp1 = req->bios[i]; bp1->bio_buf->b_resid = bp->b_resid; bp1->bio_buf->b_error = bp->b_error; if (bp->b_flags & B_ERROR) bp1->bio_buf->b_flags |= B_ERROR; biodone(bp1); } softc->trim_running = 0; biodone(bio); xpt_schedule(periph,1); } else biodone(bio); if (mustsched) xpt_schedule(periph, /*priority*/1); break; } case DA_CCB_PROBE: case DA_CCB_PROBE2: { struct scsi_read_capacity_data *rdcap; struct scsi_read_capacity_data_16 *rcaplong; char announce_buf[80]; rdcap = NULL; rcaplong = NULL; if (softc->state == DA_STATE_PROBE) rdcap =(struct scsi_read_capacity_data *)csio->data_ptr; else rcaplong = (struct scsi_read_capacity_data_16 *) csio->data_ptr; bzero(&info, sizeof(info)); info.d_type = DTYPE_SCSI; info.d_serialno = xpt_path_serialno(periph->path); if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) { struct disk_params *dp; uint32_t block_size; uint64_t maxsector; if (softc->state == DA_STATE_PROBE) { block_size = scsi_4btoul(rdcap->length); maxsector = scsi_4btoul(rdcap->addr); /* * According to SBC-2, if the standard 10 * byte READ CAPACITY command returns 2^32, * we should issue the 16 byte version of * the command, since the device in question * has more sectors than can be represented * with the short version of the command. */ if (maxsector == 0xffffffff) { softc->state = DA_STATE_PROBE2; kfree(rdcap, M_SCSIDA); xpt_release_ccb(done_ccb); xpt_schedule(periph, /*priority*/5); return; } } else { block_size = scsi_4btoul(rcaplong->length); maxsector = scsi_8btou64(rcaplong->addr); } dasetgeom(periph, block_size, maxsector); dp = &softc->params; ksnprintf(announce_buf, sizeof(announce_buf), "%juMB (%ju %u byte sectors: %dH %dS/T %dC)", (uintmax_t) (((uintmax_t)dp->secsize * dp->sectors) / (1024*1024)), (uintmax_t)dp->sectors, dp->secsize, dp->heads, dp->secs_per_track, dp->cylinders); CAM_SIM_UNLOCK(periph->sim); info.d_media_blksize = softc->params.secsize; info.d_media_blocks = softc->params.sectors; info.d_media_size = 0; info.d_secpertrack = softc->params.secs_per_track; info.d_nheads = softc->params.heads; info.d_ncylinders = softc->params.cylinders; info.d_secpercyl = softc->params.heads * softc->params.secs_per_track; info.d_serialno = xpt_path_serialno(periph->path); disk_setdiskinfo(&softc->disk, &info); CAM_SIM_LOCK(periph->sim); } else { int error; announce_buf[0] = '\0'; /* * Retry any UNIT ATTENTION type errors. They * are expected at boot. */ error = daerror(done_ccb, CAM_RETRY_SELTO, SF_RETRY_UA|SF_NO_PRINT); if (error == ERESTART) { /* * A retry was scheuled, so * just return. */ return; } else if (error != 0) { struct scsi_sense_data *sense; int asc, ascq; int sense_key, error_code; int have_sense; cam_status status; struct ccb_getdev cgd; /* Don't wedge this device's queue */ status = done_ccb->ccb_h.status; if ((status & CAM_DEV_QFRZN) != 0) cam_release_devq(done_ccb->ccb_h.path, /*relsim_flags*/0, /*reduction*/0, /*timeout*/0, /*getcount_only*/0); xpt_setup_ccb(&cgd.ccb_h, done_ccb->ccb_h.path, /* priority */ 1); cgd.ccb_h.func_code = XPT_GDEV_TYPE; xpt_action((union ccb *)&cgd); if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0) || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0) || ((status & CAM_AUTOSNS_VALID) == 0)) have_sense = FALSE; else have_sense = TRUE; if (have_sense) { sense = &csio->sense_data; scsi_extract_sense(sense, &error_code, &sense_key, &asc, &ascq); } /* * Attach to anything that claims to be a * direct access or optical disk device, * as long as it doesn't return a "Logical * unit not supported" (0x25) error. */ if ((have_sense) && (asc != 0x25) && (error_code == SSD_CURRENT_ERROR)) { const char *sense_key_desc; const char *asc_desc; scsi_sense_desc(sense_key, asc, ascq, &cgd.inq_data, &sense_key_desc, &asc_desc); ksnprintf(announce_buf, sizeof(announce_buf), "Attempt to query device " "size failed: %s, %s", sense_key_desc, asc_desc); info.d_media_blksize = 512; disk_setdiskinfo(&softc->disk, &info); } else { if (have_sense) scsi_sense_print( &done_ccb->csio); else { xpt_print(periph->path, "got CAM status %#x\n", done_ccb->ccb_h.status); } xpt_print(periph->path, "fatal error, " "failed to attach to device\n"); /* * Free up resources. */ cam_periph_invalidate(periph); } } } kfree(csio->data_ptr, M_SCSIDA); if (announce_buf[0] != '\0') { xpt_announce_periph(periph, announce_buf); /* * Create our sysctl variables, now that we know * we have successfully attached. */ taskqueue_enqueue(taskqueue_thread[mycpuid], &softc->sysctl_task); } if (softc->trim_max_ranges) { softc->disk.d_info.d_trimflag |= DA_FLAG_CAN_TRIM; kprintf("%s%d: supports TRIM\n", periph->periph_name, periph->unit_number); } softc->state = DA_STATE_NORMAL; /* * Since our peripheral may be invalidated by an error * above or an external event, we must release our CCB * before releasing the probe lock on the peripheral. * The peripheral will only go away once the last lock * is removed, and we need it around for the CCB release * operation. */ xpt_release_ccb(done_ccb); cam_periph_unhold(periph, 0); return; } case DA_CCB_WAITING: { /* Caller will release the CCB */ wakeup(&done_ccb->ccb_h.cbfcnp); return; } case DA_CCB_DUMP: /* No-op. We're polling */ return; case DA_CCB_POLLED: /* Caller releases ccb */ wakeup(&done_ccb->ccb_h.cbfcnp); return; default: break; } xpt_release_ccb(done_ccb); } static int daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags) { struct da_softc *softc; struct cam_periph *periph; int error; periph = xpt_path_periph(ccb->ccb_h.path); softc = (struct da_softc *)periph->softc; /* * Automatically detect devices that do not support * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs. */ error = 0; if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) { error = cmd6workaround(ccb); } else if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR) && (ccb->ccb_h.status & CAM_AUTOSNS_VALID) && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND) && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0) && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) { int sense_key, error_code, asc, ascq; scsi_extract_sense(&ccb->csio.sense_data, &error_code, &sense_key, &asc, &ascq); if (sense_key == SSD_KEY_ILLEGAL_REQUEST) error = cmd6workaround(ccb); } if (error == ERESTART) return (ERESTART); /* * XXX * Until we have a better way of doing pack validation, * don't treat UAs as errors. */ sense_flags |= SF_RETRY_UA; return(cam_periph_error(ccb, cam_flags, sense_flags, &softc->saved_ccb)); } static void daprevent(struct cam_periph *periph, int action) { struct da_softc *softc; union ccb *ccb; int error; softc = (struct da_softc *)periph->softc; if (((action == PR_ALLOW) && (softc->flags & DA_FLAG_PACK_LOCKED) == 0) || ((action == PR_PREVENT) && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) { return; } ccb = cam_periph_getccb(periph, /*priority*/1); ccb->ccb_h.ccb_state = DA_CCB_POLLED; scsi_prevent(&ccb->csio, /*retries*/1, /*cbcfp*/dadone, MSG_SIMPLE_Q_TAG, action, SSD_FULL_SIZE, 5000); error = cam_periph_runccb(ccb, /*error_routine*/NULL, CAM_RETRY_SELTO, SF_RETRY_UA, &softc->device_stats); if (error == 0) { if (action == PR_ALLOW) softc->flags &= ~DA_FLAG_PACK_LOCKED; else softc->flags |= DA_FLAG_PACK_LOCKED; } xpt_release_ccb(ccb); } /* * Check media on open, e.g. card reader devices which had no initial media. */ static int dacheckmedia(struct cam_periph *periph) { struct disk_params *dp; struct da_softc *softc; struct disk_info info; int error; softc = (struct da_softc *)periph->softc; dp = &softc->params; error = dagetcapacity(periph); /* * Only reprobe on initial open and if the media is removable. * * NOTE: If we setdiskinfo() it will take the device probe * a bit of time to probe the slices and partitions, * and mess up booting. So avoid if nothing has changed. * XXX */ if (softc->flags & DA_FLAG_OPEN) return (error); if ((softc->flags & DA_FLAG_PACK_REMOVABLE) == 0) return (error); bzero(&info, sizeof(info)); info.d_type = DTYPE_SCSI; info.d_serialno = xpt_path_serialno(periph->path); if (error == 0) { CAM_SIM_UNLOCK(periph->sim); info.d_media_blksize = softc->params.secsize; info.d_media_blocks = softc->params.sectors; info.d_media_size = 0; info.d_secpertrack = softc->params.secs_per_track; info.d_nheads = softc->params.heads; info.d_ncylinders = softc->params.cylinders; info.d_secpercyl = softc->params.heads * softc->params.secs_per_track; info.d_serialno = xpt_path_serialno(periph->path); if (info.d_media_blocks != softc->disk.d_info.d_media_blocks) { kprintf("%s%d: open removable media: " "%juMB (%ju %u byte sectors: %dH %dS/T %dC)\n", periph->periph_name, periph->unit_number, (uintmax_t)(((uintmax_t)dp->secsize * dp->sectors) / (1024*1024)), (uintmax_t)dp->sectors, dp->secsize, dp->heads, dp->secs_per_track, dp->cylinders); disk_setdiskinfo(&softc->disk, &info); } CAM_SIM_LOCK(periph->sim); } else { kprintf("%s%d: open removable media: no media present\n", periph->periph_name, periph->unit_number); info.d_media_blksize = 512; disk_setdiskinfo(&softc->disk, &info); } return (error); } static int dagetcapacity(struct cam_periph *periph) { struct da_softc *softc; union ccb *ccb; struct scsi_read_capacity_data *rcap; struct scsi_read_capacity_data_16 *rcaplong; uint32_t block_len; uint64_t maxsector; int error; softc = (struct da_softc *)periph->softc; block_len = 0; maxsector = 0; error = 0; /* Do a read capacity */ rcap = (struct scsi_read_capacity_data *)kmalloc(sizeof(*rcaplong), M_SCSIDA, M_INTWAIT); ccb = cam_periph_getccb(periph, /*priority*/1); ccb->ccb_h.ccb_state = DA_CCB_POLLED; scsi_read_capacity(&ccb->csio, /*retries*/4, /*cbfncp*/dadone, MSG_SIMPLE_Q_TAG, rcap, SSD_FULL_SIZE, /*timeout*/60000); ccb->ccb_h.ccb_bio = NULL; error = cam_periph_runccb(ccb, daerror, /*cam_flags*/CAM_RETRY_SELTO, /*sense_flags*/SF_RETRY_UA, &softc->device_stats); if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) cam_release_devq(ccb->ccb_h.path, /*relsim_flags*/0, /*reduction*/0, /*timeout*/0, /*getcount_only*/0); if (error == 0) { block_len = scsi_4btoul(rcap->length); maxsector = scsi_4btoul(rcap->addr); if (maxsector != 0xffffffff) goto done; } else goto done; rcaplong = (struct scsi_read_capacity_data_16 *)rcap; scsi_read_capacity_16(&ccb->csio, /*retries*/ 4, /*cbfcnp*/ dadone, /*tag_action*/ MSG_SIMPLE_Q_TAG, /*lba*/ 0, /*reladr*/ 0, /*pmi*/ 0, rcaplong, /*sense_len*/ SSD_FULL_SIZE, /*timeout*/ 60000); ccb->ccb_h.ccb_bio = NULL; error = cam_periph_runccb(ccb, daerror, /*cam_flags*/CAM_RETRY_SELTO, /*sense_flags*/SF_RETRY_UA, &softc->device_stats); if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) cam_release_devq(ccb->ccb_h.path, /*relsim_flags*/0, /*reduction*/0, /*timeout*/0, /*getcount_only*/0); if (error == 0) { block_len = scsi_4btoul(rcaplong->length); maxsector = scsi_8btou64(rcaplong->addr); } done: if (error == 0) dasetgeom(periph, block_len, maxsector); xpt_release_ccb(ccb); kfree(rcap, M_SCSIDA); return (error); } static void dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector) { struct ccb_calc_geometry ccg; struct da_softc *softc; struct disk_params *dp; softc = (struct da_softc *)periph->softc; dp = &softc->params; dp->secsize = block_len; dp->sectors = maxsector + 1; /* * Have the controller provide us with a geometry * for this disk. The only time the geometry * matters is when we boot and the controller * is the only one knowledgeable enough to come * up with something that will make this a bootable * device. */ xpt_setup_ccb(&ccg.ccb_h, periph->path, /*priority*/1); ccg.ccb_h.func_code = XPT_CALC_GEOMETRY; ccg.block_size = dp->secsize; ccg.volume_size = dp->sectors; ccg.heads = 0; ccg.secs_per_track = 0; ccg.cylinders = 0; xpt_action((union ccb*)&ccg); if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { /* * We don't know what went wrong here- but just pick * a geometry so we don't have nasty things like divide * by zero. */ dp->heads = 255; dp->secs_per_track = 255; dp->cylinders = dp->sectors / (255 * 255); if (dp->cylinders == 0) { dp->cylinders = 1; } } else { dp->heads = ccg.heads; dp->secs_per_track = ccg.secs_per_track; dp->cylinders = ccg.cylinders; } } /* * Step through all DA peripheral drivers, and if the device is still open, * sync the disk cache to physical media. */ static void dashutdown(void * arg, int howto) { struct cam_periph *periph; struct da_softc *softc; TAILQ_FOREACH(periph, &dadriver.units, unit_links) { union ccb ccb; cam_periph_lock(periph); softc = (struct da_softc *)periph->softc; /* * We only sync the cache if the drive is still open, and * if the drive is capable of it.. */ if (((softc->flags & DA_FLAG_OPEN) == 0) || (softc->quirks & DA_Q_NO_SYNC_CACHE)) { cam_periph_unlock(periph); continue; } xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/1); ccb.ccb_h.ccb_state = DA_CCB_DUMP; scsi_synchronize_cache(&ccb.csio, /*retries*/1, /*cbfcnp*/dadone, MSG_SIMPLE_Q_TAG, /*begin_lba*/0, /* whole disk */ /*lb_count*/0, SSD_FULL_SIZE, 60 * 60 * 1000); xpt_polled_action(&ccb); if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { if (((ccb.ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR) && (ccb.csio.scsi_status == SCSI_STATUS_CHECK_COND)){ int error_code, sense_key, asc, ascq; scsi_extract_sense(&ccb.csio.sense_data, &error_code, &sense_key, &asc, &ascq); if (sense_key != SSD_KEY_ILLEGAL_REQUEST) scsi_sense_print(&ccb.csio); } else { xpt_print(periph->path, "Synchronize " "cache failed, status == 0x%x, scsi status " "== 0x%x\n", ccb.ccb_h.status, ccb.csio.scsi_status); } } if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0) cam_release_devq(ccb.ccb_h.path, /*relsim_flags*/0, /*reduction*/0, /*timeout*/0, /*getcount_only*/0); cam_periph_unlock(periph); } } #else /* !_KERNEL */ /* * XXX This is only left out of the kernel build to silence warnings. If, * for some reason this function is used in the kernel, the ifdefs should * be moved so it is included both in the kernel and userland. */ void scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries, void (*cbfcnp)(struct cam_periph *, union ccb *), u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave, u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len, u_int32_t timeout) { struct scsi_format_unit *scsi_cmd; scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes; scsi_cmd->opcode = FORMAT_UNIT; scsi_cmd->byte2 = byte2; scsi_ulto2b(ileave, scsi_cmd->interleave); cam_fill_csio(csio, retries, cbfcnp, /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE, tag_action, data_ptr, dxfer_len, sense_len, sizeof(*scsi_cmd), timeout); } #endif /* _KERNEL */
25.716965
119
0.660213
[ "geometry" ]
c100fd2c2b631e6b28e6230e8d344f8b72a08c6d
6,744
h
C
ThirdParty/Havok/include/Physics2012/Collide/Shape/Convex/ConvexTransform/hkpConvexTransformShape.h
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
11
2016-08-02T03:40:36.000Z
2022-03-15T13:41:29.000Z
ThirdParty/Havok/include/Physics2012/Collide/Shape/Convex/ConvexTransform/hkpConvexTransformShape.h
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
null
null
null
ThirdParty/Havok/include/Physics2012/Collide/Shape/Convex/ConvexTransform/hkpConvexTransformShape.h
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
8
2017-03-17T05:59:25.000Z
2021-02-27T08:51:46.000Z
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKP_CONVEX_TRANSFORM_SHAPE_H #define HKP_CONVEX_TRANSFORM_SHAPE_H #include <Physics2012/Collide/Shape/Convex/hkpConvexShape.h> class hkpConvexVerticesShape; extern const hkClass hkpConvexTransformShapeClass; /// hkpConvexTransformShape contains an hkpShape and an additional transform for that shape. /// This is useful, for example, if you want to reuse a particular child shapes multiple /// times at different transforms within a parent shape container. /// The advantage of hkpConvexTransformShape over hkpTransformShape is that it does not /// require additional collision agents to be created. Instead, it intercepts the calls to /// getSupportVertex() (etc) from the collision detector and modifies them. /// For detailed information on SPU handling for this shape, see hkpConvexTranslateShape.h class hkpConvexTransformShape : public hkpConvexTransformShapeBase { //+version(2) public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_SHAPE); HK_DECLARE_REFLECTION(); HKCD_DECLARE_SHAPE_TYPE(hkcdShapeType::CONVEX_TRANSFORM); public: /// Empty constructor, to be called by the shape vtable util on SPU HK_FORCE_INLINE hkpConvexTransformShape() {} /// Constructs a new convex transform shape without scale. /// The hkpShapeContainer::ReferencePolicy is only used for the constructor, the destructor will still always decrement the childs reference hkpConvexTransformShape( const hkpConvexShape* childShape, const hkTransform& transform, hkpShapeContainer::ReferencePolicy ref = hkpShapeContainer::REFERENCE_POLICY_INCREMENT ); /// Constructs a new convex transform shape with scale. This is only supported when the child is a hkpConvexVerticesShape. /// The hkpShapeContainer::ReferencePolicy is only used for the constructor, the destructor will still always decrement the childs reference hkpConvexTransformShape( const hkpConvexShape* childShape, const hkQsTransform& transform, hkpShapeContainer::ReferencePolicy ref = hkpShapeContainer::REFERENCE_POLICY_INCREMENT ); /// Serialization constructor hkpConvexTransformShape( class hkFinishLoadedObjectFlag flag ); public: /// Sets the current transform. Additionally, it calculates the extra scale to apply to the child shape vertices /// to produce the right scaled convex shell. This process may reduce the convex radius if any of the extents of the /// scaled shape is too small to allow the original radius. /// Don't do this once the shape is added to a world as collision agents may have cached data dependent on it. void setTransform( const hkQsTransform& transform ); /// Sets the current transform and sets the extra scale to zero. /// Don't do this once the shape is added to a world as collision agents may have cached data dependent on it. inline void setTransform( const hkTransform& transform ); /// Creates a unscaled copy of the transform from the child shape's space to this transform shape's local space inline void getTransform( hkTransform* HK_RESTRICT transform ) const; /// Gets the full transform from the child shape's space to this transform shape's local space, including scale inline const hkQsTransform& getQsTransform() const; /// Gets the internal additional scale. inline const hkVector4& getExtraScale() const; /// Get the child shape inline const hkpConvexShape* getChildShape() const; /// Transforms a vertex in the child shape's space to the convex transform space correcting the resulting /// positions to produce the right convex shell HK_FORCE_INLINE void transformVertex(hkVector4Parameter localVertex, hkVector4* HK_RESTRICT vertexOut) const; public: // // hkpShapeBase interface implementation. // virtual void getSupportingVertex(hkVector4Parameter direction, hkcdVertex& supportingVertexOut) const; virtual void convertVertexIdsToVertices(const hkpVertexId* ids, int numIds, hkcdVertex* verticesOut) const; virtual void getCentre(hkVector4& centreOut) const; virtual HK_FORCE_INLINE int getNumCollisionSpheres() const; virtual const hkSphere* getCollisionSpheres(hkSphere* sphereBuffer) const; virtual void getAabb(const hkTransform& localToWorld, hkReal tolerance, hkAabb& out) const; virtual hkBool castRay(const hkpShapeRayCastInput& input, hkpShapeRayCastOutput& results) const; virtual void castRayWithCollector(const hkpShapeRayCastInput& input, const hkpCdBody& cdBody, hkpRayHitCollector& collector) const; virtual const hkpShapeContainer* getContainer() const; virtual int calcSizeForSpu( const CalcSizeForSpuInput& input, int spuBufferSizeLeft ) const; // hkpConvexShape interface implementation. virtual void getFirstVertex( hkVector4& v ) const; protected: /// Transform (including non-uniform scale) applied to the child shape. Together with the m_extraScale /// determine the final vertices transformed position. Components X and Y of the child shape's AABB center /// in the child shape's space are stored in the W component of m_translation and m_scale respectively. hkQsTransform m_transform; /// This scale is computed automatically from the scale in the transform and the child shape's convex radius and /// is used when transforming the child shape's vertices to produce the right convex shell. The W component is /// used to store the Z component of the child shape's AABB center in the child shape's space. hkVector4 m_extraScale; }; #include <Physics2012/Collide/Shape/Convex/ConvexTransform/hkpConvexTransformShape.inl> #endif // HKP_CONVEX_TRANSFORM_SHAPE_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
47.160839
251
0.784994
[ "shape", "transform" ]
c1115c87ac9c3cbbb85076da5067ab3f7a1d8b60
2,181
h
C
MMath/Quat.h
trevorvanhoof/MMath
a3f7f1edddfef7767485fffc875fa8364fcfdc14
[ "MIT" ]
1
2021-09-08T08:36:15.000Z
2021-09-08T08:36:15.000Z
MMath/Quat.h
trevorvanhoof/MMath
a3f7f1edddfef7767485fffc875fa8364fcfdc14
[ "MIT" ]
null
null
null
MMath/Quat.h
trevorvanhoof/MMath
a3f7f1edddfef7767485fffc875fa8364fcfdc14
[ "MIT" ]
null
null
null
/** MMath - vector math library for 3D applications. Released under the MIT License: Copyright 2020 Trevor van Hoof Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #pragma once #include "DLL.h" #include <xmmintrin.h> #include "Enums.h" #include "Vector.h" extern "C" { __declspec(align(16)) struct Quat { union { __m128 q; struct { float x; float y; float z; float w; }; float s[4]; }; }; } extern const Quat QUAT_IDENTITY; extern "C" { DLL Quat QuatIdentity(); DLL Quat QuatRotateX(const float radians); DLL Quat QuatRotateY(const float radians); DLL Quat QuatRotateZ(const float radians); DLL Quat QuatMul(const Quat lhs, const Quat rhs); DLL float QuatDot(const Quat a, const Quat b); DLL float QuatSqrMagnitude(const Quat q); DLL float QuatMagnitude(const Quat q); DLL Quat QuatNormalized(const Quat q, const Quat fallback); DLL Quat QuatInversed(const Quat q); // also known as conjugate DLL Quat QuatConjugated(const Quat q); // also known as inverse DLL Quat QuatSlerp(const Quat l, const Quat r, const float t); DLL Vec QuatVectorTransform(const Quat q, const __m128 v); DLL Vec QuatToEuler(const Quat q, const ERotateOrder order); }
37.603448
460
0.756992
[ "vector", "3d" ]
c11718e779e9566ade3fdd4fdd081ac61c39dd49
872
h
C
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Reactive.WindowL-23794a38.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Reactive.WindowL-23794a38.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Reactive.WindowL-23794a38.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Reactive.Bindings/1.9.0/WindowList.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{namespace Reactive{struct WindowListItem;}}} namespace g{ namespace Fuse{ namespace Reactive{ // public abstract interface WindowListItem.IDataWatcher :13 // { uInterfaceType* WindowListItem__IDataWatcher_typeof(); struct WindowListItem__IDataWatcher { void(*fp_OnCurrentDataChanged)(uObject*, ::g::Fuse::Reactive::WindowListItem*, uObject*); static void OnCurrentDataChanged(const uInterface& __this, ::g::Fuse::Reactive::WindowListItem* item, uObject* oldData) { __this.VTable<WindowListItem__IDataWatcher>()->fp_OnCurrentDataChanged(__this, item, oldData); } }; // } }}} // ::g::Fuse::Reactive
36.333333
222
0.772936
[ "object" ]
c11e218cfcca5ffc1702644bbc0c5f556107ac50
1,458
h
C
include/kimera_vio_ros/utils/UtilsRos.h
AllMySlam1/Kimera-VIO-ROS
d41428701cea247a2f95674ac5515eed35dadbd9
[ "BSD-2-Clause" ]
null
null
null
include/kimera_vio_ros/utils/UtilsRos.h
AllMySlam1/Kimera-VIO-ROS
d41428701cea247a2f95674ac5515eed35dadbd9
[ "BSD-2-Clause" ]
null
null
null
include/kimera_vio_ros/utils/UtilsRos.h
AllMySlam1/Kimera-VIO-ROS
d41428701cea247a2f95674ac5515eed35dadbd9
[ "BSD-2-Clause" ]
null
null
null
/** * @file UtilsRos.h * @brief Utilities to convert from/to ROS types * @author Antoni Rosinol */ #pragma once #include <string> #include <glog/logging.h> #include <geometry_msgs/Transform.h> #include <nav_msgs/Odometry.h> #include <ros/ros.h> #include <sensor_msgs/CameraInfo.h> #include <tf2_ros/static_transform_broadcaster.h> #include <tf2_ros/transform_listener.h> #include <gtsam/geometry/Pose3.h> #include <kimera-vio/common/VioNavState.h> #include <kimera-vio/frontend/CameraParams.h> namespace VIO { namespace utils { void rosTfToGtsamPose(const geometry_msgs::Transform& tf, gtsam::Pose3* pose); void gtsamPoseToRosTf(const gtsam::Pose3& pose, geometry_msgs::Transform* tf); void rosOdometryToGtsamPose(const nav_msgs::Odometry& odom, gtsam::Pose3* pose); void msgCamInfoToCameraParams(const sensor_msgs::CameraInfoConstPtr& cam_info, const std::string& base_link_frame_id, const std::string& cam_frame_id, CameraParams* cam_params); void rosOdometryToVioNavState(const nav_msgs::Odometry& gt_odom, const ros::NodeHandle& node_handle, VioNavState* vio_navstate); } // namespace utils } // namespace VIO
28.588235
77
0.604938
[ "geometry", "transform" ]
c11fa1c7c44c05310b18803a4ff155988925edbf
19,898
c
C
src/yipf-img-gl.c
yipf/lua-graphics
bdb6c48820158e674a87985efa3335b14715f9f1
[ "MIT" ]
6
2015-04-09T09:13:20.000Z
2022-03-27T11:09:52.000Z
src/yipf-img-gl.c
yipf/lua-graphics
bdb6c48820158e674a87985efa3335b14715f9f1
[ "MIT" ]
null
null
null
src/yipf-img-gl.c
yipf/lua-graphics
bdb6c48820158e674a87985efa3335b14715f9f1
[ "MIT" ]
null
null
null
#include "yipf-img-gl.h" static GLint shadowMapUniform,texUniform; img_type create_img(unsigned int width,unsigned int height){ img_type img=(img_type)malloc(sizeof(img_type_)); img->comp=4; img->data=(char*)malloc((width*height)<<2); img->width=width; img->height=height; return img; } char * get_pixel(img_type img,unsigned int x, unsigned int y){ char *data; unsigned int width,height; if(!img){ return 0; } width=img->width; height=img->height; data=img->data; x=x>width?width:x; y=y>height?height:y; return data+(y*width+x)*(img->comp); } char* set_pixel(char* pixel,unsigned int comp, char r, char g, char b, char a){ if(!pixel) {return pixel;} switch(comp){ case 4: pixel[3]=a; case 3: pixel[2]=b; case 2: pixel[1]=g; case 1: pixel[0]=r; default: break; } return pixel; } char * copy_pixel(char* dst,unsigned int dcomp, char* src,unsigned int scomp){ unsigned int comp=dcomp>scomp?scomp:dcomp; while(comp-->0){dst[comp]=src[comp];} return dst; } int delete_img(img_type img){ if(img->data){ free(img->data); } free(img); return 0; } int save_img(img_type img,const char* filepath){ return stbi_write_png (filepath, img->width, img->height, img->comp, img->data, (img->width)*(img->comp)); return 0; } img_type load_img(char const *filepath,int req_comp){ img_type img=create_img(1,1); img->data=stbi_load (filepath, &(img->width), &(img->height), &(img->comp), req_comp); return img; } vec4 create_vec4(scalar x,scalar y,scalar z){ vec4 v=(vec4)malloc(sizeof(scalar)*4); v[0]=x; v[1]=y; v[2]=z; v[3]=1; return v; } int destroy_vec4(vec4 v){ free(v); return 0; } vec4 cross(vec4 v1,vec4 v2,vec4 v){ scalar x1,y1,z1,x2,y2,z2; x1=v1[0]; y1=v1[1]; z1=v1[2]; x2=v2[0]; y2=v2[1]; z2=v2[2]; v=v?v:create_vec4(0,0,0); v[0]=y1*z2-y2*z1; v[1]=z1*x2-z2*x1; v[2]=x1*y2-x2*y1; return v; } scalar dot(vec4 v1,vec4 v2,int n){ scalar d=0; int i; for(i=0;i<n;i++){d=d+v1[i]*v2[i];} return d; } scalar norm(vec4 v){ scalar x,y,z; x=v[0]; y=v[1]; z=v[2]; return sqrt(x*x+y*y+z*z); } vec4 normalize(vec4 v){ scalar x,y,z,n; x=v[0]; y=v[1]; z=v[2]; n=sqrt(x*x+y*y+z*z); v[0]=x/n; v[1]=y/n; v[2]=z/n; return v; } vec4 clone_vec4(vec4 src,vec4 dst,int n){ if(dst==src){ return dst; } if(!src) return src; dst=dst?dst:create_vec4(0,0,0); int i; for(i=0;i<n;i++){dst[i]=src[i]; } return dst; } mat4x4 create_mat4x4(){ return (mat4x4)malloc(sizeof(scalar)*16); } int destroy_mat4x4(mat4x4 m){ free(m); return 0; } mat4x4 make_translate(mat4x4 m,scalar tx,scalar ty,scalar tz){ m=m?m:create_mat4x4(); m[0]=1; m[1]=0; m[2]=0; m[3]=0; m[4]=0; m[5]=1; m[6]=0; m[7]=0; m[8]=0; m[9]=0; m[10]=1; m[11]=0; m[12]=tx; m[13]=ty; m[14]=tz; m[15]=1; return m; } mat4x4 make_scale(mat4x4 m,scalar sx,scalar sy,scalar sz){ m=m?m:create_mat4x4(); m[0]=sx; m[1]=0; m[2]=0; m[3]=0; m[4]=0; m[5]=sy; m[6]=0; m[7]=0; m[8]=0; m[9]=0; m[10]=sz; m[11]=0; m[12]=0; m[13]=0; m[14]=0; m[15]=1; return m; } mat4x4 make_rotate(mat4x4 m,scalar x,scalar y,scalar z,scalar ang){ scalar n,s,c; n=sqrt(x*x+y*y+z*z); s=sin(ang); c=cos(ang); x=x/n; y=y/n; z=z/n; m=m?m:create_mat4x4(); m[0]=x*x*(1-c)+c; m[4]=x*y*(1-c)-z*s; m[8]=x*z*(1-c)+y*s; m[12]=0; m[1]=x*y*(1-c)+z*s; m[5]=y*y*(1-c)+c; m[9]=y*z*(1-c)-x*s; m[13]=0; m[2]=x*z*(1-c)-y*s; m[6]=y*z*(1-c)+x*s; m[10]=z*z*(1-c)+c; m[14]=0; m[3]=0; m[7]=0 ; m[11]=0; m[15]=1; return m; } mat4x4 make_identity(mat4x4 m){ return make_scale(m,1,1,1); } mat4x4 mult_matrix(mat4x4 m2,mat4x4 m1,mat4x4 m){ m=m?m:create_mat4x4(); scalar a11,a21,a31,a41,a12,a22,a32,a42,a13,a23,a33,a43,a14,a24,a34,a44; scalar b11,b12,b13,b14,b21,b22,b23,b24,b31,b32,b33,b34,b41,b42,b43,b44; /*get m1*/ a11=m1[0];a21=m1[1];a31=m1[2];a41=m1[3]; a12=m1[4];a22=m1[5];a32=m1[6];a42=m1[7]; a13=m1[8];a23=m1[9];a33=m1[10];a43=m1[11]; a14=m1[12];a24=m1[13];a34=m1[14];a44=m1[15]; /*get m2*/ b11=m2[0];b12=m2[1];b13=m2[2];b14=m2[3]; b21=m2[4];b22=m2[5];b23=m2[6];b24=m2[7]; b31=m2[8];b32=m2[9];b33=m2[10];b34=m2[11]; b41=m2[12];b42=m2[13];b43=m2[14];b44=m2[15]; /*m=m2*m1*/ m[0]=a11*b11+a21*b21+a31*b31+a41*b41; m[1]=a11*b12+a21*b22+a31*b32+a41*b42; m[2]=a11*b13+a21*b23+a31*b33+a41*b43; m[3]=a11*b14+a21*b24+a31*b34+a41*b44; m[4]=a12*b11+a22*b21+a32*b31+a42*b41; m[5]=a12*b12+a22*b22+a32*b32+a42*b42; m[6]=a12*b13+a22*b23+a32*b33+a42*b43; m[7]=a12*b14+a22*b24+a32*b34+a42*b44; m[8]=a13*b11+a23*b21+a33*b31+a43*b41; m[9]=a13*b12+a23*b22+a33*b32+a43*b42; m[10]=a13*b13+a23*b23+a33*b33+a43*b43; m[11]=a13*b14+a23*b24+a33*b34+a43*b44; m[12]=a14*b11+a24*b21+a34*b31+a44*b41; m[13]=a14*b12+a24*b22+a34*b32+a44*b42; m[14]=a14*b13+a24*b23+a34*b33+a44*b43; m[15]=a14*b14+a24*b24+a34*b34+a44*b44; return m; } vec4 apply_mat(mat4x4 m1,vec4 v1, vec4 v){ scalar a11,a21,a31,a41,a12,a22,a32,a42,a13,a23,a33,a43,a14,a24,a34,a44; scalar b1,b2,b3,b4; v=v?v:create_vec4(0,0,0); /*get m1*/ a11=m1[0];a21=m1[1];a31=m1[2];a41=m1[3]; a12=m1[4];a22=m1[5];a32=m1[6];a42=m1[7]; a13=m1[8];a23=m1[9];a33=m1[10];a43=m1[11]; a14=m1[12];a24=m1[13];a34=m1[14];a44=m1[15]; /*get v1*/ b1=v1[0];b2=v1[1];b3=v1[2];b4=v1[3]; v[0]=a11*b1+a12*b2+a13*b3+a14*b4; v[1]=a21*b1+a22*b2+a23*b3+a24*b4; v[2]=a31*b1+a32*b2+a33*b3+a34*b4; return v; } mat4x4 clone_mat4x4(mat4x4 src,mat4x4 dst){ if(dst==src){ return dst; } if(!src) return src; dst=dst?dst:create_mat4x4(0,0,0); int i; for(i=0;i<16;i++){dst[i]=src[i];} return dst; } static scalar PI=3.1415926535898; static scalar D_PI=6.2831853071796; //~ mat4x4 push_and_apply_matrix(mat4x4 m){ //~ mat4x4 top_matrix=MATRIX_STACK+(MATRIX_STACK_TOP<<4); //~ glGetFloatv(GL_MODELVIEW_MATRIX,top_matrix); //~ ++MATRIX_STACK_TOP; //~ glMultMatrixf(m); //~ return top_matrix; //~ } //~ mat4x4 pop_matrix(void){ //~ mat4x4 top_matrix; //~ --MATRIX_STACK_TOP; //~ top_matrix=MATRIX_STACK+(MATRIX_STACK_TOP<<4); //~ glLoadMatrixf(top_matrix); //~ return top_matrix; //~ } GLuint apply_texture(GLuint tid){ glBindTexture(GL_TEXTURE_2D,tid); return tid; } mat4x4 push_and_apply_matrix(mat4x4 m){ glPushMatrix(); glMultMatrixf(m); return m; } void pop_matrix(void){ glPopMatrix(); } //~ int my_init(unsigned int matrix_max,unsigned int texture_max){ int my_init(void){ GLenum glew_state; glew_state=glewInit(); if(GLEW_OK!=glew_state) {printf("Error Loading GLEW: %d",GLEW_OK);return 1;} MATRIX_STACK_TOP=0; TEXTURE_STACK_TOP=0; glClearDepth(1.0); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); glEnable(GL_NORMALIZE); glAlphaFunc(GL_GREATER,0.1); glEnable(GL_TEXTURE_2D); // always enable textures return 0; } int gl_set_viewport(int x,int y,int w, int h){ glViewport(x,y,w,h); return 0; } camera_type create_camera(void){ return (camera_type)malloc(sizeof(camera_type_)); } camera_type make_camera(camera_type c, scalar x, scalar y, scalar z, scalar dist ){ mat4x4 m; c=c?c:create_camera(); /*c->X,Y,Z,T*/\ c->X=create_vec4(1,0,0); c->Y=create_vec4(0,1,0); c->Z=create_vec4(0,0,1); c->T=create_vec4(x,y,z); c->dist=dist; c->h=0; c->v=0; /*c->projection*/ m=create_mat4x4(); c->projection=m; /*c->view*/ m=create_mat4x4(); c->view=m; /*c->bias*/ m=make_scale(create_mat4x4(),0.5,0.5,0.5); m[12]=0.5; m[13]=0.5; m[14]=0.5; c->bias=m; return c; } camera_type move_camera(camera_type c,scalar right, scalar up, scalar back){ scalar rate; vec4 v,t; t=c->T; rate=c->dist; if(right!=0){ right*=rate; v=c->X; t[0]+=right*v[0];t[1]+=right*v[1];t[2]+=right*v[2];} /* T=T0+right*X */ if(up!=0){up*=rate; t[1]+=up;} if(back!=0){back*=rate; v=c->Z; t[0]+=back*v[0];t[2]+=back*v[2];} return c; } camera_type rotate_camera(camera_type c,scalar dh,scalar dv){ scalar h,v,hc,hs,vc,vs; vec4 x,y,z; h=(c->h)+dh; v=(c->v)+dv; while(h>PI)h-=D_PI; while(h<-PI)h+=D_PI; while(v>PI)v-=D_PI; while(v<-PI)v+=D_PI; x=c->X; y=c->Y; z=c->Z; hc=cos(h); hs=sin(h); vc=cos(v); vs=sin(v); z[0]=hs*vc; z[1]=vs; z[2]=hc*vc; x[0]=hc;x[1]=0;x[2]=-hs; y=cross(z,x,y); c->h=h; c->v=v; return c; } camera_type scale_camera(camera_type c,scalar s){ c->dist*=s; return c; } camera_type set_camera_position(camera_type c, scalar x, scalar y, scalar z){ vec4 pos=c->T; pos[0]=x; pos[1]=y; pos[2]=z; return c; } camera_type resize_camera(camera_type c, scalar w, scalar h){ mat4x4 proj=c->projection; proj[0]*=w; proj[5]*=h; return c; } void print_matrix(mat4x4 m){ int i; for(i=0;i<4;i++){ printf("\n%f\t%f\t%f\t%f",m[i],m[i+4],m[i+8],m[i+12]); } printf("\n"); } /* http://blog.csdn.net/gnuser/article/details/5146598 */ camera_type set_camera_projection(camera_type c,scalar near,scalar far,scalar fov,scalar wh){ mat4x4 proj; proj=c->projection; scalar right,top; top=near*tan(fov/2); right=wh*top; proj[0]=near/right; proj[1]=0; proj[2]=0; proj[3]=0; proj[4]=0; proj[5]=near/top; proj[6]=0; proj[7]=0; proj[8]=0; proj[9]=0; proj[10]=(far+near)/(near-far); proj[11]=-1; proj[12]=0; proj[13]=0; proj[14]=2*far*near/(near-far); proj[15]=0; return c; } camera_type set_camera_direction(camera_type c, scalar x, scalar y, scalar z,scalar upx,scalar upy,scalar upz){ vec4 X,Y,Z; X=c->X; Y=c->Y; Z=c->Z; Z[0]=-x; Z[1]=-y; Z[2]=-z; Y[0]=upx; Y[1]=upy; Y[2]=upz; cross(Y,Z,X); cross(Z,X,Y); normalize(X); normalize(Y); normalize(Z); return c; } camera_type update_camera(camera_type c){ mat4x4 view; vec4 x,y,z,t,v; scalar d; view=c->view; x=c->X; y=c->Y; z=c->Z; t=c->T; d=c->dist; v=TEMP_VEC4; v[0]=-d*z[0]-t[0]; v[1]=-d*z[1]-t[1]; v[2]=-d*z[2]-t[2]; // get invert matrix view[0]=x[0]; view[1]=y[0]; view[2] =z[0]; view[3]=0; view[4]=x[1]; view[5]=y[1]; view[6] =z[1]; view[7]=0; view[8]=x[2]; view[9]=y[2]; view[10] =z[2]; view[11]=0; view[12]=dot(v,x,3); view[13]=dot(v,y,3); view[14]=dot(v,z,3); view[15]=1; return c; } camera_type camera_look(camera_type c){ /* set projection matrix*/ glMatrixMode(GL_PROJECTION); glLoadMatrixf(c->projection); glMultMatrixf(c->view); /* set modelview matrix*/ glMatrixMode(GL_MODELVIEW); //~ glLoadIdentity(); return c; } int gl_options(int op){ if(op&TEXTURE_2D){glEnable(GL_TEXTURE_2D);}else{ glDisable(GL_TEXTURE_2D);} if(op&LIGHTING){glEnable(GL_LIGHTING);}else{ glDisable(GL_LIGHTING);} if(op&CULL_FACE){glEnable(GL_CULL_FACE);}else{ glDisable(GL_CULL_FACE);} if(op&BLEND){glEnable(GL_BLEND);}else{ glDisable(GL_BLEND);} if(op&FOG){glEnable(GL_FOG);}else{ glDisable(GL_FOG);} if(op&FILL){glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);}else{glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);} if(op&SMOOTH){glShadeModel(GL_SMOOTH);}else{glShadeModel(GL_FLAT);} return 0; } int gl_set_light(int id,scalar x,scalar y,scalar z,scalar w){ TEMP_VEC4[0]=x; TEMP_VEC4[1]=y; TEMP_VEC4[2]=z; TEMP_VEC4[3]=w; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_LIGHT0); switch(id){ case 0: glLightfv (GL_LIGHT0, GL_POSITION, TEMP_VEC4); break; default: break; } return 0; } int gl_clear_all(void){ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); return 0; } int gl_set_bg_color(unsigned char r,unsigned char g,unsigned char b,unsigned char a){ glClearColor (r/255.0, g/255.0, b/255.0, a/255.0); return 0; } /* texture */ texture_type gen_mem_img(unsigned int w,unsigned int h){ texture_type tex=(texture_type)malloc(sizeof(texture_type_)); w=w>0?w:1; h=h>0?h:1; tex->data=(unsigned char*)malloc(w*h*4); tex->w=w; tex->h=h; return tex; } texture_type set_mem_img_color(texture_type tex, unsigned int x,unsigned int y, unsigned char r,unsigned char g,unsigned char b,unsigned char a ){ unsigned char * p; if(!tex){ tex=gen_mem_img(1,1); p=tex->data; }else{ p=(tex->data)+(y*(tex->w)+x)*4; } p[0]=r; p[1]=g; p[2]=b; p[3]=a; return tex; } GLuint mem_img2texture(texture_type tex){ GLuint id; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id ); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->w,tex->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex->data ); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); free(tex->data); free(tex); return id; } GLuint img2texture(char const *filepath){ GLuint id; unsigned int w,h,comp; unsigned char *data; data=stbi_load(filepath,&w,&h,&comp,4); if(!data){ printf("Error when loading file: %s",filepath); return 0; } glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id ); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,w,h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); free(data); return id; } /* call list */ GLuint begin_gen_calllist(void){ GLuint id; id = glGenLists (1);//glGenLists()唯一的标识一个显示列表 glNewList(id, GL_COMPILE); return id; } GLuint end_gen_calllist(void){ glEndList(); return 0; } GLuint call_list(GLuint id){ glCallList(id); return id; } /* drawer */ int begin_draw(int type){ switch(type){ case POINTS: glBegin(GL_POINTS); break; case LINES: glBegin(GL_LINES); break; case POLYGON: glBegin(GL_POLYGON); break; case TRIANGLES: glBegin(GL_TRIANGLES); break; case QUADS: glBegin(GL_QUADS); break; case LINE_STRIP: glBegin(GL_LINE_STRIP); break; case LINE_LOOP: glBegin(GL_LINE_LOOP); break; case TRIANGLE_STRIP: glBegin(GL_TRIANGLE_STRIP); break; case TRIANGLE_FAN: glBegin(GL_TRIANGLE_FAN); break; case QUAD_STRIP: glBegin(GL_QUAD_STRIP); break; default: break; } return type; } int end_draw(void){ glEnd(); } int set_vertex(scalar x,scalar y,scalar z,scalar tx,scalar ty, scalar nx, scalar ny, scalar nz){ glTexCoord2f(tx,ty); glNormal3f(nx,ny,nz); glVertex3f(x,y,z); return 0; } int draw_box(scalar r){ glBegin(GL_QUADS); /* top */ set_vertex(r,r,r,0,0,0,1,0);set_vertex(r,r,-r,0,1,0,1,0);set_vertex(-r,r,-r,1,1,0,1,0);set_vertex(-r,r,r,1,0,0,1,0); /* bottom */ set_vertex(r,-r,r,0,0,0,-1,0);set_vertex(-r,-r,r,0,1,0,-1,0);set_vertex(-r,-r,-r,1,1,0,-1,0);set_vertex(r,-r,-r,1,0,0,-1,0); /* left */ set_vertex(-r,r,r,0,0,-1,0,0);set_vertex(-r,r,-r,0,1,-1,0,0);set_vertex(-r,-r,-r,1,1,-1,0,0);set_vertex(-r,-r,r,1,0,-1,0,0); /* right */ set_vertex(r,r,r,0,0,1,0,0);set_vertex(r,-r,r,0,1,1,0,0);set_vertex(r,-r,-r,1,1,1,0,0);set_vertex(r,r,-r,1,0,1,0,0); /* front */ set_vertex(r,r,r,0,0,0,0,1);set_vertex(-r,r,r,0,1,0,0,1);set_vertex(-r,-r,r,1,1,0,0,1);set_vertex(r,-r,r,1,0,0,0,1); /* back */ set_vertex(r,r,-r,0,0,0,0,-1);set_vertex(r,-r,-r,0,1,0,0,-1);set_vertex(-r,-r,-r,1,1,0,0,-1);set_vertex(-r,r,-r,1,0,0,0,-1); glEnd(); return 0; } int draw_plane(scalar r){ glBegin(GL_QUADS); set_vertex(r,0,r,0.0,0.0,0,1,0);set_vertex(r,0,-r,0.0,1.0,0,1,0);set_vertex(-r,0,-r,1.0,1.0,0,1,0);set_vertex(-r,0,r,1.0,0.0,0,1,0); glEnd(); return 0; } GLhandleARB compile_shader(const char* string,GLenum type){ GLhandleARB handle; GLint result; // Compilation code result GLint errorLoglength; char* errorLogText; GLsizei actualErrorLogLength; handle = glCreateShaderObjectARB(type); if (!handle){ //We have failed creating the vertex shader object. printf("Failed creating vertex shader object!"); return 0; } glShaderSourceARB(handle, 1, &string, 0); glCompileShaderARB(handle); //Compilation checking. glGetObjectParameterivARB(handle, GL_OBJECT_COMPILE_STATUS_ARB, &result); if (!result) { printf("Failed to compile shader:"); glGetObjectParameterivARB(handle, GL_OBJECT_INFO_LOG_LENGTH_ARB, &errorLoglength); errorLogText = malloc(sizeof(char) * errorLoglength); glGetInfoLogARB(handle, errorLoglength, &actualErrorLogLength, errorLogText); printf("%s\n",errorLogText); free(errorLogText); } return handle; } GLhandleARB build_shader(const char* vert,const char* frag){ GLhandleARB shadowShaderId; shadowShaderId = glCreateProgramObjectARB(); glAttachObjectARB(shadowShaderId,vert?compile_shader(vert,GL_VERTEX_SHADER):0); glAttachObjectARB(shadowShaderId,frag?compile_shader(frag,GL_FRAGMENT_SHADER):0); glLinkProgramARB(shadowShaderId); return shadowShaderId; } GLhandleARB apply_shader(GLhandleARB shaderid){ glUseProgramObjectARB(shaderid); return shaderid; } static GLuint shadowmapTex=0; static GLuint SHADOW_MAP_WIDTH=2048; static GLuint SHADOW_MAP_HEIGHT=2048; static GLuint shadowmapFBO=0; render_type create_render(GLuint width, GLuint height,int render_mode){ render_type r; r=(render_type)malloc(sizeof(render_type_)); glGenFramebuffersEXT(1, &(r->FBO)); r->depth_tex=0; r->color_tex=0; return resize_tex(r,width,height,render_mode); } render_type resize_tex(render_type r,GLuint width, GLuint height,int render_mode){ glEnable(GL_TEXTURE_2D); if(render_mode&DEPTH){ if(r->depth_tex) glDeleteTextures(1,&(r->depth_tex)); glGenTextures(1, &(r->depth_tex)); glBindTexture(GL_TEXTURE_2D, (r->depth_tex) ); glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT,width,height,0,GL_DEPTH_COMPONENT,GL_UNSIGNED_BYTE,NULL); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); } if(render_mode&COLOR){ if(r->color_tex) glDeleteTextures(1,&(r->color_tex)); glGenTextures(1, &(r->color_tex)); glBindTexture(GL_TEXTURE_2D, (r->color_tex) ); glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,NULL); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r->FBO); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, r->depth_tex, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, r->color_tex, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); return r; } render_type apply_render(render_type r){ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r?(r->FBO):0); return r; } int build_shadowmap(camera_type light,render_type r){ // draw to shadowmap texture //~ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, shadowmapFBO); apply_render(r); glPushAttrib(GL_VIEWPORT_BIT | GL_COLOR_BUFFER_BIT); glClear( GL_DEPTH_BUFFER_BIT); glViewport(0,0,SHADOW_MAP_WIDTH,SHADOW_MAP_HEIGHT); glCullFace(GL_FRONT); // only draw back faces camera_look(light); glUseProgramObjectARB(0); return 0; } int bind_shadowmap(camera_type light,GLhandleARB shader,render_type r){ // return to normal rendering glPopAttrib(); glCullFace(GL_BACK); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // Go back to normal matrix mode glCullFace(GL_BACK); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // apply shader and set bind TEXTURE1: shadowmap glUseProgramObjectARB(shader); glActiveTextureARB(GL_TEXTURE1); //~ glBindTexture(GL_TEXTURE_2D, shadowmapTex); glBindTexture(GL_TEXTURE_2D, r->depth_tex); glUniform1iARB(glGetUniformLocationARB(shader,"shadowmap"), 1); glUniform1iARB(glGetUniformLocationARB(shader,"tex"), 0); // set texture matrix for texture1 glMatrixMode(GL_TEXTURE); glLoadIdentity(); glLoadMatrixf(light->bias); glMultMatrixf (light->projection); glMultMatrixf (light->view); glActiveTextureARB(GL_TEXTURE0); return 0; }
28.466381
146
0.689265
[ "object" ]
c12382a2af02794339e4a88102d2b8e68fe2b030
7,017
h
C
include/ged/database.h
Zitara/BRLCAD
620449d036e38bd52257f6b5b10daa55d9284900
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
include/ged/database.h
Zitara/BRLCAD
620449d036e38bd52257f6b5b10daa55d9284900
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
include/ged/database.h
Zitara/BRLCAD
620449d036e38bd52257f6b5b10daa55d9284900
[ "BSD-4-Clause", "BSD-3-Clause" ]
1
2018-12-21T21:09:47.000Z
2018-12-21T21:09:47.000Z
/* D A T A B A S E . H * BRL-CAD * * Copyright (c) 2008-2016 United States Government as represented by * the U.S. Army Research Laboratory. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @addtogroup ged_database * * Geometry EDiting Library Database Level Functions. * */ /** @{ */ /** @file ged/database.h */ #ifndef GED_DATABASE_H #define GED_DATABASE_H #include "common.h" #include "ged/defines.h" __BEGIN_DECLS /** Check if a database is open */ #define GED_CHECK_DATABASE_OPEN(_gedp, _flags) \ if ((_gedp) == GED_NULL || (_gedp)->ged_wdbp == RT_WDB_NULL || (_gedp)->ged_wdbp->dbip == DBI_NULL) { \ int ged_check_database_open_quiet = (_flags) & GED_QUIET; \ if (!ged_check_database_open_quiet) { \ if ((_gedp) != GED_NULL) { \ bu_vls_trunc((_gedp)->ged_result_str, 0); \ bu_vls_printf((_gedp)->ged_result_str, "A database is not open!"); \ } else {\ bu_log("A database is not open!\n"); \ } \ } \ return (_flags); \ } /** * Set/get the database title */ GED_EXPORT extern int ged_title(struct ged *gedp, int argc, const char *argv[]); /* defined in rt.c */ GED_EXPORT extern int ged_build_tops(struct ged *gedp, char **start, char **end); GED_EXPORT extern size_t ged_count_tops(struct ged *gedp); /** * Find all top level objects */ GED_EXPORT extern int ged_tops(struct ged *gedp, int argc, const char *argv[]); /** * Get dbip */ GED_EXPORT extern int ged_dbip(struct ged *gedp, int argc, const char *argv[]); /** * Dump a full copy of the database into file.g */ GED_EXPORT extern int ged_dump(struct ged *gedp, int argc, const char *argv[]); /** * Find combinations that reference object */ GED_EXPORT extern int ged_find(struct ged *gedp, int argc, const char *argv[]); /** * Globs expression against the database */ GED_EXPORT extern int ged_glob(struct ged *gedp, int argc, const char *argv[]); /** * Import a database into the current database using an auto-incrementing or custom affix */ GED_EXPORT extern int ged_concat(struct ged *gedp, int argc, const char *argv[]); /** * Check for duplicate names in file */ GED_EXPORT extern int ged_dup(struct ged *gedp, int argc, const char *argv[]); /** * Text edit the color table */ GED_EXPORT extern int ged_edcolor(struct ged *gedp, int argc, const char *argv[]); /** * Edit file. */ GED_EXPORT extern int ged_editit(struct ged *gedp, int argc, const char *argv[]); /** * List the objects in this database */ GED_EXPORT extern int ged_ls(struct ged *gedp, int argc, const char *argv[]); /** * List all paths from name(s) to leaves */ GED_EXPORT extern int ged_pathlist(struct ged *gedp, int argc, const char *argv[]); /** * Lists all paths matching the input path */ GED_EXPORT extern int ged_pathsum(struct ged *gedp, int argc, const char *argv[]); /** * Show the matrix transformations along path */ GED_EXPORT extern int ged_showmats(struct ged *gedp, int argc, const char *argv[]); /** * Checks that each directory in the supplied path actually has the subdirectories * that are implied by the path. */ GED_EXPORT extern int ged_path_validate(struct ged *gedp, const struct db_full_path * const path); /** * Returns a list of id to region name mappings for the entire database. */ GED_EXPORT extern int ged_rmap(struct ged *gedp, int argc, const char *argv[]); /** * Set/get tessellation and calculation tolerances */ GED_EXPORT extern int ged_tol(struct ged *gedp, int argc, const char *argv[]); /** * Set/get the database units */ GED_EXPORT extern int ged_units(struct ged *gedp, int argc, const char *argv[]); /** * Returns the database version. */ GED_EXPORT extern int ged_version(struct ged *gedp, int argc, const char *argv[]); /** * Write region ident codes to filename. */ GED_EXPORT extern int ged_wcodes(struct ged *gedp, int argc, const char *argv[]); /* defined in copy.c */ GED_EXPORT extern int ged_dbcopy(struct ged *from_gedp, struct ged *to_gedp, const char *from, const char *to, int fflag); /** * Globs expression against database objects */ GED_EXPORT extern int ged_expand(struct ged *gedp, int argc, const char *argv[]); /** * Set region ident codes. */ GED_EXPORT extern int ged_item(struct ged *gedp, int argc, const char *argv[]); /** * Open a database */ GED_EXPORT extern int ged_reopen(struct ged *gedp, int argc, const char *argv[]); /** * Read region ident codes from filename. */ GED_EXPORT extern int ged_rcodes(struct ged *gedp, int argc, const char *argv[]); /** * Change the default region ident codes: item air los mat */ GED_EXPORT extern int ged_regdef(struct ged *gedp, int argc, const char *argv[]); /** * Read material properties from a file. */ GED_EXPORT extern int ged_rmater(struct ged *gedp, int argc, const char *argv[]); /** * Interface to search functionality (i.e. Unix find for geometry) */ GED_EXPORT extern int ged_search(struct ged *gedp, int argc, const char *argv[]); /** * Count/list primitives/regions/groups */ GED_EXPORT extern int ged_summary(struct ged *gedp, int argc, const char *argv[]); /** * Sync up the in-memory database with the on-disk database. */ GED_EXPORT extern int ged_sync(struct ged *gedp, int argc, const char *argv[]); /** * The ged_tables() function serves idents, regions and solids. * * Make ascii summary of region idents. * */ GED_EXPORT extern int ged_tables(struct ged *gedp, int argc, const char *argv[]); /** * The ged_which() function serves both whichair and whichid. * * Find the regions with the specified air codes. Find the regions * with the specified region ids. */ GED_EXPORT extern int ged_which(struct ged *gedp, int argc, const char *argv[]); /** * Return all combinations with the specified shaders. */ GED_EXPORT extern int ged_which_shader(struct ged *gedp, int argc, const char *argv[]); /** * Make color entry. */ GED_EXPORT extern int ged_color(struct ged *gedp, int argc, const char *argv[]); /** * Print color table */ GED_EXPORT extern int ged_prcolor(struct ged *gedp, int argc, const char *argv[]); /** * Get/set the output handler script */ GED_EXPORT extern int ged_set_output_script(struct ged *gedp, int argc, const char *argv[]); __END_DECLS #endif /* GED_DATABASE_H */ /** @} */ /* * Local Variables: * tab-width: 8 * mode: C * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
26.182836
107
0.697592
[ "cad", "geometry", "object" ]
c126941dcf22b34dd965fb853f2e2d1faa9b70c0
1,264
h
C
PrivateFrameworks/CoreSuggestionsInternals/SGSymbolicMappingTransformer.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/CoreSuggestionsInternals/SGSymbolicMappingTransformer.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/CoreSuggestionsInternals/SGSymbolicMappingTransformer.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" #import "PMLTransformerProtocol.h" @class NSCharacterSet, NSString; @interface SGSymbolicMappingTransformer : NSObject <PMLTransformerProtocol> { NSString *_numericMapping; NSString *_characterMapping; NSCharacterSet *_characterSet; } + (id)withNumericMapping:(id)arg1 andSymbolicMapping:(id)arg2; @property(retain) NSCharacterSet *characterSet; // @synthesize characterSet=_characterSet; @property(retain) NSString *characterMapping; // @synthesize characterMapping=_characterMapping; @property(retain) NSString *numericMapping; // @synthesize numericMapping=_numericMapping; - (void).cxx_destruct; @property(readonly) unsigned long long hash; - (BOOL)isEqual:(id)arg1; - (BOOL)isEqualToSymbolicMappingTransformer:(id)arg1; - (id)initWithPlist:(id)arg1 chunks:(id)arg2 context:(id)arg3; - (id)toPlistWithChunks:(id)arg1; - (id)transform:(id)arg1; - (id)initWithNumericMapping:(id)arg1 andSymbolicMapping:(id)arg2; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) Class superclass; @end
31.6
96
0.768196
[ "transform" ]
c12bac32d20d6abddb41da7a4664217e0717de34
4,682
h
C
scip/applications/STP/src/cons_stp.h
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
null
null
null
scip/applications/STP/src/cons_stp.h
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
null
null
null
scip/applications/STP/src/cons_stp.h
avrech/scipoptsuite-6.0.2-avrech
bb4ef31b6e84ff7e1e65cee982acf150739cda86
[ "MIT" ]
1
2022-01-19T01:15:11.000Z
2022-01-19T01:15:11.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and library */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2002-2019 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SCIP is distributed under the terms of the ZIB Academic License. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with SCIP; see the file COPYING. If not visit scip.zib.de. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file cons_stp.h * @brief Constraint handler for Steiner problems * @author Gerald Gamrath * @author Daniel Rehfeldt * @author Michael Winkler * * This file checks solutions for feasibility and separates violated model constraints. For more details see \ref STP_CONS page. */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #ifndef __SCIP_CONS_STP_H__ #define __SCIP_CONS_STP_H__ #include "scip/scip.h" #include "grph.h" #ifdef __cplusplus extern "C" { #endif #ifndef RESTRICT #define RESTRICT restrict #endif /** creates the handler for element constraints and includes it in SCIP */ SCIP_RETCODE SCIPincludeConshdlrStp( SCIP* scip /**< SCIP data structure */ ); /** creates and captures a stp constraint */ SCIP_RETCODE SCIPcreateConsStp( SCIP* scip, /**< SCIP data structure */ SCIP_CONS** cons, /**< pointer to hold the created constraint */ const char* name, /**< name of constraint */ GRAPH* graph /**< graph data structure */ ); /** sets graph */ void SCIPStpConshdlrSetGraph( SCIP* scip, /**< SCIP data structure */ const GRAPH* g /**< graph data structure */ ); /** dual ascent heuristic */ SCIP_RETCODE SCIPStpDualAscent( SCIP* scip, /**< SCIP data structure */ const GRAPH* g, /**< graph data structure */ SCIP_Real* RESTRICT redcost, /**< array to store reduced costs or NULL */ SCIP_Real* RESTRICT nodearrreal, /**< real vertices array for internal computations or NULL */ SCIP_Real* objval, /**< pointer to store objective value */ SCIP_Bool addcuts, /**< should dual ascent add Steiner cuts? */ SCIP_Bool ascendandprune, /**< should the ascent-and-prune heuristic be executed? */ GNODE** gnodearrterms, /**< gnode terminals array for internal computations or NULL */ const int* result, /**< solution array (solution needs to be provided) */ int* RESTRICT edgearrint, /**< int edges array for internal computations or NULL */ int* RESTRICT nodearrint, /**< int vertices array for internal computations or NULL */ int root, /**< the root */ SCIP_Bool is_pseudoroot, /**< is the root a pseudo root? */ SCIP_Real damaxdeviation, /**< number of dual ascent runs */ STP_Bool* RESTRICT nodearrchar /**< char vertices array for internal computations or NULL */ ); /** dual ascent heuristic for the PCSPG and the MWCSP */ SCIP_RETCODE SCIPStpDualAscentPcMw( SCIP* scip, /**< SCIP data structure */ GRAPH* g, /**< graph data structure */ SCIP_Real* redcost, /**< array to store reduced costs or NULL */ SCIP_Real* objval, /**< pointer to store objective value */ SCIP_Bool addcuts, /**< should dual ascent add Steiner cuts? */ SCIP_Bool ascendandprune, /**< perform ascend-and-prune and add solution? */ int nruns /**< number of dual ascent runs */ ); #ifdef __cplusplus } #endif #endif
47.77551
128
0.47736
[ "model" ]
c12e8b1d5cc75ec01856440b4efeff68523f5f7a
6,131
h
C
Gems/AWSCore/Code/Include/Framework/RequestBuilder.h
whywhywhyw/o3de
8e09f66799d4c8f188d45861d821e8656a554cb1
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/AWSCore/Code/Include/Public/Framework/RequestBuilder.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/AWSCore/Code/Include/Public/Framework/RequestBuilder.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <Framework/JsonWriter.h> // The AWS Native SDK AWSAllocator triggers a warning due to accessing members of std::allocator directly. // AWSAllocator.h(70): warning C4996: 'std::allocator<T>::pointer': warning STL4010: Various members of std::allocator are deprecated in C++17. // Use std::allocator_traits instead of accessing these members directly. // You can define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING or _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have received this warning. #include <AzCore/PlatformDef.h> AZ_PUSH_DISABLE_WARNING(4251 4996, "-Wunknown-warning-option") #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/http/HttpTypes.h> AZ_POP_DISABLE_WARNING namespace Aws { namespace Client { class AWSAuthSigner; } } namespace AWSCore { /// Provides methods for replacing url path parameters, appending /// url query string parameters, and writing body content. class RequestBuilder { public: RequestBuilder(); /// Converts the provided object to JSON and sends it as the /// body of the request. The object can implement the following /// function to enable serialization: /// /// bool WriteJson(ServiceApi::JsonWriter& writer) const /// { /// bool ok = true; /// ok = ok && writer.StartObject(); /// ... /// ok = ok && writer.EndObject(); /// return ok; /// } /// /// Alternatively you can provide a global function with the /// following signature: /// /// namespace AWSCore { /// template<> /// bool GlobalWriteJson<MyObjectType>(ServiceApi::JsonWriter& writer, const MyObjectType& source) /// { /// bool ok = true; /// ... /// return ok; /// } /// } /// template<class ObjectType> bool WriteJsonBodyParameter(const ObjectType& bodyObject) { m_bodyContent = std::make_shared<Aws::StringStream>(); JsonOutputStream stream{ *m_bodyContent.get() }; return JsonWriter::WriteObject(stream, bodyObject); } bool WriteJsonBodyRaw(const AZStd::string& body) { m_bodyContent = std::make_shared<Aws::StringStream>(); m_bodyContent->str(body.c_str()); return true; } const Aws::String& GetRequestUrl() { return m_requestUrl; } void SetRequestUrl(const Aws::String& requestUrl) { m_requestUrl = requestUrl; } /// Replaces a key with an escaped value. Key should be /// "{foo}" to replace the "{foo}" part of "/bar/{foo}". bool SetPathParameter(const char* key, const AZStd::string& value); bool SetPathParameter(const char* key, const char* value); bool SetPathParameter(const char* key, double value); bool SetPathParameter(const char* key, bool value); bool SetPathParameter(const char* key, int value); bool SetPathParameter(const char* key, int64_t value); bool SetPathParameter(const char* key, unsigned value); bool SetPathParameter(const char* key, uint64_t value); /// Appends a query parameter to the url. An "?" or "&" is added /// as needed. The value is escaped. bool AddQueryParameter(const char* name, const AZStd::string& value); bool AddQueryParameter(const char* name, const char* value); bool AddQueryParameter(const char* name, double value); bool AddQueryParameter(const char* name, bool value); bool AddQueryParameter(const char* name, int value); bool AddQueryParameter(const char* name, int64_t value); bool AddQueryParameter(const char* name, unsigned value); bool AddQueryParameter(const char* name, uint64_t value); Aws::Http::HttpMethod GetHttpMethod() { return m_httpMethod; } void SetHttpMethod(Aws::Http::HttpMethod httpMethod) { m_httpMethod = httpMethod; } const AZStd::string& GetErrorMessage() { return m_errorMessage; } void SetErrorMessage(const AZStd::string& message) { m_errorMessage = message; } std::shared_ptr<Aws::StringStream> GetBodyContent() { return m_bodyContent; } void SetAWSAuthSigner(std::shared_ptr<Aws::Client::AWSAuthSigner> awsAuthSigner) { m_AWSAuthSigner = awsAuthSigner; } std::shared_ptr<Aws::Client::AWSAuthSigner> GetAWSAuthSigner() { return m_AWSAuthSigner; } private: bool SetPathParameterUnescaped(const char* key, const char* value); bool AddQueryParameterUnescaped(const char* name, const char* value); /// copy and assignment not supported. RequestBuilder(const RequestBuilder&) = delete; RequestBuilder& operator=(const RequestBuilder&) = delete; /// HTTP method for the request. Aws::Http::HttpMethod m_httpMethod; /// The url being modified. Aws::String m_requestUrl; /// Description of error should one occur. AZStd::string m_errorMessage; /// JSON format body content. std::shared_ptr<Aws::StringStream> m_bodyContent; /// Appends characters from value to target, escaping special characters. static Aws::String escape(const char* value); //? AWS signer to use for request signing std::shared_ptr<Aws::Client::AWSAuthSigner> m_AWSAuthSigner{ nullptr }; }; } // namespace AWSCore
34.44382
169
0.621921
[ "object", "3d" ]
c132900f57099d0e3804a9a0534364b3855f237c
3,694
c
C
opal/dss/dss_size.c
ystk/debian-openmpi
cea6f8a27c406a30cfa81d49ab479d3f67a58878
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
opal/dss/dss_size.c
ystk/debian-openmpi
cea6f8a27c406a30cfa81d49ab479d3f67a58878
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
opal/dss/dss_size.c
ystk/debian-openmpi
cea6f8a27c406a30cfa81d49ab479d3f67a58878
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
/* * Copyright (c) 2004-2007 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2006 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "opal_config.h" #include "opal/dss/dss_internal.h" int opal_dss_size(size_t *size, void *src, opal_data_type_t type) { opal_dss_type_info_t *info; /* check for error */ if (NULL == size) { return OPAL_ERR_BAD_PARAM; } /* Lookup the size function for this type and call it */ if (NULL == (info = (opal_dss_type_info_t*)opal_pointer_array_get_item(&opal_dss_types, type))) { return OPAL_ERR_UNKNOWN_DATA_TYPE; } return info->odti_size_fn(size, src, type); } /* * STANDARD SIZE FUNCTION - WORKS FOR EVERYTHING NON-STRUCTURED */ int opal_dss_std_size(size_t *size, void *src, opal_data_type_t type) { switch(type) { case OPAL_BOOL: *size = sizeof(bool); break; case OPAL_INT: case OPAL_UINT: *size = sizeof(int); break; case OPAL_SIZE: *size = sizeof(size_t); break; case OPAL_PID: *size = sizeof(pid_t); break; case OPAL_BYTE: case OPAL_INT8: case OPAL_UINT8: case OPAL_NULL: *size = 1; break; case OPAL_INT16: case OPAL_UINT16: *size = sizeof(uint16_t); break; case OPAL_INT32: case OPAL_UINT32: *size = sizeof(uint32_t); break; case OPAL_INT64: case OPAL_UINT64: *size = sizeof(uint64_t); break; case OPAL_DATA_TYPE: *size = sizeof(opal_data_type_t); break; default: *size = 0; return OPAL_ERR_UNKNOWN_DATA_TYPE; } return OPAL_SUCCESS; } /* SIZE FUNCTIONS FOR NON-STANDARD SYSTEM TYPES */ /* * STRING */ int opal_dss_size_string(size_t *size, char *src, opal_data_type_t type) { if (NULL != src) { *size = strlen(src) + 1; } else { *size = sizeof(char*); /* account for NULL */ } return OPAL_SUCCESS; } /* SIZE FUNCTIONS FOR GENERIC OPAL TYPES */ /* * OPAL_DATA_VALUE */ int opal_dss_size_data_value(size_t *size, opal_dss_value_t *src, opal_data_type_t type) { size_t data_size; int rc; /* account for size of object itself... */ *size = sizeof(opal_dss_value_t); if (NULL != src) { /* ...and the number of bytes in the payload, IF an actual object was provided */ if (OPAL_SUCCESS != (rc = opal_dss.size(&data_size, src->data, src->type))) { return rc; } *size += data_size; } return OPAL_SUCCESS; } /* * OPAL_BYTE_OBJECT */ int opal_dss_size_byte_object(size_t *size, opal_byte_object_t *src, opal_data_type_t type) { /* account for size of object itself... */ *size = sizeof(opal_byte_object_t); if (NULL != src) { /* ...and the number of bytes in the payload, IF an actual object was provided */ *size += src->size; } return OPAL_SUCCESS; }
23.832258
101
0.582025
[ "object" ]
c13417b9ae96513ea16fdba6b5753a98e406ab85
6,554
h
C
pjsip/pjnath/docs/doc_turn.h
tomorrow-rain/pjsip
776e032c4ee2672cd42b8c665021b1310181d126
[ "MIT" ]
null
null
null
pjsip/pjnath/docs/doc_turn.h
tomorrow-rain/pjsip
776e032c4ee2672cd42b8c665021b1310181d126
[ "MIT" ]
null
null
null
pjsip/pjnath/docs/doc_turn.h
tomorrow-rain/pjsip
776e032c4ee2672cd42b8c665021b1310181d126
[ "MIT" ]
null
null
null
/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** @defgroup PJNATH_TURN TURN: Traversal Using Relays around NAT @brief TURN protocol implementation @ingroup PJNATH \section turn_intro_sec Introduction to TURN When a direct communication path cannot be found, it is necessary to use the services of an intermediate host that acts as a relay for the packets. This relay typically sits in the public Internet and relays packets between two hosts that both sit behind NATs. TURN allows a host behind a NAT (called the TURN client) to request that another host (called the TURN server) act as a relay. The client can arrange for the server to relay packets to and from certain other hosts (called peers) and can control aspects of how the relaying is done. The client does this by obtaining an IP address and port on the server, called the relayed-transport-address. When a peer sends a packet to the relayed-transport-address, the server relays the packet to the client. When the client sends a data packet to the server, the server relays it to the appropriate peer using the relayed- transport-address as the source. \section turn_op_sec Overview of TURN operations <b>Discovering TURN server</b>.\n Client learns the IP address of the TURN server either through some privisioning or by querying DNS SRV records for TURN service for the specified domain. Client may use UDP or TCP (or TLS) to connect to the TURN server. <b>Authentication</b>.\n All TURN operations requires the use of authentication (it uses STUN long term autentication method), hence client must be configured with the correct credential to use the service. <b>Allocation</b>.\n Client creates one "relay port" (or called <b>relayed-transport-address</b> in TURN terminology) in the TURN server by sending TURN \a Allocate request, hence this process is called creating allocation. Once the allocation is successful, client will be given the IP address and port of the "relay port" in the Allocate response. <b>Sending data through the relay</b>.\n Once allocation has been created, client may send data to any remote endpoints (called peers in TURN terminology) via the "relay port". It does so by sending Send Indication to the TURN server, giving the peer address in the indication message. But note that at this point peers are not allowed to send data towards the client (via the "relay port") before permission is installed for that peer. <b>Creating permissions</b>.\n Permission needs to be created in the TURN server so that a peer can send data to the client via the relay port (a peer in this case is identified by its IP address). Without this, when the TURN server receives data from the peer in the "relay port", it will drop this data. <b>Receiving data from peers</b>.\n Once permission has been installed for the peer, any data received by the TURN server (from that peer) in the "relay port" will be relayed back to client by using Data Indication. <b>Using ChannelData</b>.\n TURN provides optimized framing to the data by using ChannelData packetization. The client activates this format by sending ChannelBind request to the TURN server, which provides (channel) binding which maps a particular peer address with a channel number. Data sent or received to/for this peer will then use ChannelData format instead of Send or Data Indications. <b>Refreshing the allocation, permissions, and channel bindings</b>.\n Allocations, permissions, and channel bindings need to be refreshed periodically by client, or otherwise they will expire. <b>Destroying the allocation</b>.\n Once the "relay port" is no longer needed, client destroys the allocation by sending Refresh request with LIFETIME attribute set to zero. \section turn_org_sec Library organizations The TURN functionalities in PJNATH primarily consist of \ref PJNATH_TURN_SOCK and \ref PJNATH_TURN_SESSION. Please see more below. \section turn_using_sec Using TURN transport The \ref PJNATH_TURN_SOCK is a ready to use object for relaying application data via a TURN server, by managing all the operations above. Among other things it provides the following features: - resolution of the TURN server with DNS SRV - interface to create allocation, permissions, and channel bindings - interface to send and receive packets through the relay - provides callback to notify the application about incoming data - managing the allocation, permissions, and channel bindings Please see \ref PJNATH_TURN_SOCK for more documentation about and on how to use this object. \section turn_owntransport_sec Creating custom TURN transport The \ref PJNATH_TURN_SESSION is a transport-independent object to manage a client TURN session. It contains the core logic for managing the TURN client session as listed in TURN operations above, but in transport-independent manner (i.e. it doesn't have a socket), so that developer can integrate TURN client functionality into existing framework that already has its own means to send and receive data, or to support new transport types to TURN, such as TLS. You can create your own (custom) TURN transport by wrapping this into your own object, and provide it with the means to send and receive packets. Please see \ref PJNATH_TURN_SESSION for more information. \section turn_samples_sec Samples The \ref turn_client_sample is a sample application to use the \ref PJNATH_TURN_SOCK. Also there is a sample TURN server in the distribution as well. Also see <b>\ref samples_page</b> for other samples. */ /** * @defgroup PJNATH_TURN_SOCK TURN client transport * @brief Client transport utilizing TURN relay * @ingroup PJNATH_TURN */ /** * @defgroup PJNATH_TURN_SESSION TURN client session * @brief Transport independent TURN client session * @ingroup PJNATH_TURN */
39.721212
77
0.784406
[ "object" ]
c13569ce36cd961eba29b81a9bb5278a12a8365a
9,536
h
C
include/Random.h
chorman0773/random-c
e10545ddbaff2e2b4e6fc544e17e7e6e1a1bfb5b
[ "MIT" ]
null
null
null
include/Random.h
chorman0773/random-c
e10545ddbaff2e2b4e6fc544e17e7e6e1a1bfb5b
[ "MIT" ]
null
null
null
include/Random.h
chorman0773/random-c
e10545ddbaff2e2b4e6fc544e17e7e6e1a1bfb5b
[ "MIT" ]
null
null
null
/* * Random.h * * Created on: Sep 18, 2019 * Author: chorm * Copyright (C) 2019, Connor Horman. * Released under the terms of the MIT License, see the acompanying LICENSE */ #ifndef INCLUDE_RANDOM_H_ #define INCLUDE_RANDOM_H_ #ifdef __cplusplus extern"C"{ #endif #include <stdint.h> #include <stddef.h> #include <stdbool.h> /// //The implementation of Random here is according to the LCLib Random Specification //The implementation is defined by Oracle, under java.util.Random, which is adopted // as standard by LCLib. //The implementation is according to https://docs.oracle.com/javase/8/docs/api/java/util/Random.html // Pursuant to that documentation, this code comes with the following warnings // /// Thread-safety // If this file is compiled with the macro TIGAME_MULTITHREAD_SUPPORT, // then instances of Random are thread safe. However, use of // a single instance of Random across multiple threads may // encounter contention, and therefore is disabled. // If thread-safety is not required, the macro can be left undefined, // and use of Random will be generally faster. // /// Security // This Random Number Generator is NOT Cryptographically Strong and should NOT be used // for Security Purposes. /// Expects clauses // Functions may have expects clauses. // Such a clause defines a precondition of that function. The behavior of violating an Expects clause is undefined. typedef struct Random Random; /** * Creates a new, uninitialized Pseudo-random Number Generator according to the LCLib Random Specification. * The Random Instance, will be given a unique seed, as though by `Random_seed(rand)` the first time its used, if neither Random_seed nor Random_setSeed is called on it prior. * Random_new allocates the instance via a call to malloc. If malloc fails, Random_new returns NULL. * However, it may make additional allocations or initializations. * If these additional allocations or initializations fail, * any which are completed are deallocated and/or deinitialized in the reverse order, * then the instance is deallocated using free, and the call returns NULL. * The instance must be destroyed using Random_free. If the instance is freed in any other way, the behavior is undefined. * * The algorithms defined below are defined in terms of 3 fields for exposition only, a uint64_t field called seed, * a double field called nextNextGaussian, and a _Bool field called haveNextNextGaussian. * Implementations need not provide these fields. Consumers cannot access fields of this instance. * If an instance of type Random is examined or written to as an array of char or unsigned char, the behavior is undefined. */ Random* Random_new(); /** * Destroys the given instance of Random. * All allocations and initializations peformed by Random_new are reversed in the reverse order they were performed. * rand MUST be a valid random instance that was returned by Random_new() and has not been freed, or the behavior is undefined */ void Random_free(Random* rand); /** * Automatically initializes the instance of random with a seed that is almost guaranteed (with overwealming probability), * to be unique from any other invocation of this function. * * The algorithm which is used to perform this task is unspecified, but is guaranteed to be thread-safe. * * If neither this method nor Random_setSeed is called on an instance prior to any call to a generator function, * the instance is automatically initialized as though by this function. * After this call, haveNextNextGaussian shall be false. * Expects: rand shall have been returned by Random_new(), and must not have been freed. */ void Random_seed(Random* rand); /** * Initializes the generator to the state indicated by seed. * This function operates as though by setting seed to (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1) * If the library is compiled using TIGAME_MULTITHREAD_SUPPORT, the above operation shall be atomic. * Additionally, this function clears haveNextNextGaussian. * Expects: rand shall have been returned by Random_new(), and must not have been freed. */ void Random_setSeed(Random* rand,uint64_t seed); /** * An exposition only function which generates a random integer up to bits. * This function operates as though by updating seed to (seed * 0x5DEECE66DuLL + 0xBuLL) & ((1uLL << 48) - 1), * then returns (uint32_t)(seed >> (48 - bits)). * If the library is compiled using TIGAME_MULTITHREAD_SUPPORT, both operations shall be atomic, and the composite shall be atomic. * * An implementation shall not provide an accessible function called Random_next. * Expects: rand shall have been returned by Random_new(), and must not have been freed. This is shared by all Random_next*(rand) functions. */ /*uint32_t Random_next(Random* rand,int bits);*/ /** * Returns the result of (int32_t)(Random_next(rand,32)); */ int32_t Random_nextInt(Random* rand); /** * Generates a random integer in [0,bound), as though by the following algorithm: if ((bound & -bound) == bound) // i.e., bound is a power of 2 return (int32_t)((bound * (uint64_t)Random_next(rand,31)) >> 31); int32_t bits, val; do { bits = Random_next(31); val = bits % bound; } while (bits - val + (bound-1) < 0); return val; * Documentation copied and adapted from the Random#nextInt(int) function. * Expects: In addition to the general requirements for all Random_next* functions, bound MUST not be negative. * Api Note: The function accepts a signed bound, as the algorithm specified can only output positive signed values. * It made little sense to allow unsigned values greater than INT32_MAX. * The return type, as well as the bound to an extent, is also a legacy choice, as prior C++ implementations of java.util.Random returned signed int32_t. */ int32_t Random_nextIntb(Random* rand,int32_t bound); /** * Returns the result of (int64_t)(((uint64_t)Random_next(rand,32))<<32)|Random_next(rand,32)); * Note: as the generator deals with 48-bit seeds, this function will not generate all possible long values. */ int64_t Random_nextLong(Random* rand); /** * Generates a Random floating point number in [0,1). * Returns the result of ((float)Random_next(rand,24))/(1<<24). */ float Random_nextFloat(Random* rand); /** * Generates a Random double-precision floating point number in [0,1) * Returns the result of ((double)(((uint64_t)Random_next(rand,26))<<27)|Random_next(rand,27)))/1uLL<<53; */ double Random_nextDouble(Random* rand); /** * Generates a Random Gaussian distributed double value with mean 0 and standard distribution 1. * If the exposition-only flag haveNextNextGaussian is set, clears haveNextNextGaussian and returns nextNextGaussian. * Otherwise, generates two such double values as though by the following algorithm: double v1, v2, s; do { v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 s = v1 * v1 + v2 * v2; } while (s >= 1 || s == 0); double multiplier = sqrt(-2 * log(s)/s); rand->nextNextGaussian = v2 * multiplier; rand->haveNextNextGaussian = true; return v1 * multiplier; * Documentation copied and adapted from Random#nextGaussian() * */ double Random_nextGaussian(Random* rand); /** * Generates a random boolean value, with approximately equal probability of generating either true or false. * Returns the result of Random_next(rand,1)!=0 */ bool Random_nextBoolean(Random* rand); /** * Fills the output array with size random bytes, as though by the following algorithm: for (int i = 0; i < size; ) for (int rnd = Random_nextInt(rand), n = min(size - i, 4); n-- > 0; rnd >>= 8) ((char*)out)[i++] = (char)rnd; Where min(a,b) is an exposition only function-like macro which is defined as ((a)<(b)?(a):(b)) * Documentation copied and adapted from Random#nextBytes(byte[]) * Expects: out must point to an object, which */ void Random_nextBytes(Random* rand,void* out,size_t size); /** * Generates len random ints as though by Random_nextInt(rand), and stores them in [out,out+len). * The function is not constrained to write the output values in any particular order. * Expects: the range [out,out+len) must be a valid, continuous, and writeable range. */ void Random_ints(Random* rand,int* out,size_t len); /** * Generates len random double values as though by Random_nextDouble(rand), and stores them in [out,out+len) * The function is not constrained to write the output values in any particular order. * Expects: the range [out,out+len) must be a valid, continuous, and writeable range. */ void Random_doubles(Random* rand,double* out,size_t len); /** * Generates len random ints as though by Random_nextIntb(rand,max-min)+min, and stores them in [out,out+len). * The function is not constrained to write the output values in any particular order. * Expects: the range [out,out+len) must be a valid, continuous, and writeable range. */ void Random_intsb(Random* rand,int* out,size_t len,int min,int max); /** * Generates len random double values in [min,max) as though by Random_nextDouble(rand)*(max-min)+min, and stores them in [out,out+len) * The function is not constrained to write the output values in any particular order. * Expects: the range [out,out+len) must be a valid, continuous, and writeable range. */ void Random_doublesb(Random* rand,double* out,size_t len,double min,double max); Random* getThreadLocalRandom(); #ifdef __cplusplus }; #endif #endif /* INCLUDE_RANDOM_H_ */
44.148148
175
0.740247
[ "object" ]