hexsha stringlengths 40 40 | size int64 5 2.72M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 976 | max_stars_repo_name stringlengths 5 113 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:01:43 2022-03-31 23:59:48 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 00:06:24 2022-03-31 23:59:53 ⌀ | max_issues_repo_path stringlengths 3 976 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | 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 976 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:19 2022-03-31 23:59:49 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 12:00:57 2022-03-31 23:59:49 ⌀ | content stringlengths 5 2.72M | avg_line_length float64 1.38 573k | max_line_length int64 2 1.01M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
281186489d1bd90f49e66dd6fd3bb73d6c3c1706 | 2,581 | h | C | Spektrum.h | devangel77b/Spektrum | 2565d07fe8883036111bc6ada75db79bac393417 | [
"Apache-2.0"
] | null | null | null | Spektrum.h | devangel77b/Spektrum | 2565d07fe8883036111bc6ada75db79bac393417 | [
"Apache-2.0"
] | 2 | 2018-11-15T16:08:50.000Z | 2018-11-15T20:34:09.000Z | Spektrum.h | devangel77b/Spektrum | 2565d07fe8883036111bc6ada75db79bac393417 | [
"Apache-2.0"
] | null | null | null | /*
Spektrum.h
Spektrum serial receiver mbed library
Dennis Evangelista, 2018
*/
#ifndef SPEKTRUM_H
#define SPEKTRUM_H
#define SPEKTRUM_VERSION "1.0.1"
#include "mbed.h"
#include "rtos.h"
// bind modes
#define SPEKTRUM_INT_DSMX_22MS 7
#define SPEKTRUM_EXT_DSMX_22MS 8
#define SPEKTRUM_INT_DSMX_11MS 9
#define SPEKTRUM_EXT_DSMX_11MS 10
// DSM2 bind modes not recommended, not implemented
// EXT(ernal) bind modes don't really work on solitary satellite receiver
// field definitions
// #define SPEKTRUM_MASK_1024_CHANID 0xfc00
// #define SPEKTRUM_MASK_1024_SXPOS 0x03ff
// first two only used in DSM2 which are not implemented
#define SPEKTRUM_MASK_2048_CHANID 0x7800
#define SPEKTRUM_MASK_2048_CHANID_MSB 0x78
#define SPEKTRUM_MASK_2048_SXPOS 0x07ff
// allowable system field values
// #define SPEKTRUM_22MS_1024_DSM2 0x01
// #define SPEKTRUM_11MS_2048_DSM2 0x12
#define SPEKTRUM_22MS_2048_DSMX 0xa2
#define SPEKTRUM_11MS_2048_DSMX 0xb2
#define SPEKTRUM_BAUD 115200
// Spektrum baud is supposed to be 125000, but the LPC1768 seems not
// to support nonstandard baud rates.
#define SPEKTRUM_SERVOS 7
#define SPEKTRUM_PACKET_SIZE 16
#define SPEKTRUM_CHANNELS 16
#define SPEKTRUM_COUNT2US(x) (x*600/1024+900)
/** Spektrum receiver object for connecting to eg SPM9745 receiver
*/
class Spektrum{
public:
/** Number of fades (failed packets) from receiver */
unsigned int fades;
/** Tells if system is in DSMX 11ms or 22ms for example */
unsigned int system;
/** Contains 0-2048 values for all channels 0-15 */
unsigned int channel[SPEKTRUM_CHANNELS];
/** Contains approx 900-2100us pulsewidths corresponding to chan 0-15 */
unsigned int pulsewidth[SPEKTRUM_CHANNELS];
/** If true, data is value */
bool valid; // TODO switch to EventFlags?
/** 11 or 22 ms */
unsigned int period_ms;
Spektrum(PinName tx, PinName rx); // constructor
~Spektrum(); // destructor
private:
UARTSerial _rx;
unsigned char _buf[SPEKTRUM_PACKET_SIZE];
Thread _packet_thread;
void _packet_callback(void);
};
/** For binding a Spektrum receiver to transmitter */
class BindPlug{
public:
/** e.g. SPEKTRUM_INT_DSMX_11MS, SPEKTRUM_INT_DSMX_22MS */
int mode;
BindPlug(PinName tx, PinName rx, int mode = SPEKTRUM_INT_DSMX_11MS);
~BindPlug();
void bind();
private:
DigitalOut _3Vpin;
DigitalOut _datapin;
};
/* LATER
class SpektrumTestDevice{
public:
unsigned int fades;
unsigned int servo[7];
SpektrumTestDevice(PinName tx, PinName rx);
~SpektrumTestDevice();
private:
Serial _receiver;
};
*/
#endif
| 22.443478 | 74 | 0.752422 |
28121cca06659136658ddd31aa1e97b16758ba22 | 11,072 | h | C | dcerpc/ncklib/cnassm.h | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | 372 | 2016-10-28T10:50:35.000Z | 2022-03-18T19:54:37.000Z | dcerpc/ncklib/cnassm.h | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | 317 | 2016-11-02T17:41:48.000Z | 2021-11-08T20:28:19.000Z | dcerpc/ncklib/cnassm.h | kenferrara/pbis-open | 690c325d947b2bf6fb3032f9d660e41b94aea4be | [
"Apache-2.0"
] | 107 | 2016-11-03T19:25:16.000Z | 2022-03-20T21:15:22.000Z | /*
*
* (c) Copyright 1989 OPEN SOFTWARE FOUNDATION, INC.
* (c) Copyright 1989 HEWLETT-PACKARD COMPANY
* (c) Copyright 1989 DIGITAL EQUIPMENT CORPORATION
* To anyone who acknowledges that this file is provided "AS IS"
* without any express or implied warranty:
* permission to use, copy, modify, and distribute this
* file for any purpose is hereby granted without fee, provided that
* the above copyright notices and this notice appears in all source
* code copies, and that none of the names of Open Software
* Foundation, Inc., Hewlett-Packard Company, or Digital Equipment
* Corporation be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior
* permission. Neither Open Software Foundation, Inc., Hewlett-
* Packard Company, nor Digital Equipment Corporation makes any
* representations about the suitability of this software for any
* purpose.
*
*/
/*
*/
/*
**
** NAME
**
** cnassm.h
**
** FACILITY:
**
** Remote Procedure Call (RPC)
**
** ABSTRACT:
**
** Definitions of types/constants internal to the NCA Connection
** RPC Protocol Service association state machine.
**
**
*/
#ifndef _CNASSM_H
#define _CNASSM_H 1
/*
* The default fragment size all implementations of the NCA
* Connection protocol must be able to receive as defined in the NCA
* Architecture spec.
*/
#define RPC_C_ASSOC_MUST_RECV_FRAG_SIZE 1432
/***********************************************************************/
/*
* R P C _ C N _ A S S O C _ C H E C K _ S T
*
* This macro will check the given status. If not rpc_s_ok a local
* error event will be inserted into the association event list.
*/
#define RPC_CN_ASSOC_CHECK_ST(assoc, st)\
{\
rpc_cn_sm_event_entry_t _event;\
\
if (*(st) != rpc_s_ok)\
{\
(assoc)->assoc_local_status = *(st);\
_event.event_id = RPC_C_ASSOC_LOCAL_ERROR;\
RPC_CN_ASSOC_INSERT_EVENT ((assoc), &_event);\
return (*(st));\
}\
}
/***********************************************************************/
/*
* R P C _ C N _ A S S O C _ S M _ T R C
*/
#ifdef DEBUG
#define RPC_CN_ASSOC_SM_TRC(assoc, event_id)\
{\
if ((assoc)->assoc_flags & RPC_C_CN_ASSOC_CLIENT)\
{\
RPC_DBG_PRINTF (rpc_e_dbg_cn_state, RPC_C_CN_DBG_ASSOC_SM_TRACE, \
("STATE CLIENT ASSOC: %x state->%s event->%s\n",\
assoc,\
rpc_g_cn_assoc_client_states[(assoc)->assoc_state.cur_state-RPC_C_CN_STATEBASE],\
rpc_g_cn_assoc_client_events[event_id-RPC_C_CN_STATEBASE]));\
}\
else\
{\
RPC_DBG_PRINTF (rpc_e_dbg_cn_state, RPC_C_CN_DBG_ASSOC_SM_TRACE, \
("STATE SERVER ASSOC: %x state->%s event->%s\n",\
assoc,\
rpc_g_cn_assoc_server_states[(assoc)->assoc_state.cur_state-RPC_C_CN_STATEBASE],\
rpc_g_cn_assoc_server_events[event_id-RPC_C_CN_STATEBASE]));\
}\
}
#else
#define RPC_CN_ASSOC_SM_TRC(assoc, event_id)
#endif /* DEBUG */
/***********************************************************************/
/*
* R P C _ C N _ A S S O C _ S M _ T R C _ S T A T E
*/
#ifdef DEBUG
#define RPC_CN_ASSOC_SM_TRC_STATE(assoc)\
{\
if ((assoc)->assoc_flags & RPC_C_CN_ASSOC_CLIENT)\
{\
RPC_DBG_PRINTF (rpc_e_dbg_cn_state, RPC_C_CN_DBG_ASSOC_SM_TRACE, \
("STATE CLIENT ASSOC: %x new state->%s\n",\
assoc, \
rpc_g_cn_assoc_client_states[(assoc)->assoc_state.cur_state-RPC_C_CN_STATEBASE])); \
}\
else\
{\
RPC_DBG_PRINTF (rpc_e_dbg_cn_state, RPC_C_CN_DBG_ASSOC_SM_TRACE, \
("STATE SERVER ASSOC: %x new state->%s\n",\
assoc, \
rpc_g_cn_assoc_server_states[(assoc)->assoc_state.cur_state-RPC_C_CN_STATEBASE])); \
}\
}
#else
#define RPC_CN_ASSOC_SM_TRC_STATE(assoc)
#endif /* DEBUG */
/***********************************************************************/
/*
* R P C _ C N _ A S S O C _ E V A L _ N E T W O R K _ E V E N T
*
* This macro will be called by the network receiver thread when an
* association network event is detected. The "scanned" bit in
* the association is turned off. This bit is used in finding
* associations to reclaim. The fragbuf is freed if provided as an
* event parameter.
*/
#define RPC_CN_ASSOC_EVAL_NETWORK_EVENT(assoc, event_id, fragbuf, st)\
{\
RPC_CN_ASSOC_SM_TRC (assoc, event_id);\
st = rpc__cn_sm_eval_event ((event_id),\
(pointer_t) (fragbuf),\
(pointer_t) (assoc),\
&((assoc)->assoc_state));\
assoc->assoc_flags &= ~RPC_C_CN_ASSOC_SCANNED;\
if ((fragbuf) != NULL)\
{\
(*(fragbuf)->fragbuf_dealloc)((fragbuf));\
}\
RPC_CN_ASSOC_SM_TRC_STATE (assoc); \
}
/***********************************************************************/
/*
* R P C _ C N _ A S S O C _ E V A L _ U S E R _ E V E N T
*
* This macro will be called when user level events are detected. If
* the association status is bad then don't evaluate the user event.
* The "scanned" bit in the association is turned off.
*/
#define RPC_CN_ASSOC_EVAL_USER_EVENT(assoc, event_id, event_param, st)\
{\
RPC_CN_ASSOC_SM_TRC (assoc, event_id);\
st = assoc->assoc_status;\
if (st == rpc_s_ok)\
{\
st = rpc__cn_sm_eval_event ((event_id),\
(pointer_t) (event_param),\
(pointer_t) (assoc),\
&((assoc)->assoc_state));\
assoc->assoc_flags &= ~RPC_C_CN_ASSOC_SCANNED;\
}\
RPC_CN_ASSOC_SM_TRC_STATE (assoc); \
}
/***********************************************************************/
/*
* R P C _ C N _ A S S O C _ I N S E R T _ E V E N T
*
* This macro will be called when an event is generated inside an
* action routine of the association state machine.
*/
#define RPC_CN_ASSOC_INSERT_EVENT(assoc, event)\
{\
RPC_DBG_PRINTF (rpc_e_dbg_cn_state, RPC_C_CN_DBG_ASSOC_SM_TRACE, \
("STATE INSERT EVENT ")); \
RPC_CN_ASSOC_SM_TRC ((assoc), (event)->event_id);\
rpc__cn_sm_insert_event ((event),\
&((assoc)->assoc_state));\
}
/***********************************************************************/
/*
* A S S O C E V E N T S
*/
/*
* Events common to both client and server state machines and a
* comment as to who generated them: the user of the association
* services or the network.
*
* Note: local_error is not defined in the architecture. It is an
* event indicating a fatal error has occured while processing an
* event in the state machine.
*
* State values are incremented by 100 to distinguish them from
* action routine indexes which are all < 100. This was done as
* an efficiency measure to the engine, rpc__cn_sm_eval_event().
*/
#define RPC_C_ASSOC_ABORT_REQ 101 /* user */
#define RPC_C_ASSOC_NO_CONN_IND 104 /* network */
#define RPC_C_ASSOC_ALLOCATE_REQ 109 /* user */
#define RPC_C_ASSOC_DEALLOCATE_REQ 110 /* user */
#define RPC_C_ASSOC_LOCAL_ERROR 112 /* internal */
#define RPC_C_ASSOC_SHUTDOWN_REQ 111 /* user */
/*
* Events only applicable to client state machine
*
* Note: calls_done is 12 in the architecture. I'm
* making it 13 here so local_error will be 12 and therefore the same
* as the server local_error event.
*
* Note: shutdown_ind is 11 in the architecture. I'm
* making it 14 here so shutdown_req will be 11 and therefore the same
* as the server shutdown_req event.
*/
#define RPC_C_ASSOC_REQ 100 /* user */
#define RPC_C_ASSOC_REQUEST_CONN_ACK 102 /* network */
#define RPC_C_ASSOC_REQUEST_CONN_NACK 103 /* network */
#define RPC_C_ASSOC_ACCEPT_CONF 105 /* network */
#define RPC_C_ASSOC_REJECT_CONF 106 /* network */
#define RPC_C_ASSOC_ALTER_CONTEXT_REQ 107 /* user */
#define RPC_C_ASSOC_ALTER_CONTEXT_CONF 108 /* network */
#define RPC_C_ASSOC_CALLS_DONE 113 /* user */
#define RPC_C_ASSOC_SHUTDOWN_IND 114 /* network */
/*
* Events only applicable to server state machine
*/
/*
* Note: alter_context_resp is 4 in the architecture. I'm
* making it 5 here so no_conn_ind will be 4 and therefore the same
* as the client no_conn_ind event.
*
* Note: accept_resp is 1 in the architecture. I'm making
* it 13 here so abort_req will be 1 and therefore the same as the
* client abort_req event.
*/
#define RPC_C_ASSOC_IND 100 /* network */
#define RPC_C_ASSOC_REJECT_RESP 102 /* user */
#define RPC_C_ASSOC_ALTER_CONTEXT_IND 103 /* network */
#define RPC_C_ASSOC_ALTER_CONTEXT_RESP 105 /* user */
#define RPC_C_ASSOC_AUTH3_IND 106 /* network */
#define RPC_C_ASSOC_AUTH3_ACK 107 /* user */
#define RPC_C_ASSOC_AUTH3_NACK 108 /* user */
#define RPC_C_ASSOC_ACCEPT_RESP 113 /* user */
#define RPC_C_ASSOC_ASSOC_COMPLETE_RESP 114 /* user */
/***********************************************************************/
/*
* C L I E N T A S S O C S T A T E S
*/
#define RPC_C_CLIENT_ASSOC_CLOSED 100
#define RPC_C_CLIENT_ASSOC_CONNECT_WAIT 101
#define RPC_C_CLIENT_ASSOC_INIT_WAIT 102
#define RPC_C_CLIENT_ASSOC_OPEN 103
#define RPC_C_CLIENT_ASSOC_ACTIVE 104
#define RPC_C_CLIENT_ASSOC_CALL_DONE_WAIT 105
#define RPC_C_CLIENT_ASSOC_STATES 106
/***********************************************************************/
/*
* C L I E N T A S S O C T A B L E S
*/
EXTERNAL rpc_cn_sm_state_entry_p_t rpc_g_cn_client_assoc_sm [];
EXTERNAL rpc_cn_sm_action_fn_t rpc_g_cn_client_assoc_act_tbl [];
EXTERNAL char *rpc_g_cn_assoc_client_events [];
EXTERNAL char *rpc_g_cn_assoc_client_states [];
/***********************************************************************/
/*
* S E R V E R A S S O C S T A T E S
*/
#define RPC_C_SERVER_ASSOC_CLOSED 100
#define RPC_C_SERVER_ASSOC_REQUESTED 101
#define RPC_C_SERVER_ASSOC_AUTH3_WAIT 102
#define RPC_C_SERVER_ASSOC_AUTH3 103
#define RPC_C_SERVER_ASSOC_OPEN 104
#define RPC_C_SERVER_ASSOC_WAIT 105
#define RPC_C_SERVER_ASSOC_STATES 106
/***********************************************************************/
/*
* S E R V E R A S S O C T A B L E S
*/
EXTERNAL rpc_cn_sm_state_entry_p_t rpc_g_cn_server_assoc_sm [];
EXTERNAL rpc_cn_sm_action_fn_t rpc_g_cn_server_assoc_act_tbl [];
EXTERNAL char *rpc_g_cn_assoc_server_events [];
EXTERNAL char *rpc_g_cn_assoc_server_states [];
#endif /* _CNASSM_H */
| 35.261146 | 109 | 0.593569 |
2817dd6434b3226f99b2ad63fb01156a773e622b | 2,262 | h | C | drawingWorkshop/pitchDrawing/src/aubio/include/aubio/pitchyinfft.h | ofZach/VAW_workshop | 0a0adab37bfd9f5cfbdb3f5eaf4cb255e8997f4d | [
"MIT"
] | 19 | 2015-02-06T16:23:23.000Z | 2021-06-23T07:56:36.000Z | clientApp/src/aubio/include/aubio/pitchyinfft.h | HellicarAndLewis/DiaghilevMask | 73fdf6c1ac2ab5e7c7f6764d49d1f9cb6e87093e | [
"MIT"
] | 1 | 2017-02-11T17:28:03.000Z | 2017-02-11T17:28:03.000Z | clientApp/src/aubio/include/aubio/pitchyinfft.h | HellicarAndLewis/DiaghilevMask | 73fdf6c1ac2ab5e7c7f6764d49d1f9cb6e87093e | [
"MIT"
] | 5 | 2015-11-25T06:33:09.000Z | 2019-03-16T11:19:06.000Z | /*
Copyright (C) 2003 Paul Brossier
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/** \file
Pitch detection using a spectral implementation of the YIN algorithm
This algorithm was derived from the YIN algorithm (see pitchyin.c). In this
implementation, a Fourier transform is used to compute a tapered square
difference function, which allows spectral weighting. Because the difference
function is tapered, the selection of the period is simplified.
Paul Brossier, ``Automatic annotation of musical audio for interactive
systems'', Chapter 3, Pitch Analysis, PhD thesis, Centre for Digital music,
Queen Mary University of London, London, UK, 2006.
*/
#ifndef PITCHYINFFT_H
#define PITCHYINFFT_H
#ifdef __cplusplus
extern "C" {
#endif
/** pitch detection object */
typedef struct _aubio_pitchyinfft_t aubio_pitchyinfft_t;
/** execute pitch detection on an input buffer
\param p pitch detection object as returned by new_aubio_pitchyinfft
\param input input signal window (length as specified at creation time)
\param tol tolerance parameter for minima selection [default 0.85]
*/
smpl_t aubio_pitchyinfft_detect (aubio_pitchyinfft_t *p, fvec_t * input, smpl_t tol);
/** creation of the pitch detection object
\param bufsize size of the input buffer to analyse
*/
aubio_pitchyinfft_t * new_aubio_pitchyinfft (ba_uint_t bufsize);
/** deletion of the pitch detection object
\param p pitch detection object as returned by new_aubio_pitchyinfft()
*/
void del_aubio_pitchyinfft (aubio_pitchyinfft_t *p);
#ifdef __cplusplus
}
#endif
#endif /*PITCHYINFFT_H*/
| 32.314286 | 85 | 0.76481 |
28183530366217ff4677b4def0e003faa1699f8d | 292 | h | C | LearningRoad/LearningRoad/Custom/HLTabbarViewController/HLTabbarController.h | zhanghuilin37/HLLearningRoad | 170d3b0707c0038550ca29dc7ca997ff5f36822e | [
"MIT"
] | null | null | null | LearningRoad/LearningRoad/Custom/HLTabbarViewController/HLTabbarController.h | zhanghuilin37/HLLearningRoad | 170d3b0707c0038550ca29dc7ca997ff5f36822e | [
"MIT"
] | null | null | null | LearningRoad/LearningRoad/Custom/HLTabbarViewController/HLTabbarController.h | zhanghuilin37/HLLearningRoad | 170d3b0707c0038550ca29dc7ca997ff5f36822e | [
"MIT"
] | 1 | 2018-08-10T08:35:20.000Z | 2018-08-10T08:35:20.000Z | //
// HLTabbarController.h
// HLTabbarDemo
//
// Created by Zhl on 2017/3/3.
// Copyright © 2017年 LearningRoad. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "HLTabbar.h"
@interface HLTabbarController : UITabBarController
@property (nonatomic,strong) HLTabbar *hlTabBar;
@end
| 19.466667 | 56 | 0.729452 |
2818a20561d5760ea91d5f0b24e8c111d1d49994 | 11,149 | c | C | gg-utils.c | hkjn/greygoo | 89b1fb3af7a5ad3df21c289de61b76d21c77bd82 | [
"Apache-2.0"
] | 7 | 2015-10-22T23:48:26.000Z | 2022-03-15T05:00:51.000Z | gg-utils.c | hkjn/greygoo | 89b1fb3af7a5ad3df21c289de61b76d21c77bd82 | [
"Apache-2.0"
] | null | null | null | gg-utils.c | hkjn/greygoo | 89b1fb3af7a5ad3df21c289de61b76d21c77bd82 | [
"Apache-2.0"
] | 1 | 2016-09-07T18:40:57.000Z | 2016-09-07T18:40:57.000Z | /* Copyright 2011 Google Inc. 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.
*
* Author: Julien Tinnes
*
*/
#include <errno.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include "report.h"
#include "gg-utils.h"
/* OpenSSH-style x* functions
*
* Call FATAL() if any allocation or free fails.
*/
void *xmalloc(size_t size) {
void *pt;
if (size == 0) {
FATAL("xmalloc: size == 0");
}
pt = malloc(size);
if (pt == NULL) {
FATAL("xmalloc: failed to alloc");
}
return pt;
}
void xfree(void *ptr) {
if (ptr == NULL)
FATAL("xfree: ptr == NULL)");
free(ptr);
}
GG_ptr ggp_init(char *buf, size_t size) {
GG_ptr ret;
if (!buf || size > SIZE_MAX || buf + size < buf)
FATAL("ggp_init: potential memory corruption");
ret._start = buf;
ret._size = size;
ret.ptr = buf;
return ret;
}
/* check if a GG_ptr has obvious memory corruption issue.
* Terminate with FATAL if so
*/
static void assert_ggp_valid(const GG_ptr *ggp) {
/* 1. Obvious checks
* 2. Overflow check for (3)
* 3. Check that ptr is in the permitted range
*/
if (!ggp || !ggp->ptr || !ggp->_start || ggp->_size > SIZE_MAX ||
ggp->_start + ggp->_size < ggp->_start ||
ggp->_start > ggp->ptr || ggp->_start + ggp->_size < ggp->ptr)
FATAL("potential memory corruption");
}
/* Check if a GG_ptr can accomodate size in its current state
*
* Terminate with FATAL if not so
*/
void assert_ggp_size(const GG_ptr *ggp, size_t size) {
assert_ggp_valid(ggp);
if (size > SIZE_MAX || size > ggp->_size ||
ggp->ptr + size < ggp->ptr ||
ggp->_start > ggp->ptr + size ||
ggp->_start + ggp->_size < ggp->ptr + size)
FATAL("potential memory corruption");
}
/* consider this a pointer copy */
GG_ptr ggp_clone(const GG_ptr *ggp) {
GG_ptr ret;
assert_ggp_valid(ggp);
ret._start = ggp->_start;
ret._size = ggp->_size;
ret.ptr = ggp->ptr;
return ret;
}
/* add "offset" to a GG_ptr */
static void ggp_seek(GG_ptr *ggp, size_t offset) {
/* we don't add a assert_ggp_size there. The caller should be free to seek
* up to an invalid location, as long as the pointer is not
* used. (For instance parse_string).
*/
if (offset > SIZE_MAX)
FATAL("ggp_seek: potential memory correction");
ggp->ptr += offset;
}
/* use like read(), except ggp->ptr is the destination */
ssize_t ggp_read(int socket, const GG_ptr *ggp, size_t size) {
ssize_t ret;
assert_ggp_size(ggp, size);
if (size > SSIZE_MAX) {
FATAL("FATAL: ggp_read");
}
ret = read(socket, ggp->ptr, size);
return ret;
}
/* use like read(), except ggp->ptr is the destination */
ssize_t ggp_write(int socket, const GG_ptr *ggp, size_t size) {
ssize_t ret;
assert_ggp_size(ggp, size);
if (size > SSIZE_MAX) {
FATAL("FATAL: ggp_write");
}
ret = write(socket, ggp->ptr, size);
return ret;
}
ssize_t ggp_full_read(int socket, const GG_ptr *ggp, size_t size) {
size_t nread = 0;
ssize_t ret = 0;
GG_ptr buf;
buf = *ggp;
if (size > SSIZE_MAX)
return -1;
while (nread < size) {
ret = ggp_read(socket, &buf, size - nread);
if (ret <= 0)
return ret;
nread += ret;
buf.ptr += ret;
}
return nread;
}
ssize_t ggp_full_write(int socket, const GG_ptr *ggp, size_t size) {
size_t nread = 0;
ssize_t ret = 0;
GG_ptr buf;
buf = *ggp;
if (size > SSIZE_MAX)
return -1;
while (nread < size) {
ret = ggp_write(socket, &buf, size - nread);
if (ret <= 0)
return ret;
nread += ret;
buf.ptr += ret;
}
return nread;
}
/* fixed timing comparison return 0 if equal, something else otherwise */
int ggp_equal(const GG_ptr *s1, const GG_ptr *s2, size_t n) {
unsigned int i;
int ret;
char *v1;
char *v2;
assert_ggp_size(s1, n);
assert_ggp_size(s2, n);
v1 = (char *) s1->ptr;
v2 = (char *) s2->ptr;
for (i = 0, ret = 0; i < n; ++i) {
ret |= v1[i] ^ v2[i];
}
return ret;
}
int ggp_memcmp(const GG_ptr *ggpp, const void *s2, size_t n) {
assert_ggp_size(ggpp, n);
return memcmp(ggpp->ptr, s2, n);
}
void *ggp_memcpy(const GG_ptr *dest, const void *src, size_t n) {
assert_ggp_size(dest, n);
return memcpy(dest->ptr, src, n);
}
void gg_bzero(const GG_ptr *s, size_t n) {
assert_ggp_size(s, n);
bzero(s->ptr, n);
}
uint32_t ggp_get_uint32(const GG_ptr *ggpp) {
assert_ggp_size(ggpp, sizeof(uint32_t));
return ntohl(*((uint32_t *) ggpp->ptr));
}
uint16_t ggp_get_uint16(const GG_ptr *ggpp) {
assert_ggp_size(ggpp, sizeof(uint16_t));
return ntohs(*((uint16_t *) ggpp->ptr));
}
void ggp_put_uint32(const GG_ptr *ggpp, uint32_t num) {
assert_ggp_size(ggpp, sizeof(uint32_t));
*((uint32_t *) ggpp->ptr) = htonl(num);
}
void ggp_put_uint16(const GG_ptr *ggpp, uint16_t num) {
assert_ggp_size(ggpp, sizeof(uint16_t));
*((uint16_t *) ggpp->ptr) = htons(num);
}
/* helpers for parsing / encoding stuff */
/* read a 32 bits integer in network order
* and increase the pointer
*/
uint32_t parse_uint32(GG_ptr *ggpp) {
uint32_t ret;
ret = ggp_get_uint32(ggpp);
ggp_seek(ggpp, sizeof(uint32_t));
return ret;
}
uint16_t parse_uint16(GG_ptr *ggpp) {
uint16_t ret;
ret = ggp_get_uint16(ggpp);
ggp_seek(ggpp, sizeof(uint16_t));
return ret;
}
ssize_t parse_string(GG_ptr *ggpp, size_t maxlen) {
size_t ret;
char *cp = ggpp->ptr;
if (maxlen < 1 || maxlen > SSIZE_MAX)
return -1;
assert_ggp_size(ggpp, maxlen);
for (ret = 0; ret < maxlen; cp++, ret++)
if (*cp == 0) {
ggp_seek(ggpp, ret + 1);
return (ret + 1);
}
return -1;
}
/* maxlen: max size of the buffer */
ssize_t encode_string(GG_ptr *ggpp, char *string, size_t maxlen) {
size_t len;
/* we need to account for the NUL byte */
if (maxlen <= 1 || (len = strlen(string)) > maxlen - 1 ||
len > SSIZE_MAX - 1)
return -1;
assert_ggp_size(ggpp, maxlen);
/* account for the NUL byte */
len++;
ggp_memcpy(ggpp, string, len);
ggp_seek(ggpp, len);
return len;
}
ssize_t encode_uint32(GG_ptr *ggpp, uint32_t num) {
ggp_put_uint32(ggpp, num);
ggp_seek(ggpp, sizeof(uint32_t));
return sizeof(uint32_t);
}
ssize_t encode_uint16(GG_ptr *ggpp, uint16_t num) {
ggp_put_uint16(ggpp, num);
ggp_seek(ggpp, sizeof(uint16_t));
return sizeof(uint16_t);
}
/* returns 0 on success */
static int write_to_oom_adj_file(const char *oom_adj_file,
const char *oom_score) {
FILE *oom_adj = NULL;
size_t n;
int ret = -1;
if (!oom_adj_file || !oom_score)
goto out;
oom_adj = fopen(oom_adj_file, "a+");
if (!oom_adj)
goto out;
n = fwrite(oom_score, strlen(oom_score), 1, oom_adj);
if (n != 1)
goto out;
/* all good */
ret = 0;
out:
if (oom_adj && fclose(oom_adj))
ret = -1;
return ret;
}
/* Convert old style /proc/pid/oom_adj to new style /proc/pid/oom_score_adj
* values.
*/
int oom_adj_to_oom_score_adj(int oom_adj) {
const int kOOM_ADJUST_MAX = 15; /* include/linux/oom.h */
const int kOOM_SCORE_ADJ_MAX = 1000;
const int kOOM_DISABLE = -17;
int oom_score_adj;
if (oom_adj < kOOM_DISABLE || oom_adj > kOOM_ADJUST_MAX)
FATAL("invalid OOM score");
/* We convert between the two by using the linear formula that newer kernels
* use for backward compatibility (fs/proc/base.c).
*/
if (oom_adj == kOOM_ADJUST_MAX) {
oom_score_adj = kOOM_SCORE_ADJ_MAX;
} else {
oom_score_adj = (oom_adj * kOOM_SCORE_ADJ_MAX) / -kOOM_DISABLE;
}
return oom_score_adj;
}
/* The kernel can use new style (oom_score_adj) or old style (oom_adj). We try
* both.
*/
int adjust_oom_score(int oom_adj) {
char score_string[16];
int oom_score_adj; /* new style score */
int ret;
oom_score_adj = oom_adj_to_oom_score_adj(oom_adj);
/* First we try new-style OOM adjustment */
ret = snprintf(score_string, sizeof(score_string), "%d", oom_score_adj);
if (ret < 0 || (unsigned) ret >= sizeof(score_string))
FATAL("snprintf");
if (write_to_oom_adj_file("/proc/self/oom_score_adj", score_string) == 0)
return 0;
/* Then we try old-style OOM adjustment */
ret = snprintf(score_string, sizeof(score_string), "%d", oom_adj);
if (ret < 0 || (unsigned) ret >= sizeof(score_string))
FATAL("snprintf");
if (write_to_oom_adj_file("/proc/self/oom_adj", score_string) == 0)
return 0;
else
return -1;
}
int become_bullet_proof(int prio) {
const int kOOM_DISABLE = -17;
int ret = 0;
/* commit all the pages we might need to memory. We don't use MCL_FUTURE
* since that could cause things to fail. Also this is not inherited on
* fork(), which is what we want.
* Most pages of the virtual address space should be shared anyway, so
* workers will have their code commited to memory.
*/
if (mlockall(MCL_CURRENT)) {
DEBUG(1, "Could not lock all memory(): %m\n");
ret = -1;
}
/* Give complete immunity. Inherited on fork(). */
if (adjust_oom_score(kOOM_DISABLE)) {
DEBUG(1, "Could not get OOM immunity\n");
ret = -1;
}
/* Set priority for the current process group. Inherited on fork() */
if (setpriority(PRIO_PGRP, 0, prio)) {
DEBUG(1, "Could not set priority: %d\n", prio);
ret = -1;
}
return ret;
}
int protect_address_space(void) {
int ret = 0;
const struct rlimit rl = {RLIM_INFINITY, RLIM_INFINITY};
/* Get unlimited locked memory space if we can */
if (setrlimit(RLIMIT_MEMLOCK, &rl)) ret = -1;
/* no core dumps */
if (prctl(PR_SET_DUMPABLE, 0, -1, -1, -1)) ret = -1;
/* No swap */
if (mlockall(MCL_CURRENT | MCL_FUTURE)) ret = -1;
return ret;
}
/* FIXME: fixup for OLD libc that don't support ppoll */
/* we know the system call number for Linux i386 */
#if (!SYS_ppoll && __WORDSIZE == 32 && i386 && linux)
#define SYS_ppoll 309
#endif
/*
* ppoll is only supported since glibc 2.4 (~2006)
* The system call is present since Linux 2.6.16
* We accomodate old libcs
*/
int old_libc_compatible_ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask) {
struct timespec ts;
int ret;
/* Point timeout to a modifiable copy (glibc guarantees timeout won't be
* modified)
*/
if (timeout) {
ts = *timeout;
timeout = &ts;
}
ret = syscall(SYS_ppoll, fds, nfds, timeout, sigmask, _NSIG / 8);
if ((ret == -1) && (errno == ENOSYS))
FATAL("This system does not support ppoll\n");
return ret;
}
| 24.396061 | 78 | 0.650731 |
281d5ec7b614dbcf5cf1c7ab360cf505eeec5e20 | 1,343 | h | C | src/common/media/image.h | Tatrabbit/trance | 9f0a9c21a079da2e376857138591593a9cff5a21 | [
"WTFPL"
] | 37 | 2015-02-19T02:36:26.000Z | 2021-10-05T22:06:17.000Z | src/common/media/image.h | Tatrabbit/trance | 9f0a9c21a079da2e376857138591593a9cff5a21 | [
"WTFPL"
] | 21 | 2015-07-14T13:07:14.000Z | 2019-10-17T15:30:32.000Z | src/common/media/image.h | Tatrabbit/trance | 9f0a9c21a079da2e376857138591593a9cff5a21 | [
"WTFPL"
] | 20 | 2016-08-18T11:11:47.000Z | 2022-03-05T20:58:00.000Z | #ifndef TRANCE_SRC_COMMON_MEDIA_IMAGE_H
#define TRANCE_SRC_COMMON_MEDIA_IMAGE_H
#include <memory>
#include <mutex>
#include <vector>
namespace sf
{
class Image;
}
struct vpx_image;
// In-memory image with load-on-request OpenGL texture which is ref-counted
// and automatically unloaded once no longer used.
class Image
{
public:
Image();
Image(uint32_t width, uint32_t height, unsigned char* data);
Image(const sf::Image& image);
explicit operator bool() const;
uint32_t width() const;
uint32_t height() const;
uint32_t texture() const;
// Call from OpenGL context thread only!
bool ensure_texture_uploaded() const;
const std::shared_ptr<sf::Image>& get_sf_image() const;
void clear_sf_image() const;
static void delete_textures();
private:
// In order to ensure textures are deleted from the rendering thread, we
// use a separate set.
static std::vector<uint32_t> textures_to_delete;
static std::mutex textures_to_delete_mutex;
struct texture_deleter {
texture_deleter(uint32_t texture) : texture{texture}
{
}
~texture_deleter();
uint32_t texture;
};
uint32_t _width;
uint32_t _height;
mutable uint32_t _texture;
mutable std::shared_ptr<sf::Image> _sf_image;
mutable std::shared_ptr<texture_deleter> _deleter;
};
Image load_image(const std::string& path);
#endif | 23.561404 | 75 | 0.741623 |
281de038520736b26f3061fcce88c170e4036097 | 4,875 | h | C | code/include/atk_audio.h | Gentil-N/arcade-toolkit | 6a6a6d11d01e501cd09a53be0ca575068521976c | [
"MIT"
] | null | null | null | code/include/atk_audio.h | Gentil-N/arcade-toolkit | 6a6a6d11d01e501cd09a53be0ca575068521976c | [
"MIT"
] | null | null | null | code/include/atk_audio.h | Gentil-N/arcade-toolkit | 6a6a6d11d01e501cd09a53be0ca575068521976c | [
"MIT"
] | null | null | null | #ifndef __AUDIO_H__
#define __AUDIO_H__
#ifndef __ATK_H__
#include "atk_core.h"
#endif //__ATK_H__
#ifdef __cplusplus
extern "C"
{
#endif //__cplusplus
ATK_API bool adiInit();
ATK_API void adiEnd();
typedef enum AdiAttenuationType
{
ADI_ATT_TYPE_LINEAR = 0xD003,
ADI_ATT_TYPE_INVERSE = 0xD001,
ADI_ATT_TYPE_EXPONENT = 0xD005
} AdiAttenuationType;
ATK_API void adiSetAttenuation(AdiAttenuationType attenuation_type);
typedef struct AdiSoundData AdiSoundData;
typedef struct AdiSoundDataSettings
{
const char *name;
} AdiSoundDataSettings;
ATK_API bool adiLoadSoundData(AdiSoundData *sound_data, const AdiSoundDataSettings *settings);
ATK_API void adiFreeSoundData(AdiSoundData *sound_data);
typedef struct AdiSource AdiSource;
ATK_API void adiCreateSource(AdiSource *source);
ATK_API void adiDestroySource(AdiSource *source);
ATK_API void adiSourceBindSoundData(AdiSource *source, const AdiSoundData *sound_data);
ATK_API void adiSourcePlay(AdiSource *source);
ATK_API void adiSourcePause(AdiSource *source);
ATK_API void adiSourceStop(AdiSource *source);
ATK_API bool adiSourceIsPlaying(AdiSource *source);
ATK_API void adiSourceEnableLooping(AdiSource *source);
ATK_API void adiSourceDisableLooping(AdiSource *source);
ATK_API void adiSourceSetPosition(AdiSource *source, float x, float y, float z);
ATK_API void adiSourceSetVelocity(AdiSource *source, float x, float y, float z);
ATK_API void adiListenerSetPosition(float x, float y, float z);
ATK_API void adiListenerSetOrientation(float at_x, float at_y, float at_z, float up_x, float up_y, float up_z);
ATK_API void adiListenerSetVelocity(float x, float y, float z);
#ifdef __cplusplus
}
#endif //__cplusplus
struct AdiSoundData
{
uint32_t m_buffer;
#ifdef __cplusplus
AdiSoundData() : m_buffer(0)
{
}
AdiSoundData(const AdiSoundDataSettings &settings) : m_buffer(0)
{
adiLoadSoundData(this, &settings);
}
AdiSoundData(const AdiSoundData &sound_data) = delete; //to avoid destroy errors
AdiSoundData(AdiSoundData &&sound_data)
{
m_buffer = sound_data.m_buffer;
sound_data.m_buffer = 0;
}
~AdiSoundData()
{
if (m_buffer == 0)
{
return;
}
adiFreeSoundData(this);
}
AdiSoundData &operator=(const AdiSoundData &sound_data) = delete;
AdiSoundData &operator=(AdiSoundData &&sound_data)
{
m_buffer = sound_data.m_buffer;
sound_data.m_buffer = 0;
return *this;
}
void load(const AdiSoundDataSettings &settings)
{
adiLoadSoundData(this, &settings);
}
void free()
{
adiFreeSoundData(this);
m_buffer = 0;
}
#endif //___cplusplus
};
struct AdiSource
{
uint32_t m_id;
#ifdef __cplusplus
AdiSource() : m_id(0) //create must be called
{
}
AdiSource(const AdiSource &source) = delete; //to avoid destroy errors
AdiSource(AdiSource &&source)
{
m_id = source.m_id;
source.m_id = 0;
}
~AdiSource()
{
if(m_id == 0)
{
return;
}
adiDestroySource(this);
}
AdiSource &operator=(const AdiSource &source) = delete;
AdiSource &operator=(AdiSource &&source)
{
m_id = source.m_id;
source.m_id = 0;
return *this;
}
void create()
{
adiCreateSource(this);
}
void destroy()
{
adiDestroySource(this);
}
void bindSource(AdiSoundData &sound_data)
{
adiSourceBindSoundData(this, &sound_data);
}
void play()
{
adiSourcePlay(this);
}
void pause()
{
adiSourcePause(this);
}
void stop()
{
adiSourceStop(this);
}
bool isPlaying()
{
return adiSourceIsPlaying(this);
}
void enableLooping()
{
adiSourceEnableLooping(this);
}
void disableLooping()
{
adiSourceDisableLooping(this);
}
void setPosition(float x, float y, float z)
{
adiSourceSetPosition(this, x, y, z);
}
void setVelocity(float x, float y, float z)
{
adiSourceSetVelocity(this, x, y, z);
}
#endif //___cplusplus
};
#endif //__AUDIO_H__ | 27.698864 | 118 | 0.577436 |
281e23ceb8fab6cabbde1b17c6c2962f8045a6db | 433 | h | C | ProgrammableCalculator/Expressions/AssignmentExpression.h | gmenchetti/Object_Oriented_Class_Projects | fee02e4247b1ef8a44e8d5b0cc6febbd18611e8d | [
"MIT"
] | 3 | 2019-11-19T20:47:31.000Z | 2019-12-05T04:25:28.000Z | ProgrammableCalculator/Expressions/AssignmentExpression.h | gmenchetti/Object_Oriented_Class_Projects | fee02e4247b1ef8a44e8d5b0cc6febbd18611e8d | [
"MIT"
] | null | null | null | ProgrammableCalculator/Expressions/AssignmentExpression.h | gmenchetti/Object_Oriented_Class_Projects | fee02e4247b1ef8a44e8d5b0cc6febbd18611e8d | [
"MIT"
] | null | null | null | //
// Created by Guglielmo Menchetti on 27/11/2018.
//
#ifndef HW5_ASSIGNMENTEXPRESSION_H
#define HW5_ASSIGNMENTEXPRESSION_H
#include "Expression.h"
class AssignmentExpression : Expression {
public:
AssignmentExpression(RegisterCounter& rc, std::string& rec, double val);
void execute();
std::string getInstructionText();
private:
std::string receiver;
double value;
};
#endif //HW5_ASSIGNMENTEXPRESSION_H
| 18.041667 | 76 | 0.743649 |
2820577352b98feac8ad17afbc0bf1dac4cbb6d5 | 1,170 | c | C | lib/sndkit/dsp/sparse.c | PaulBatchelor/mnolth | 4b9f315f0062212ef96b41153e089dea61c6d16d | [
"MIT"
] | 2 | 2022-01-11T07:00:40.000Z | 2022-01-11T07:00:43.000Z | lib/sndkit/dsp/sparse.c | PaulBatchelor/mnolth | 4b9f315f0062212ef96b41153e089dea61c6d16d | [
"MIT"
] | null | null | null | lib/sndkit/dsp/sparse.c | PaulBatchelor/mnolth | 4b9f315f0062212ef96b41153e089dea61c6d16d | [
"MIT"
] | null | null | null | #line 45 "sparse.org"
#define SK_SPARSE_PRIV
#include "sparse.h"
#line 152 "sparse.org"
static SKFLT randval(sk_sparse *sp);
#line 45 "sparse.org"
#line 75 "sparse.org"
void sk_sparse_init(sk_sparse *sp, int sr, unsigned long seed)
{
sp->sr = sr;
#line 97 "sparse.org"
sk_sparse_freq(sp, 30); /* arbitrary positive value */
sp->pfreq = -1;
#line 126 "sparse.org"
sp->thresh = 0;
#line 140 "sparse.org"
sp->rng = seed;
#line 79 "sparse.org"
}
#line 108 "sparse.org"
void sk_sparse_freq(sk_sparse *sp, SKFLT freq)
{
sp->freq = freq;
}
#line 157 "sparse.org"
static SKFLT randval(sk_sparse *sp)
{
sp->rng = (1103515245L * sp->rng + 12345L);
sp->rng %= 2147483648L;
return (SKFLT)sp->rng / 2147483648L;
}
#line 175 "sparse.org"
SKFLT sk_sparse_tick(sk_sparse *sp)
{
SKFLT out;
SKFLT r;
out = 0;
#line 200 "sparse.org"
if (sp->freq != sp->pfreq) {
sp->pfreq = sp->freq;
sp->thresh = sp->freq / (SKFLT)sp->sr;
}
#line 175 "sparse.org"
#line 212 "sparse.org"
r = randval(sp);
#line 175 "sparse.org"
#line 217 "sparse.org"
if (r < sp->thresh) out = (2 * randval(sp)) - 1;
#line 184 "sparse.org"
return out;
}
#line 45 "sparse.org"
| 20.892857 | 62 | 0.647009 |
282335fbd69235c5f44dc6ac92b2e8898481836d | 7,559 | h | C | cpp/apps/OrbitalWar/SpaceCraft.h | Aki78/FlightAI | 9c5480f2392c9c89b9fee4902db0c4cde5323a6c | [
"MIT"
] | 1 | 2019-02-15T08:31:59.000Z | 2019-02-15T08:31:59.000Z | cpp/apps/OrbitalWar/SpaceCraft.h | Aki78/FlightAI | 9c5480f2392c9c89b9fee4902db0c4cde5323a6c | [
"MIT"
] | null | null | null | cpp/apps/OrbitalWar/SpaceCraft.h | Aki78/FlightAI | 9c5480f2392c9c89b9fee4902db0c4cde5323a6c | [
"MIT"
] | null | null | null |
#ifndef SpaceCraft_h
#define SpaceCraft_h
#include <vector>
#include "Vec2.h"
#include "Vec3.h"
#include "Mat3.h"
#include "quaternion.h"
#include "geom3D.h"
namespace SpaceCrafting{
const int NAME_LEN = 16;
class BodyPose{ public:
Vec3d pos;
Mat3d rot;
//Quat4d rot;
};
/*
//class BBox : public BodyPose{ public:
class BBox : public BodyPose{ public:
//int type; // elipsoide, box, ... ?
Vec3d pmin;
Vec3d pmax;
};
*/
// ==== Materials
class CatalogItem{ public:
int id;
int kind;
char name[NAME_LEN] = "\n";
};
class Material : public CatalogItem { public:
double density; // [kg/m3]
double Spull,Spush; // [Pa] Strenght
double Kpull,Kpush; // [Pa] elastic modulus
double reflectivity; // [1] reflectivity
double Tmelt; // [T] temperature of failure
// What about heat, electricity etc. ?
};
class Commodity : public CatalogItem { public:
double density; // [kg/m3]
// What about heat, electricity etc. ?
};
class FuelType : public Commodity { public:
double EnergyDesity; // [J/kg]
};
// ==== Components
class Node{ public:
Vec3d pos;
std::vector<Vec2i> components; // {kind,index}
Node(Vec3d pos):pos(pos){};
};
class ShipComponent{ public:
int id;
int kind;
int shape;
//int p0; // anchor node
// char name[NAME_LEN];
double mass; // [kg]
//RigidBody pose;
};
class Modul: public ShipComponent { public:
BodyPose pose;
Box bbox;
Vec3d span;
double volume;
void pick(const Vec3d& ro, const Vec3d& rd){
}
};
class Tank : public Modul { public:
Commodity * typ;
//double radius;
//double length;
// [m^3]
double filled; // [1]
};
class Balloon : public Modul { public:
};
class Rock : public Modul { public:
};
//class GirderType : public CatalogItem { public:
// int mseg;
// Vec3d wh;
//};
class NodeLinker : public ShipComponent { public:
int p0,p1;
double length;
};
class Girder : public NodeLinker { public:
//int p1; // anchor node; p0 inherate
//double length;
int nseg;
int mseg;
Vec2d wh; // [m] width and height
Vec3d up;
//double SPull,SPush;
//double kPull,kPush;
Material * material;
Vec2i poitRange; // index of start and end in Truss
Vec2i stickRange; // --,,---
//GirderType * type = NULL;
};
//class Ring : public NodeLinker { public:
class Ring : public ShipComponent { public:
//int p1; // anchor node; p0 inherate
//double length;
BodyPose pose;
int nseg;
double R;
Vec2d wh;
Material * material;
Vec2i poitRange; // index of start and end in Truss
Vec2i stickRange; // --,,---
//GirderType * type = NULL;
};
class Rope : public NodeLinker { public:
double thick;
Material * material;
};
class Pipe : public ShipComponent { public:
double maxFlow; // units depend on commodity
ShipComponent * a;
ShipComponent * b;
};
//class Hub : public ShipComponent { public:
// int npipes; // number of pipes going to hub;
// Pipe * pipes; //
//}
// ==== Motors
class Plate : public ShipComponent { public:
double area;
int g1,g2; // anchor girders
Vec2f g1span; // pos along girdes
Vec2f g2span;
//Vec3d normal;
//int ntris;
//int * tris; // triangles from points of spaceship
};
class Radiator : public Plate{ public:
double temperature;
};
class Shield : public Plate{ public:
};
class Collector : public Plate{ public:
};
// ==== Motors
class ThrusterType : public CatalogItem { public:
double efficiency; // how much power is used for acceleration of propelant
double veMin; // minimal exhaust velocity [m/s]
double veMax; // maximal exhaust velocity [m/s]
bool exhaustFuel; // if true the burned fuel is added to propellant mass
FuelType * fuel = NULL;
Commodity * Propelant = NULL;
};
class Thruster : public Modul { public:
ThrusterType * typ = NULL;
double thrust;
double power;
double consumption;
};
class Rotor : public ShipComponent { public:
// Move ship componenets with respect to each other in inner manuevers
double Radius;
double power; // [kg.m^2]
double torque; // [kg.m^2]
double Inertia; // [kg.m^2] moment of inertia
};
class Slider : public ShipComponent { public:
// allow slide a note over a girder
int girder;
double power; // [kg.m^2]
double Force;
};
// === Guns
class GunType : public CatalogItem { public:
double recoil;
// scaling laws - how performace (power, accuracy, penetration, time of flight ...) scales with size ?
};
// Also Accelerator?
class Accelerator : public ShipComponent{ public:
// TODO: can be also attached to Ring ?
// This can be perhaps determined from type
int suppType; // ring or girder
int suppId; // anchor girders
Vec2f suppSpan; // pos along girdes
double lenght; // [m]
double PowerPeak; // [W]
double PulseEnergy; // [J]
double PulseDuration; // [s]
double PulsePerios; // [s]
//std::vector<int> anchors; // anchor points
};
class Gun : public Accelerator{ public:
GunType * typ = NULL;
double Aperture; // [m^2]
double divergence; // [1] tangens of angle
// attached to girder?
// incorporated in girder?
};
// === SpaceShip
class SpaceCraft : public CatalogItem { public:
std::vector<int> LODs;
Truss truss;
std::vector<Node> nodes;
std::vector<Rope> ropes;
std::vector<Girder> girders;
std::vector<Ring> rings;
std::vector<Thruster> thrusters;
std::vector<Gun> guns;
std::vector<Radiator> radiators;
std::vector<Shield> shields;
std::vector<Tank> tanks;
std::vector<Pipe> pipes;
std::vector<Balloon> balloons;
std::vector<Rock> rocks;
// Truss * coarse = NULL;
// Truss * fine = NULL;
void clear(){
nodes.clear(); ropes.clear(); girders.clear(); rings.clear(); thrusters.clear(); guns.clear(); radiators.clear(); shields.clear(); tanks.clear(); pipes.clear();
rocks.clear(); balloons.clear();
truss.clear();
};
void pick(Vec3d ro, Vec3d rd){
}
void toTruss(Truss& truss){
int i=0;
truss.newBlock();
int ip0 = truss.points.size();
for(Node o: nodes){
truss.points.push_back( o.pos );
}
for(Rope o: ropes){
truss.edges.push_back( (TrussEdge){o.p0,o.p1,0} );
}
for(Girder o: girders){
//printf("DEBUG toTruss : girder #%i \n", i);
truss.girder1( nodes[o.p0].pos, nodes[o.p1].pos, o.up, o.nseg, o.wh.a );
truss.girder1_caps( o.p0, o.p1, 1 );
Vec2i& bak = truss.blocks.back();
o.poitRange = {bak.x,truss.points.size()};
o.stickRange = {bak.y,truss.edges .size()};
i++;
}
i=0;
for(Ring o: rings){
printf("DEBUG toTruss : ring #%i %f %f \n", i, o.nseg, o.wh.a );
truss.wheel( o.pose.pos, o.pose.pos+o.pose.rot.b*o.R, o.pose.rot.c, o.nseg, o.wh.a );
Vec2i& bak = truss.blocks.back();
o.poitRange = {bak.x,truss.points.size()};
o.stickRange = {bak.y,truss.edges .size()};
i++;
}
printf( "npoint %i nstick %i nblocks %i \n", truss.points.size(), truss.edges.size(), truss.blocks.size() );
}
void toTruss(){ truss.clear(); toTruss(truss); };
};
} // namespace SpaceCrafting
#endif
| 23.258462 | 168 | 0.60127 |
282839e8c9918e05c2294fa81f926ceffaa34b65 | 1,350 | h | C | src/Lethe/Core/Sys/Assert.h | killvxk/lethe | c1a9bb45063f5148dc6cf681ce907dcbb468f5e6 | [
"BSL-1.0"
] | 9 | 2020-03-08T14:54:49.000Z | 2021-12-22T22:52:04.000Z | src/Lethe/Core/Sys/Assert.h | kmar/lethe | 78259f56e7eb887dcd470bd7d988df0b153bca43 | [
"BSL-1.0"
] | null | null | null | src/Lethe/Core/Sys/Assert.h | kmar/lethe | 78259f56e7eb887dcd470bd7d988df0b153bca43 | [
"BSL-1.0"
] | 3 | 2020-03-09T08:24:40.000Z | 2020-03-09T14:04:23.000Z | #pragma once
#include "../Common.h"
#include "Likely.h"
#if LETHE_DEBUG
# include <cassert>
#endif
// compile-time assert
#define LETHE_COMPILE_ASSERT(cond) do { struct CompileTimeAssert { char arr[(cond) ? 1 : -1]; } tmp_; tmp_.arr[0]=0;(void)tmp_; } while(false)
// runtime assert (even in release)
#define LETHE_RUNTIME_ASSERT(cond) do { \
if (LETHE_UNLIKELY(!(cond))) { \
lethe::AbortProgramAssert(#cond, __FILE__, __LINE__); \
} \
} while(false)
// assert/verify
#if !LETHE_DEBUG
# define LETHE_ASSERT(cond) do {} while(false)
# define LETHE_VERIFY(cond) ((void)(cond))
#else
# define LETHE_ASSERT(cond) assert(cond)
# define LETHE_VERIFY(cond) assert(cond)
#endif
#if !defined(assert)
# define assert LETHE_ASSERT
#endif
#define LETHE_ASSERT_ALWAYS(msg) LETHE_ASSERT(false && #msg)
#define LETHE_NOT_IMPLEMENTED(func) LETHE_ASSERT(false && "Not implemented: " #func)
namespace lethe
{
// trap into debugger (where available)
void LETHE_API DebugerTrap();
// aborts program
void LETHE_API AbortProgram(const char *msg = nullptr, int exitCode = 1);
void LETHE_API AbortProgramAssert(const char *msg, const char *file, int line, int exitCode = 1);
// abort assert( aborts program)
inline void AbortAssert(bool cond, const char *desc = nullptr, int exitCode = 1)
{
if (LETHE_UNLIKELY(!cond))
AbortProgram(desc, exitCode);
}
}
| 25.961538 | 142 | 0.724444 |
2829a039a0547f9eb5742b0df77e382d03bfb95d | 217 | h | C | Afterburner/Afterburner/ViewController.h | lele0108/afterburner | 2baf84b955c28af4c76a4da5d336a927a718e5f0 | [
"MIT"
] | null | null | null | Afterburner/Afterburner/ViewController.h | lele0108/afterburner | 2baf84b955c28af4c76a4da5d336a927a718e5f0 | [
"MIT"
] | null | null | null | Afterburner/Afterburner/ViewController.h | lele0108/afterburner | 2baf84b955c28af4c76a4da5d336a927a718e5f0 | [
"MIT"
] | null | null | null | //
// ViewController.h
// Afterburner
//
// Created by Jimmy Liu on 12/29/14.
// Copyright (c) 2014 jimmyliu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
| 13.5625 | 53 | 0.686636 |
282a730ee7e42700c9e0828239530088ec62715d | 1,910 | h | C | libpandabase/utils/type_helpers.h | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | 1 | 2021-09-09T03:17:23.000Z | 2021-09-09T03:17:23.000Z | libpandabase/utils/type_helpers.h | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | null | null | null | libpandabase/utils/type_helpers.h | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:21:57.000Z | 2021-09-13T11:21:57.000Z | /*
* Copyright (c) 2021 Huawei Device 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 PANDA_LIBPANDABASE_UTILS_TYPE_HELPERS_H_
#define PANDA_LIBPANDABASE_UTILS_TYPE_HELPERS_H_
namespace panda::helpers {
template <class T>
constexpr auto ToSigned(T v)
{
using signed_type = std::make_signed_t<T>;
return static_cast<signed_type>(v);
}
template <class T>
constexpr auto ToUnsigned(T v)
{
using unsigned_type = std::make_unsigned_t<T>;
return static_cast<unsigned_type>(v);
}
template <typename T, std::enable_if_t<std::is_enum_v<T>> * = nullptr>
constexpr auto ToUnderlying(T value)
{
return static_cast<std::underlying_type_t<T>>(value);
}
constexpr size_t UnsignedDifference(size_t x, size_t y)
{
return x > y ? x - y : 0;
}
constexpr uint64_t UnsignedDifferenceUint64(uint64_t x, uint64_t y)
{
return x > y ? x - y : 0;
}
} // namespace panda::helpers
#ifdef __SIZEOF_INT128__
__extension__ using int128 = __int128;
#else
#include <cstdint>
using int128 = struct int128_type {
constexpr int128_type() = default;
constexpr explicit int128_type(std::int64_t v) : lo(v) {};
std::int64_t hi {0};
std::int64_t lo {0};
bool operator==(std::int64_t v) const
{
return (hi == 0) && (lo == v);
}
};
static_assert(sizeof(int128) == sizeof(std::int64_t) * 2U);
#endif
#endif // PANDA_LIBPANDABASE_UTILS_TYPE_HELPERS_H_
| 26.901408 | 75 | 0.71623 |
282c6aec8194d75fb46e65cc2aeea287deb6c1f1 | 207 | h | C | GDDataDrivenView/Classes/Service/GDDLocalRpc.h | isabella232/GDDataDrivenView | 778a146519c77c7d013c687084c7ee81a242107f | [
"MIT"
] | 12 | 2016-07-10T02:06:36.000Z | 2021-02-04T09:41:50.000Z | GDDataDrivenView/Classes/Service/GDDLocalRpc.h | isabella232/GDDataDrivenView | 778a146519c77c7d013c687084c7ee81a242107f | [
"MIT"
] | 1 | 2018-01-16T09:47:38.000Z | 2018-01-16T10:51:49.000Z | GDDataDrivenView/Classes/Service/GDDLocalRpc.h | isabella232/GDDataDrivenView | 778a146519c77c7d013c687084c7ee81a242107f | [
"MIT"
] | 6 | 2016-09-03T03:03:39.000Z | 2022-03-26T08:59:28.000Z | #import "GDDRpc.h"
@interface GDDLocalRpc<__covariant ObjectType> : NSObject <GDDRpc>
- (GDDLocalRpc<ObjectType> *(^)(ObjectType result))result;
- (GDDLocalRpc<ObjectType> *(^)(NSError *error))error;
@end | 25.875 | 66 | 0.7343 |
282f7d8470f04b89dbb4e170f11ffa8cf3aff0b9 | 408 | h | C | PhysicsEngine/include/Colliders/SphereColliderComponent.h | maxbrundev/OpenGL-Modern-ECS-GameEngine | 9924bacb35e20cd76b68ae79c6cf40a1b34ec4c0 | [
"MIT"
] | 2 | 2020-09-28T18:54:50.000Z | 2020-11-21T19:20:54.000Z | PhysicsEngine/include/Colliders/SphereColliderComponent.h | maxbrundev/OpenGL-Modern-ECS-GameEngine | 9924bacb35e20cd76b68ae79c6cf40a1b34ec4c0 | [
"MIT"
] | null | null | null | PhysicsEngine/include/Colliders/SphereColliderComponent.h | maxbrundev/OpenGL-Modern-ECS-GameEngine | 9924bacb35e20cd76b68ae79c6cf40a1b34ec4c0 | [
"MIT"
] | 2 | 2019-04-07T19:11:00.000Z | 2019-12-03T13:05:07.000Z | #pragma once
#include "Colliders/ACollider.h"
namespace Physics
{
namespace Collision
{
class PHYSICS_API SphereColliderComponent : public ACollider, public ECS::Component<SphereColliderComponent>
{
public:
SphereColliderComponent(COMPONENT_INIT_PARAMS, float p_radius, const Core::Transform& p_transform);
~SphereColliderComponent();
float GetRadius() const;
};
}
} | 21.473684 | 111 | 0.732843 |
282fbf79bf5bef9ea91e1669f1b0f8dcd8093231 | 1,391 | h | C | Tool/kvscheck/SupportChecker.h | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | Tool/kvscheck/SupportChecker.h | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | Tool/kvscheck/SupportChecker.h | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************/
/**
* @file SupportChecker.h
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id: SupportChecker.h 1433 2013-03-17 01:23:37Z naohisa.sakamoto@gmail.com $
*/
/****************************************************************************/
#ifndef KVSCHECK__SUPPORT_CHECKER_H_INCLUDE
#define KVSCHECK__SUPPORT_CHECKER_H_INCLUDE
#include <string>
#include <iostream>
#include <kvs/StringList>
namespace kvscheck
{
/*==========================================================================*/
/**
* KVS support library checker class.
*/
/*==========================================================================*/
class SupportChecker
{
protected:
kvs::StringList m_descriptions; ///< KVS support library description list
kvs::StringList m_versions; ///< KVS support library version list
public:
SupportChecker();
const kvs::StringList& descriptionList() const;
const kvs::StringList& versionList() const;
friend std::ostream& operator << ( std::ostream& os, const SupportChecker& checker );
};
} // end of namespace kvscheck
#endif // KVSCHECK__SUPPORT_CHECKER_H_INCLUDE
| 28.387755 | 89 | 0.51977 |
28344a2f9b23ea9a409e0953c6beb6d86221af17 | 1,295 | h | C | include/Engine/Render/Mesh/Mesh.h | SamCZ/NovaEngine | 7f667988467ab611018f650295825b63c97e8d43 | [
"MIT"
] | 2 | 2021-04-18T06:40:19.000Z | 2021-06-29T23:35:31.000Z | include/Engine/Render/Mesh/Mesh.h | SamCZ/NovaEngine | 7f667988467ab611018f650295825b63c97e8d43 | [
"MIT"
] | null | null | null | include/Engine/Render/Mesh/Mesh.h | SamCZ/NovaEngine | 7f667988467ab611018f650295825b63c97e8d43 | [
"MIT"
] | null | null | null | #ifndef MESH_H
#define MESH_H
#include <map>
#include "Engine/Render/Mesh/VertexBuffer.h"
namespace NovaEngine {
class BoundingBox;
class BIHTree;
enum class Mode : GLenum {
Triangles = GL_TRIANGLES,
Quads = GL_QUADS,
TriangleTrip = GL_TRIANGLE_STRIP,
TriangleFan = GL_TRIANGLE_FAN,
Lines = GL_LINES,
Points = GL_POINTS,
Patch = GL_PATCHES
};
class Mesh {
public:
GLuint _vertexAttribArrays[16];
int _enabledVertexAttribArrays = 0;
GLuint _lastShader;
Mesh();
~Mesh();
void setData(MeshBuffer::Type type, int components, Buffer* buffer);
void setVertexBuffer(MeshBuffer::Type type, VertexBuffer* buffer);
VertexBuffer* getVertexBuffer(MeshBuffer::Type type);
VertexBuffer** getVertexBuffers();
Mode getMode() const;
void setMode(Mode mode);
void createCollisionData();
BIHTree* getCollider();
BoundingBox* getBounds();
void setBounds(BoundingBox* bound);
void updateBounds();
int getPatchVertexCount() const;
void setPatchVertexCount(int patchCount);
int getInstanceCount() const;
void setInstanceCount(int count);
private:
Mode _mode;
VertexBuffer** _vertexBuffersArr;
BIHTree* _collisionTree = nullptr;
BoundingBox* _boundingBox = nullptr;
int _patchVertexCount;
int _instanceCount;
};
}
#endif // !MESH_H | 20.887097 | 70 | 0.73668 |
2837436d105c39b0090f9b1e74d39d1d0a4c006d | 168 | h | C | error.h | zhangboyang/fdu_xk_oldsystem | 2e57b865398d67420ed87fb182eabf43ca61a2c9 | [
"MIT"
] | null | null | null | error.h | zhangboyang/fdu_xk_oldsystem | 2e57b865398d67420ed87fb182eabf43ca61a2c9 | [
"MIT"
] | null | null | null | error.h | zhangboyang/fdu_xk_oldsystem | 2e57b865398d67420ed87fb182eabf43ca61a2c9 | [
"MIT"
] | null | null | null | #ifndef XK_ERROR_H
#define XK_ERROR_H
#include "xk.h"
#define XK_ERROR_MAXLINE 4096
void err_sys(const char *fmt, ...);
void err_quit(const char *fmt, ...);
#endif
| 14 | 36 | 0.714286 |
2839fcb06d0af977ca711d9f2b26c6e4754d801f | 796 | h | C | Spirmark/SpirmarkApp.h | codingoat/Spirmark | f613441063410a8fd89ae718785285a5cea32c00 | [
"MIT"
] | 1 | 2022-03-17T20:50:46.000Z | 2022-03-17T20:50:46.000Z | Spirmark/SpirmarkApp.h | codingoat/Spirmark | f613441063410a8fd89ae718785285a5cea32c00 | [
"MIT"
] | null | null | null | Spirmark/SpirmarkApp.h | codingoat/Spirmark | f613441063410a8fd89ae718785285a5cea32c00 | [
"MIT"
] | 1 | 2021-09-14T09:22:27.000Z | 2021-09-14T09:22:27.000Z | #pragma once
// Helpers
#include <ProgramObject.h>
#include <Bencher.h>
#include <ShaderToySource.h>
#include <SpirverAstAnalyzer.h>
#include <BenchmarkedShaderResult.h>
// Spirmark components
#include <SpirmarkCore.h>
#include <SpirmarkUI.h>
#include <imgui/imgui.h>
#include <filesystem>
namespace Spirmark
{
class SpirmarkApp
{
public:
SpirmarkApp();
~SpirmarkApp();
// main loop
void Update();
void Render();
// input events
void KeyboardDown(SDL_KeyboardEvent&);
void KeyboardUp(SDL_KeyboardEvent&);
void MouseMove(SDL_MouseMotionEvent&);
void MouseDown(SDL_MouseButtonEvent&);
void MouseUp(SDL_MouseButtonEvent&);
void MouseWheel(SDL_MouseWheelEvent&);
void Resize(int, int);
private:
SpirmarkCore core;
SpirmarkUI ui;
};
} | 18.090909 | 40 | 0.714824 |
283adc045acaa0b8d1d751940d42e0c6627276c7 | 718 | h | C | digitalCurrency/Controllers/我的/model/AboutUSModel.h | CoderWeiLee/digitalCurrenc | 7feaac2306d756f264efa9d67231df13b3bd0125 | [
"Apache-2.0"
] | null | null | null | digitalCurrency/Controllers/我的/model/AboutUSModel.h | CoderWeiLee/digitalCurrenc | 7feaac2306d756f264efa9d67231df13b3bd0125 | [
"Apache-2.0"
] | null | null | null | digitalCurrency/Controllers/我的/model/AboutUSModel.h | CoderWeiLee/digitalCurrenc | 7feaac2306d756f264efa9d67231df13b3bd0125 | [
"Apache-2.0"
] | null | null | null | //
// AboutUSModel.h
// digitalCurrency
//
// Created by iDog on 2019/3/21.
// Copyright © 2019年 ABC. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface AboutUSModel : NSObject
@property(nonatomic,copy)NSString *ID;
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *logo;
@property(nonatomic,copy)NSString *addressIcon;
@property(nonatomic,copy)NSString *url;
@property(nonatomic,copy)NSString *keywords;
@property(nonatomic,copy)NSString *describe;
@property(nonatomic,copy)NSString *copyright;
@property(nonatomic,copy)NSString *postcode;
@property(nonatomic,copy)NSString *contact;
@property(nonatomic,copy)NSString *otherInformation;
@end
| 28.72 | 53 | 0.754875 |
283e74840da30cadc118ffe06704be9ed58ef0bd | 752 | h | C | TYModuleServices/Classes/BusinessServiceProtocol/TYTimerProtocol.h | TuyaInc/TYModuleServices | 42bc0c59c81d3bfc50ce148d88d7f238794ef0ef | [
"MIT"
] | null | null | null | TYModuleServices/Classes/BusinessServiceProtocol/TYTimerProtocol.h | TuyaInc/TYModuleServices | 42bc0c59c81d3bfc50ce148d88d7f238794ef0ef | [
"MIT"
] | null | null | null | TYModuleServices/Classes/BusinessServiceProtocol/TYTimerProtocol.h | TuyaInc/TYModuleServices | 42bc0c59c81d3bfc50ce148d88d7f238794ef0ef | [
"MIT"
] | null | null | null | //
// TYTimerProtocol.h
// TYTimerModule
//
// Created by 黄凯 on 2018/7/23.
//
#ifndef TYTimerProtocol_h
#define TYTimerProtocol_h
// 设备预约时间变化
#define KNotificationLinkageTimeUpdate @"KNotificationLinkageTimeUpdate"
@protocol TYTimerProtocol <NSObject>
/**
老版定时入口,Wi-Fi 定时
需要参数为:
{
"gwid" : "xxx",
"devId" : "xxx",
"groupId" : "xxx", // 如果是群组就传
"config" : params
}
@param parameters 数据参数接口
*/
- (void)goToAlarmListActivity:(NSDictionary *)parameters;
/**
新版定时入口,dp 定时
{
"gwid" : "xxx",
"devId" : "xxx",
"isGroup" : yes / no,
"groupId" : "xxx", // 如果是群组就传
"config" : params
}
@param parameters 数据参数接口
*/
- (void)gotoDpAlarm:(NSDictionary *)parameters;
@end
#endif /* TYTimerProtocol_h */
| 15.666667 | 76 | 0.635638 |
28439eae7fe5ea72a6935641011af57a8fb4c599 | 235 | h | C | LazyThemeDemo/LazyThemeDemo/DiscoveryViewController.h | Rannie/LazyTheme | 2cad1bd53a7cabf42c9b8f5cfb2d7db283604ee8 | [
"MIT"
] | 2 | 2016-10-03T08:35:11.000Z | 2019-06-27T17:11:02.000Z | LazyThemeDemo/LazyThemeDemo/DiscoveryViewController.h | Rannie/LazyTheme | 2cad1bd53a7cabf42c9b8f5cfb2d7db283604ee8 | [
"MIT"
] | null | null | null | LazyThemeDemo/LazyThemeDemo/DiscoveryViewController.h | Rannie/LazyTheme | 2cad1bd53a7cabf42c9b8f5cfb2d7db283604ee8 | [
"MIT"
] | null | null | null | //
// DiscoveryViewController.h
// LazyThemeDemo
//
// Created by QiXin on 2016/10/21.
// Copyright © 2016年 rannie. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DiscoveryViewController : UITableViewController
@end
| 16.785714 | 58 | 0.72766 |
284befbfec3967146dd07252092af26ea015b4da | 610 | h | C | EnterPriseIn/EnterPriseIn/ViewController/MainPage/Subviews/BusinessListCell.h | flysss1219/ENAutoHome | fc857bb445a52ee92f925988f3fc81d06a505b33 | [
"Apache-2.0"
] | null | null | null | EnterPriseIn/EnterPriseIn/ViewController/MainPage/Subviews/BusinessListCell.h | flysss1219/ENAutoHome | fc857bb445a52ee92f925988f3fc81d06a505b33 | [
"Apache-2.0"
] | null | null | null | EnterPriseIn/EnterPriseIn/ViewController/MainPage/Subviews/BusinessListCell.h | flysss1219/ENAutoHome | fc857bb445a52ee92f925988f3fc81d06a505b33 | [
"Apache-2.0"
] | null | null | null | //
// BusinessListCell.h
// EnterPriseIn
//
// Created by iOSDev on 2018/6/22.
// Copyright © 2018年 com.shun. All rights reserved.
//
#import <UIKit/UIKit.h>
@class EnterpriseInfoModel;
@interface BusinessListCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *tagLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UIImageView *levelImageView;
- (void)setDataForCell:(EnterpriseInfoModel*)data;
@end
| 19.677419 | 65 | 0.755738 |
284d1f3619198338c41fcf1ef66d109dad614a29 | 779 | h | C | test/dump/swdbgbk_src/chap27/D4D/FastTracer.h | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 39 | 2015-12-09T09:28:46.000Z | 2021-11-16T12:57:25.000Z | test/dump/swdbgbk_src/chap27/D4D/FastTracer.h | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 1 | 2020-10-17T02:23:42.000Z | 2020-10-17T02:23:42.000Z | test/dump/swdbgbk_src/chap27/D4D/FastTracer.h | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 8 | 2018-05-29T12:48:13.000Z | 2022-02-27T01:45:57.000Z | // FastTracer.h: interface for the CFastTracer class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_FASTTRACER_H__FB7E24E8_447A_41CE_A3C2_C918096834E2__INCLUDED_)
#define AFX_FASTTRACER_H__FB7E24E8_447A_41CE_A3C2_C918096834E2__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "D4dObject.h"
typedef ULONG (WINAPI *PFN_RTLWALKFRAMECHAIN)(PVOID *pReturnAddresses,
DWORD dwCount, DWORD dwFlags);
class D4D_API CFastTracer
{
public:
DWORD GetFrameChain(PVOID * pReturnAddresses, DWORD dwCount);
HRESULT Setup();
CFastTracer();
virtual ~CFastTracer();
protected:
PFN_RTLWALKFRAMECHAIN m_pfnWalkFrameChain;
};
#endif // !defined(AFX_FASTTRACER_H__FB7E24E8_447A_41CE_A3C2_C918096834E2__INCLUDED_)
| 27.821429 | 85 | 0.739409 |
284dffa4823c2dd81a00ec1b585f7771adf67a31 | 2,474 | c | C | pocketsphinx/visualdsp/pocketsphinx_continuous/bf561sphinx_heaptab.c | ejuacel/pocketsphinx.js | 6826d08122063d261478ac39a5c7ef9a88f23106 | [
"Unlicense",
"MIT-CMU",
"MIT"
] | 1 | 2016-05-26T03:32:42.000Z | 2016-05-26T03:32:42.000Z | pocketsphinx/visualdsp/pocketsphinx_continuous/bf561sphinx_heaptab.c | ejuacel/pocketsphinx.js | 6826d08122063d261478ac39a5c7ef9a88f23106 | [
"Unlicense",
"MIT-CMU",
"MIT"
] | null | null | null | pocketsphinx/visualdsp/pocketsphinx_continuous/bf561sphinx_heaptab.c | ejuacel/pocketsphinx.js | 6826d08122063d261478ac39a5c7ef9a88f23106 | [
"Unlicense",
"MIT-CMU",
"MIT"
] | null | null | null | /* MANAGED-BY-SYSTEM-BUILDER */
/*
** User heap source file generated on Feb 22, 2008 at 17:31:53.
**
** Copyright (C) 2000-2006 Analog Devices Inc., All Rights Reserved.
**
** This file is generated automatically based upon the options selected
** in the LDF Wizard. Changes to the LDF configuration should be made by
** changing the appropriate options rather than editing this file.
**
** Configuration:-
** crt_doj: .\Debug\bf561sphinx_basiccrt.doj
** processor: ADSP-BF561
** si_revision: automatic
** cplb_init_cplb_ctrl: 81
** using_cplusplus: true
** mem_init: false
** use_vdk: false
** use_eh: true
** use_argv: false
** running_from_internal_memory: true
** user_heap_src_file: C:\work\pocketsphinx\visualdsp\pocketsphinx_continuous\bf561sphinx_heaptab.c
** libraries_use_stdlib: true
** libraries_use_fileio_libs: true
** libraries_use_ieeefp_emulation_libs: false
** libraries_use_eh_enabled_libs: false
** system_heap: L3
** system_heap_size: 16M
** system_stack: L2
** system_stack_size: 31K
** use_sdram: true
** use_sdram_size: 64M
** use_sdram_partitioned: custom
** num_user_heaps: 1
** user_heap0: L3
** user_heap0_size: 16M
** user_heap0_heap_name: MyHeap
** use_multicores: 2
** use_multicores_use_core: multi_core
**
*/
extern "asm" int ldf_heap_space;
extern "asm" int ldf_heap_length;
extern "asm" int MyHeap_space;
extern "asm" int MyHeap_length;
struct heap_table_t
{
void *base;
unsigned long length;
long int userid;
};
#pragma file_attr("libData=HeapTable")
#pragma section("constdata")
struct heap_table_t heap_table[3] =
{
{ &ldf_heap_space, (int) &ldf_heap_length, 0 },
{ &MyHeap_space, (int) &MyHeap_length, 1 },
{ 0, 0, 0 }
};
| 34.361111 | 123 | 0.50768 |
284e1106328b8a821f7e00f72a0e0a4aa93f70a2 | 295 | h | C | Fonts/NSString+RegEx.h | ffried/system-fonts | a13e1ebc7d10285598b1b18ce18b47ed5cfd5fbd | [
"Apache-2.0"
] | null | null | null | Fonts/NSString+RegEx.h | ffried/system-fonts | a13e1ebc7d10285598b1b18ce18b47ed5cfd5fbd | [
"Apache-2.0"
] | null | null | null | Fonts/NSString+RegEx.h | ffried/system-fonts | a13e1ebc7d10285598b1b18ce18b47ed5cfd5fbd | [
"Apache-2.0"
] | null | null | null | //
// NSString+RegEx.h
// Fonts
//
// Created by Florian Friedrich on 08.04.14.
// Copyright (c) 2014 Florian Friedrich. All rights reserved.
//
@import Foundation;
@interface NSString (RegEx)
- (BOOL)matchesPattern:(NSString *)pattern;
- (BOOL)containsPattern:(NSString *)pattern;
@end
| 17.352941 | 62 | 0.701695 |
284f11a8af85d4edb39522e0366200791a69b024 | 5,342 | c | C | engines/native_x86.c | enferex/asrepl | d0945a11c3f826f1f1e34bd93c681481fec1af5a | [
"BSD-3-Clause"
] | 59 | 2017-02-20T00:57:23.000Z | 2021-11-30T20:32:03.000Z | engines/native_x86.c | enferex/asrepl | d0945a11c3f826f1f1e34bd93c681481fec1af5a | [
"BSD-3-Clause"
] | 4 | 2017-02-20T05:43:24.000Z | 2017-04-10T04:18:27.000Z | engines/native_x86.c | enferex/asrepl | d0945a11c3f826f1f1e34bd93c681481fec1af5a | [
"BSD-3-Clause"
] | 3 | 2017-02-20T04:30:43.000Z | 2020-07-13T00:45:08.000Z | #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <errno.h>
#include "../asrepl.h"
#include "common.h"
static void get_registers(pid_t pid, struct user_regs_struct *gpregs)
{
memset(gpregs, 0, sizeof(*gpregs));
ptrace(PTRACE_GETREGS, pid, NULL, gpregs);
}
static uintptr_t get_pc(pid_t pid)
{
struct user_regs_struct gpregs;
get_registers(pid, &gpregs);
return gpregs.rip;
}
static void native_x8664_read_registers(engine_t *eng)
{
pid_t pid = eng->engine_pid;
struct user_regs_struct regs;
get_registers(pid, ®s);
REGS_X8664(eng).eflags = regs.eflags;
REGS_X8664(eng).rip = regs.rip;
REGS_X8664(eng).cs = regs.cs;
REGS_X8664(eng).ds = regs.ds;
REGS_X8664(eng).es = regs.es;
REGS_X8664(eng).fs = regs.fs;
REGS_X8664(eng).gs = regs.fs;
REGS_X8664(eng).ss = regs.ss;
REGS_X8664(eng).rbp = regs.rbp;
REGS_X8664(eng).rsp = regs.rsp;
REGS_X8664(eng).rax = regs.rax;
REGS_X8664(eng).rbx = regs.rbx;
REGS_X8664(eng).rcx = regs.rcx;
REGS_X8664(eng).rdx = regs.rdx;
REGS_X8664(eng).rdi = regs.rdi;
REGS_X8664(eng).rsi = regs.rsi;
REGS_X8664(eng).r8 = regs.r8;
REGS_X8664(eng).r9 = regs.r9;
REGS_X8664(eng).r10 = regs.r10;
REGS_X8664(eng).r11 = regs.r11;
REGS_X8664(eng).r12 = regs.r12;
REGS_X8664(eng).r13 = regs.r13;
REGS_X8664(eng).r14 = regs.r14;
REGS_X8664(eng).r15 = regs.r15;
}
static _Bool native_x8664_init(asrepl_t *asr, engine_t *eng)
{
uint64_t pid;
eng->handle = calloc(1, sizeof(pid_t));
if (!eng->handle)
ERF("Could not allocate enough memory to represent an engine handle.");
pid = fork();
eng->engine_pid = pid;
if (pid > 0) {
/* Parent with child's pid. Wait for the child. */
int status;
const pid_t ret = waitpid(pid, &status, __WALL);
return (pid == ret && WIFSTOPPED(status));
}
else if (pid == 0) {
/* Child (tracee) */
if (ptrace(PTRACE_TRACEME, pid, NULL, NULL) == -1) {
ERF("Error setting traceme in the child process: %s",
strerror(errno));
}
/* Just a ton of nops for space */
for ( ;; ) {
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
/* All instructions should be inserted here, since
* this is where the pc will be in the tracee as the int3 below
* will signal the tracer to start inserting instructions.
*/
__asm__ __volatile__ ("int $3\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
__asm__ __volatile__ ("nop\n");
}
}
else
ERR("Error fork()ing child process: %s", strerror(errno));
return false; /* Error */
}
static _Bool native_x8664_shutdown(engine_t *eng)
{
return true;
}
static void native_x8664_execute(engine_t *eng, const ctx_t *ctx)
{
int i, n_words, status;
uintptr_t pc, orig_pc;
pid_t ret;
uint8_t *insns;
struct user_regs_struct regs;
/* We will restore the pc after we single step and gather registers */
orig_pc = get_pc(eng->engine_pid);
/* POKETEXT operates on word size units (round up) */
pc = orig_pc;
insns = ctx->text;
n_words = (ctx->length / sizeof(word_t));
if (ctx->length % sizeof(word_t))
++n_words;
for (i=0; i<n_words; ++i) {
word_t word = *(word_t *)insns;
ptrace(PTRACE_POKETEXT, eng->engine_pid, (void *)pc, (void *)word);
pc += sizeof(word_t);
insns += sizeof(word_t);
}
/* Now that data is loaded at the PC of the engine, single step one insn */
ptrace(PTRACE_SINGLESTEP, eng->engine_pid, NULL, NULL);
ret = waitpid(eng->engine_pid, &status, __WALL);
if (ret != 0 && !WIFSTOPPED(status))
ERF("Error waiting for engine to single step\n");
/* Now that we have executed the instruction, restore the pc */
get_registers(eng->engine_pid, ®s);
regs.rip = orig_pc;
ptrace(PTRACE_SETREGS, eng->engine_pid, NULL, ®s);
}
/*
* REGISTRATION
*/
const engine_desc_t *native_x8664_registration(void)
{
static const engine_desc_t desc = {
.type = ENGINE_NATIVE_X8664,
.init = native_x8664_init,
.execute = native_x8664_execute,
.shutdown = native_x8664_shutdown,
.read_registers = native_x8664_read_registers,
.dump_registers = common_x8664_dump_registers
};
return &desc;
}
| 30.180791 | 79 | 0.59678 |
284f382f95704c74bdc0e88cd3ac665bd090b8d9 | 125,029 | c | C | source/blender/blenkernel/intern/particle_system.c | wycivil08/blendocv | f6cce83e1f149fef39afa8043aade9c64378f33e | [
"Unlicense"
] | 30 | 2015-01-29T14:06:05.000Z | 2022-01-10T07:47:29.000Z | source/blender/blenkernel/intern/particle_system.c | ttagu99/blendocv | f6cce83e1f149fef39afa8043aade9c64378f33e | [
"Unlicense"
] | 1 | 2017-02-20T20:57:48.000Z | 2018-12-19T23:44:38.000Z | source/blender/blenkernel/intern/particle_system.c | ttagu99/blendocv | f6cce83e1f149fef39afa8043aade9c64378f33e | [
"Unlicense"
] | 15 | 2015-04-23T02:38:36.000Z | 2021-03-01T20:09:39.000Z | /*
* $Id: particle_system.c 41020 2011-10-15 01:42:26Z jhk $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2007 by Janne Karhu.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): Raul Fernandez Hernandez (Farsthary), Stephen Swhitehorn.
*
* Adaptive time step
* Copyright 2011 AutoCRC
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/blenkernel/intern/particle_system.c
* \ingroup bke
*/
#include <stddef.h>
#include "BLI_storage.h" /* _LARGEFILE_SOURCE */
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "MEM_guardedalloc.h"
#include "DNA_anim_types.h"
#include "DNA_boid_types.h"
#include "DNA_particle_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_force.h"
#include "DNA_object_types.h"
#include "DNA_material_types.h"
#include "DNA_curve_types.h"
#include "DNA_group_types.h"
#include "DNA_scene_types.h"
#include "DNA_texture_types.h"
#include "DNA_ipo_types.h" // XXX old animation system stuff... to be removed!
#include "DNA_listBase.h"
#include "BLI_edgehash.h"
#include "BLI_rand.h"
#include "BLI_jitter.h"
#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_kdtree.h"
#include "BLI_kdopbvh.h"
#include "BLI_listbase.h"
#include "BLI_threads.h"
#include "BLI_storage.h" /* For _LARGEFILE64_SOURCE; zlib needs this on some systems */
#include "BLI_string.h"
#include "BLI_utildefines.h"
#include "BKE_main.h"
#include "BKE_animsys.h"
#include "BKE_boids.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_collision.h"
#include "BKE_displist.h"
#include "BKE_effect.h"
#include "BKE_particle.h"
#include "BKE_global.h"
#include "BKE_DerivedMesh.h"
#include "BKE_object.h"
#include "BKE_material.h"
#include "BKE_cloth.h"
#include "BKE_depsgraph.h"
#include "BKE_lattice.h"
#include "BKE_pointcache.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
#include "BKE_scene.h"
#include "BKE_bvhutils.h"
#include "PIL_time.h"
#include "RE_shader_ext.h"
/* fluid sim particle import */
#ifndef DISABLE_ELBEEM
#include "DNA_object_fluidsim.h"
#include "LBM_fluidsim.h"
#include <zlib.h>
#include <string.h>
#endif // DISABLE_ELBEEM
/************************************************/
/* Reacting to system events */
/************************************************/
static int particles_are_dynamic(ParticleSystem *psys) {
if(psys->pointcache->flag & PTCACHE_BAKED)
return 0;
if(psys->part->type == PART_HAIR)
return psys->flag & PSYS_HAIR_DYNAMICS;
else
return ELEM3(psys->part->phystype, PART_PHYS_NEWTON, PART_PHYS_BOIDS, PART_PHYS_FLUID);
}
static int psys_get_current_display_percentage(ParticleSystem *psys)
{
ParticleSettings *part=psys->part;
if((psys->renderdata && !particles_are_dynamic(psys)) /* non-dynamic particles can be rendered fully */
|| (part->child_nbr && part->childtype) /* display percentage applies to children */
|| (psys->pointcache->flag & PTCACHE_BAKING)) /* baking is always done with full amount */
return 100;
return psys->part->disp;
}
static int tot_particles(ParticleSystem *psys, PTCacheID *pid)
{
if(pid && psys->pointcache->flag & PTCACHE_EXTERNAL)
return pid->cache->totpoint;
else if(psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT)
return psys->part->grid_res * psys->part->grid_res * psys->part->grid_res - psys->totunexist;
else
return psys->part->totpart - psys->totunexist;
}
void psys_reset(ParticleSystem *psys, int mode)
{
PARTICLE_P;
if(ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
if(mode == PSYS_RESET_ALL || !(psys->flag & PSYS_EDITED)) {
/* don't free if not absolutely necessary */
if(psys->totpart != tot_particles(psys, NULL)) {
psys_free_particles(psys);
psys->totpart= 0;
}
psys->totkeyed= 0;
psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
if(psys->edit && psys->free_edit) {
psys->free_edit(psys->edit);
psys->edit = NULL;
psys->free_edit = NULL;
}
}
}
else if(mode == PSYS_RESET_CACHE_MISS) {
/* set all particles to be skipped */
LOOP_PARTICLES
pa->flag |= PARS_NO_DISP;
}
/* reset children */
if(psys->child) {
MEM_freeN(psys->child);
psys->child= NULL;
}
psys->totchild= 0;
/* reset path cache */
psys_free_path_cache(psys, psys->edit);
/* reset point cache */
BKE_ptcache_invalidate(psys->pointcache);
if(psys->fluid_springs) {
MEM_freeN(psys->fluid_springs);
psys->fluid_springs = NULL;
}
psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
}
static void realloc_particles(ParticleSimulationData *sim, int new_totpart)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
ParticleData *newpars = NULL;
BoidParticle *newboids = NULL;
PARTICLE_P;
int totpart, totsaved = 0;
if(new_totpart<0) {
if(part->distr==PART_DISTR_GRID && part->from != PART_FROM_VERT) {
totpart= part->grid_res;
totpart*=totpart*totpart;
}
else
totpart=part->totpart;
}
else
totpart=new_totpart;
if(totpart != psys->totpart) {
if(psys->edit && psys->free_edit) {
psys->free_edit(psys->edit);
psys->edit = NULL;
psys->free_edit = NULL;
}
if(totpart) {
newpars= MEM_callocN(totpart*sizeof(ParticleData), "particles");
if(newpars == NULL)
return;
if(psys->part->phystype == PART_PHYS_BOIDS) {
newboids= MEM_callocN(totpart*sizeof(BoidParticle), "boid particles");
if(newboids == NULL) {
/* allocation error! */
if(newpars)
MEM_freeN(newpars);
return;
}
}
}
if(psys->particles) {
totsaved=MIN2(psys->totpart,totpart);
/*save old pars*/
if(totsaved) {
memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
if(psys->particles->boid)
memcpy(newboids, psys->particles->boid, totsaved*sizeof(BoidParticle));
}
if(psys->particles->keys)
MEM_freeN(psys->particles->keys);
if(psys->particles->boid)
MEM_freeN(psys->particles->boid);
for(p=0, pa=newpars; p<totsaved; p++, pa++) {
if(pa->keys) {
pa->keys= NULL;
pa->totkey= 0;
}
}
for(p=totsaved, pa=psys->particles+totsaved; p<psys->totpart; p++, pa++)
if(pa->hair) MEM_freeN(pa->hair);
MEM_freeN(psys->particles);
psys_free_pdd(psys);
}
psys->particles=newpars;
psys->totpart=totpart;
if(newboids) {
LOOP_PARTICLES
pa->boid = newboids++;
}
}
if(psys->child) {
MEM_freeN(psys->child);
psys->child=NULL;
psys->totchild=0;
}
}
static int get_psys_child_number(struct Scene *scene, ParticleSystem *psys)
{
int nbr;
if(!psys->part->childtype)
return 0;
if(psys->renderdata)
nbr= psys->part->ren_child_nbr;
else
nbr= psys->part->child_nbr;
return get_render_child_particle_number(&scene->r, nbr);
}
static int get_psys_tot_child(struct Scene *scene, ParticleSystem *psys)
{
return psys->totpart*get_psys_child_number(scene, psys);
}
static void alloc_child_particles(ParticleSystem *psys, int tot)
{
if(psys->child){
/* only re-allocate if we have to */
if(psys->part->childtype && psys->totchild == tot) {
memset(psys->child, 0, tot*sizeof(ChildParticle));
return;
}
MEM_freeN(psys->child);
psys->child=NULL;
psys->totchild=0;
}
if(psys->part->childtype) {
psys->totchild= tot;
if(psys->totchild)
psys->child= MEM_callocN(psys->totchild*sizeof(ChildParticle), "child_particles");
}
}
/************************************************/
/* Distribution */
/************************************************/
void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
{
/* use for building derived mesh mapping info:
node: the allocated links - total derived mesh element count
nodearray: the array of nodes aligned with the base mesh's elements, so
each original elements can reference its derived elements
*/
Mesh *me= (Mesh*)ob->data;
PARTICLE_P;
/* CACHE LOCATIONS */
if(!dm->deformedOnly) {
/* Will use later to speed up subsurf/derivedmesh */
LinkNode *node, *nodedmelem, **nodearray;
int totdmelem, totelem, i, *origindex;
if(psys->part->from == PART_FROM_VERT) {
totdmelem= dm->getNumVerts(dm);
totelem= me->totvert;
origindex= dm->getVertDataArray(dm, CD_ORIGINDEX);
}
else { /* FROM_FACE/FROM_VOLUME */
totdmelem= dm->getNumFaces(dm);
totelem= me->totface;
origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
}
nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
for(i=0, node=nodedmelem; i<totdmelem; i++, origindex++, node++) {
node->link= SET_INT_IN_POINTER(i);
if(*origindex != -1) {
if(nodearray[*origindex]) {
/* prepend */
node->next = nodearray[*origindex];
nodearray[*origindex]= node;
}
else
nodearray[*origindex]= node;
}
}
/* cache the verts/faces! */
LOOP_PARTICLES {
if(pa->num < 0) {
pa->num_dmcache = -1;
continue;
}
if(psys->part->from == PART_FROM_VERT) {
if(nodearray[pa->num])
pa->num_dmcache= GET_INT_FROM_POINTER(nodearray[pa->num]->link);
}
else { /* FROM_FACE/FROM_VOLUME */
/* Note that sometimes the pa->num is over the nodearray size, this is bad, maybe there is a better place to fix this,
* but for now passing NULL is OK. every face will be searched for the particle so its slower - Campbell */
pa->num_dmcache= psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, pa->num < totelem ? nodearray[pa->num] : NULL);
}
}
MEM_freeN(nodearray);
MEM_freeN(nodedmelem);
}
else {
/* TODO PARTICLE, make the following line unnecessary, each function
* should know to use the num or num_dmcache, set the num_dmcache to
* an invalid value, just incase */
LOOP_PARTICLES
pa->num_dmcache = -1;
}
}
static void distribute_simple_children(Scene *scene, Object *ob, DerivedMesh *finaldm, ParticleSystem *psys)
{
ChildParticle *cpa = NULL;
int i, p;
int child_nbr= get_psys_child_number(scene, psys);
int totpart= get_psys_tot_child(scene, psys);
alloc_child_particles(psys, totpart);
cpa = psys->child;
for(i=0; i<child_nbr; i++){
for(p=0; p<psys->totpart; p++,cpa++){
float length=2.0;
cpa->parent=p;
/* create even spherical distribution inside unit sphere */
while(length>=1.0f){
cpa->fuv[0]=2.0f*BLI_frand()-1.0f;
cpa->fuv[1]=2.0f*BLI_frand()-1.0f;
cpa->fuv[2]=2.0f*BLI_frand()-1.0f;
length=len_v3(cpa->fuv);
}
cpa->num=-1;
}
}
/* dmcache must be updated for parent particles if children from faces is used */
psys_calc_dmcache(ob, finaldm, psys);
}
static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys)
{
ParticleData *pa=NULL;
float min[3], max[3], delta[3], d;
MVert *mv, *mvert = dm->getVertDataArray(dm,0);
int totvert=dm->getNumVerts(dm), from=psys->part->from;
int i, j, k, p, res=psys->part->grid_res, size[3], axis;
mv=mvert;
/* find bounding box of dm */
copy_v3_v3(min, mv->co);
copy_v3_v3(max, mv->co);
mv++;
for(i=1; i<totvert; i++, mv++){
min[0]=MIN2(min[0],mv->co[0]);
min[1]=MIN2(min[1],mv->co[1]);
min[2]=MIN2(min[2],mv->co[2]);
max[0]=MAX2(max[0],mv->co[0]);
max[1]=MAX2(max[1],mv->co[1]);
max[2]=MAX2(max[2],mv->co[2]);
}
VECSUB(delta,max,min);
/* determine major axis */
axis = (delta[0]>=delta[1]) ? 0 : ((delta[1]>=delta[2]) ? 1 : 2);
d = delta[axis]/(float)res;
size[axis] = res;
size[(axis+1)%3] = (int)ceil(delta[(axis+1)%3]/d);
size[(axis+2)%3] = (int)ceil(delta[(axis+2)%3]/d);
/* float errors grrr.. */
size[(axis+1)%3] = MIN2(size[(axis+1)%3],res);
size[(axis+2)%3] = MIN2(size[(axis+2)%3],res);
size[0] = MAX2(size[0], 1);
size[1] = MAX2(size[1], 1);
size[2] = MAX2(size[2], 1);
/* no full offset for flat/thin objects */
min[0]+= d < delta[0] ? d/2.f : delta[0]/2.f;
min[1]+= d < delta[1] ? d/2.f : delta[1]/2.f;
min[2]+= d < delta[2] ? d/2.f : delta[2]/2.f;
for(i=0,p=0,pa=psys->particles; i<res; i++){
for(j=0; j<res; j++){
for(k=0; k<res; k++,p++,pa++){
pa->fuv[0] = min[0] + (float)i*d;
pa->fuv[1] = min[1] + (float)j*d;
pa->fuv[2] = min[2] + (float)k*d;
pa->flag |= PARS_UNEXIST;
pa->hair_index = 0; /* abused in volume calculation */
}
}
}
/* enable particles near verts/edges/faces/inside surface */
if(from==PART_FROM_VERT){
float vec[3];
pa=psys->particles;
min[0] -= d/2.0f;
min[1] -= d/2.0f;
min[2] -= d/2.0f;
for(i=0,mv=mvert; i<totvert; i++,mv++){
sub_v3_v3v3(vec,mv->co,min);
vec[0]/=delta[0];
vec[1]/=delta[1];
vec[2]/=delta[2];
(pa +((int)(vec[0]*(size[0]-1))*res
+(int)(vec[1]*(size[1]-1)))*res
+(int)(vec[2]*(size[2]-1)))->flag &= ~PARS_UNEXIST;
}
}
else if(ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)){
float co1[3], co2[3];
MFace *mface= NULL, *mface_array;
float v1[3], v2[3], v3[3], v4[4], lambda;
int a, a1, a2, a0mul, a1mul, a2mul, totface;
int amax= from==PART_FROM_FACE ? 3 : 1;
totface=dm->getNumFaces(dm);
mface_array= dm->getFaceDataArray(dm,CD_MFACE);
for(a=0; a<amax; a++){
if(a==0){ a0mul=res*res; a1mul=res; a2mul=1; }
else if(a==1){ a0mul=res; a1mul=1; a2mul=res*res; }
else{ a0mul=1; a1mul=res*res; a2mul=res; }
for(a1=0; a1<size[(a+1)%3]; a1++){
for(a2=0; a2<size[(a+2)%3]; a2++){
mface= mface_array;
pa = psys->particles + a1*a1mul + a2*a2mul;
copy_v3_v3(co1, pa->fuv);
co1[a] -= d < delta[a] ? d/2.f : delta[a]/2.f;
copy_v3_v3(co2, co1);
co2[a] += delta[a] + 0.001f*d;
co1[a] -= 0.001f*d;
/* lets intersect the faces */
for(i=0; i<totface; i++,mface++){
copy_v3_v3(v1, mvert[mface->v1].co);
copy_v3_v3(v2, mvert[mface->v2].co);
copy_v3_v3(v3, mvert[mface->v3].co);
if(isect_axial_line_tri_v3(a, co1, co2, v2, v3, v1, &lambda)){
if(from==PART_FROM_FACE)
(pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
else /* store number of intersections */
(pa+(int)(lambda*size[a])*a0mul)->hair_index++;
}
if(mface->v4){
copy_v3_v3(v4, mvert[mface->v4].co);
if(isect_axial_line_tri_v3(a, co1, co2, v4, v1, v3, &lambda)){
if(from==PART_FROM_FACE)
(pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
else
(pa+(int)(lambda*size[a])*a0mul)->hair_index++;
}
}
}
if(from==PART_FROM_VOLUME){
int in=pa->hair_index%2;
if(in) pa->hair_index++;
for(i=0; i<size[0]; i++){
if(in || (pa+i*a0mul)->hair_index%2)
(pa+i*a0mul)->flag &= ~PARS_UNEXIST;
/* odd intersections == in->out / out->in */
/* even intersections -> in stays same */
in=(in + (pa+i*a0mul)->hair_index) % 2;
}
}
}
}
}
}
if(psys->part->flag & PART_GRID_HEXAGONAL) {
for(i=0,p=0,pa=psys->particles; i<res; i++){
for(j=0; j<res; j++){
for(k=0; k<res; k++,p++,pa++){
if(j%2)
pa->fuv[0] += d/2.f;
if(k%2) {
pa->fuv[0] += d/2.f;
pa->fuv[1] += d/2.f;
}
}
}
}
}
if(psys->part->flag & PART_GRID_INVERT){
for(i=0; i<size[0]; i++){
for(j=0; j<size[1]; j++){
pa=psys->particles + res*(i*res + j);
for(k=0; k<size[2]; k++, pa++){
pa->flag ^= PARS_UNEXIST;
}
}
}
}
if(psys->part->grid_rand > 0.f) {
float rfac = d * psys->part->grid_rand;
for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++){
if(pa->flag & PARS_UNEXIST)
continue;
pa->fuv[0] += rfac * (PSYS_FRAND(p + 31) - 0.5f);
pa->fuv[1] += rfac * (PSYS_FRAND(p + 32) - 0.5f);
pa->fuv[2] += rfac * (PSYS_FRAND(p + 33) - 0.5f);
}
}
}
/* modified copy from rayshade.c */
static void hammersley_create(float *out, int n, int seed, float amount)
{
RNG *rng;
double p, t, offs[2];
int k, kk;
rng = rng_new(31415926 + n + seed);
offs[0]= rng_getDouble(rng) + (double)amount;
offs[1]= rng_getDouble(rng) + (double)amount;
rng_free(rng);
for (k = 0; k < n; k++) {
t = 0;
for (p = 0.5, kk = k; kk; p *= 0.5, kk >>= 1)
if (kk & 1) /* kk mod 2 = 1 */
t += p;
out[2*k + 0]= fmod((double)k/(double)n + offs[0], 1.0);
out[2*k + 1]= fmod(t + offs[1], 1.0);
}
}
/* modified copy from effect.c */
static void init_mv_jit(float *jit, int num, int seed2, float amount)
{
RNG *rng;
float *jit2, x, rad1, rad2, rad3;
int i, num2;
if(num==0) return;
rad1= (float)(1.0f/sqrtf((float)num));
rad2= (float)(1.0f/((float)num));
rad3= (float)sqrt((float)num)/((float)num);
rng = rng_new(31415926 + num + seed2);
x= 0;
num2 = 2 * num;
for(i=0; i<num2; i+=2) {
jit[i]= x + amount*rad1*(0.5f - rng_getFloat(rng));
jit[i+1]= i/(2.0f*num) + amount*rad1*(0.5f - rng_getFloat(rng));
jit[i]-= (float)floor(jit[i]);
jit[i+1]-= (float)floor(jit[i+1]);
x+= rad3;
x -= (float)floor(x);
}
jit2= MEM_mallocN(12 + 2*sizeof(float)*num, "initjit");
for (i=0 ; i<4 ; i++) {
BLI_jitterate1(jit, jit2, num, rad1);
BLI_jitterate1(jit, jit2, num, rad1);
BLI_jitterate2(jit, jit2, num, rad2);
}
MEM_freeN(jit2);
rng_free(rng);
}
static void psys_uv_to_w(float u, float v, int quad, float *w)
{
float vert[4][3], co[3];
if(!quad) {
if(u+v > 1.0f)
v= 1.0f-v;
else
u= 1.0f-u;
}
vert[0][0]= 0.0f; vert[0][1]= 0.0f; vert[0][2]= 0.0f;
vert[1][0]= 1.0f; vert[1][1]= 0.0f; vert[1][2]= 0.0f;
vert[2][0]= 1.0f; vert[2][1]= 1.0f; vert[2][2]= 0.0f;
co[0]= u;
co[1]= v;
co[2]= 0.0f;
if(quad) {
vert[3][0]= 0.0f; vert[3][1]= 1.0f; vert[3][2]= 0.0f;
interp_weights_poly_v3( w,vert, 4, co);
}
else {
interp_weights_poly_v3( w,vert, 3, co);
w[3]= 0.0f;
}
}
/* Find the index in "sum" array before "value" is crossed. */
static int distribute_binary_search(float *sum, int n, float value)
{
int mid, low=0, high=n;
if(value == 0.f)
return 0;
while(low <= high) {
mid= (low + high)/2;
if(sum[mid] < value && value <= sum[mid+1])
return mid;
if(sum[mid] >= value)
high= mid - 1;
else if(sum[mid] < value)
low= mid + 1;
else
return mid;
}
return low;
}
/* the max number if calls to rng_* funcs within psys_thread_distribute_particle
* be sure to keep up to date if this changes */
#define PSYS_RND_DIST_SKIP 2
/* note: this function must be thread safe, for from == PART_FROM_CHILD */
#define ONLY_WORKING_WITH_PA_VERTS 0
static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, ChildParticle *cpa, int p)
{
ParticleThreadContext *ctx= thread->ctx;
Object *ob= ctx->sim.ob;
DerivedMesh *dm= ctx->dm;
float *v1, *v2, *v3, *v4, nor[3], orco1[3], co1[3], co2[3], nor1[3];
float cur_d, min_d, randu, randv;
int from= ctx->from;
int cfrom= ctx->cfrom;
int distr= ctx->distr;
int i, intersect, tot;
int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */
if(from == PART_FROM_VERT) {
/* TODO_PARTICLE - use original index */
pa->num= ctx->index[p];
pa->fuv[0] = 1.0f;
pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0;
#if ONLY_WORKING_WITH_PA_VERTS
if(ctx->tree){
KDTreeNearest ptn[3];
int w, maxw;
psys_particle_on_dm(ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0);
transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
maxw = BLI_kdtree_find_n_nearest(ctx->tree,3,orco1,NULL,ptn);
for(w=0; w<maxw; w++){
pa->verts[w]=ptn->num;
}
}
#endif
}
else if(from == PART_FROM_FACE || from == PART_FROM_VOLUME) {
MFace *mface;
pa->num = i = ctx->index[p];
mface = dm->getFaceData(dm,i,CD_MFACE);
switch(distr){
case PART_DISTR_JIT:
if(ctx->jitlevel == 1) {
if(mface->v4)
psys_uv_to_w(0.5f, 0.5f, mface->v4, pa->fuv);
else
psys_uv_to_w(0.33333f, 0.33333f, mface->v4, pa->fuv);
}
else {
ctx->jitoff[i] = fmod(ctx->jitoff[i],(float)ctx->jitlevel);
psys_uv_to_w(ctx->jit[2*(int)ctx->jitoff[i]], ctx->jit[2*(int)ctx->jitoff[i]+1], mface->v4, pa->fuv);
ctx->jitoff[i]++;
}
break;
case PART_DISTR_RAND:
randu= rng_getFloat(thread->rng);
randv= rng_getFloat(thread->rng);
rng_skip_tot -= 2;
psys_uv_to_w(randu, randv, mface->v4, pa->fuv);
break;
}
pa->foffset= 0.0f;
/* experimental */
if(from==PART_FROM_VOLUME){
MVert *mvert=dm->getVertDataArray(dm,CD_MVERT);
tot=dm->getNumFaces(dm);
psys_interpolate_face(mvert,mface,0,0,pa->fuv,co1,nor,0,0,0,0);
normalize_v3(nor);
mul_v3_fl(nor,-100.0);
VECADD(co2,co1,nor);
min_d=2.0;
intersect=0;
for(i=0,mface=dm->getFaceDataArray(dm,CD_MFACE); i<tot; i++,mface++){
if(i==pa->num) continue;
v1=mvert[mface->v1].co;
v2=mvert[mface->v2].co;
v3=mvert[mface->v3].co;
if(isect_line_tri_v3(co1, co2, v2, v3, v1, &cur_d, 0)){
if(cur_d<min_d){
min_d=cur_d;
pa->foffset=cur_d*50.0f; /* to the middle of volume */
intersect=1;
}
}
if(mface->v4){
v4=mvert[mface->v4].co;
if(isect_line_tri_v3(co1, co2, v4, v1, v3, &cur_d, 0)){
if(cur_d<min_d){
min_d=cur_d;
pa->foffset=cur_d*50.0f; /* to the middle of volume */
intersect=1;
}
}
}
}
if(intersect==0)
pa->foffset=0.0;
else switch(distr){
case PART_DISTR_JIT:
pa->foffset*= ctx->jit[p%(2*ctx->jitlevel)];
break;
case PART_DISTR_RAND:
pa->foffset*=BLI_frand();
break;
}
}
}
else if(from == PART_FROM_CHILD) {
MFace *mf;
if(ctx->index[p] < 0) {
cpa->num=0;
cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]=0.0f;
cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
return;
}
mf= dm->getFaceData(dm, ctx->index[p], CD_MFACE);
randu= rng_getFloat(thread->rng);
randv= rng_getFloat(thread->rng);
rng_skip_tot -= 2;
psys_uv_to_w(randu, randv, mf->v4, cpa->fuv);
cpa->num = ctx->index[p];
if(ctx->tree){
KDTreeNearest ptn[10];
int w,maxw;//, do_seams;
float maxd /*, mind,dd */, totw= 0.0f;
int parent[10];
float pweight[10];
psys_particle_on_dm(dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,NULL,NULL,orco1,NULL);
transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
maxw = BLI_kdtree_find_n_nearest(ctx->tree,4,orco1,NULL,ptn);
maxd=ptn[maxw-1].dist;
/* mind=ptn[0].dist; */ /* UNUSED */
/* the weights here could be done better */
for(w=0; w<maxw; w++){
parent[w]=ptn[w].index;
pweight[w]=(float)pow(2.0,(double)(-6.0f*ptn[w].dist/maxd));
}
for(;w<10; w++){
parent[w]=-1;
pweight[w]=0.0f;
}
for(w=0,i=0; w<maxw && i<4; w++){
if(parent[w]>=0){
cpa->pa[i]=parent[w];
cpa->w[i]=pweight[w];
totw+=pweight[w];
i++;
}
}
for(;i<4; i++){
cpa->pa[i]=-1;
cpa->w[i]=0.0f;
}
if(totw>0.0f) for(w=0; w<4; w++)
cpa->w[w]/=totw;
cpa->parent=cpa->pa[0];
}
}
if(rng_skip_tot > 0) /* should never be below zero */
rng_skip(thread->rng, rng_skip_tot);
}
static void *distribute_threads_exec_cb(void *data)
{
ParticleThread *thread= (ParticleThread*)data;
ParticleSystem *psys= thread->ctx->sim.psys;
ParticleData *pa;
ChildParticle *cpa;
int p, totpart;
if(thread->ctx->from == PART_FROM_CHILD) {
totpart= psys->totchild;
cpa= psys->child;
for(p=0; p<totpart; p++, cpa++) {
if(thread->ctx->skip) /* simplification skip */
rng_skip(thread->rng, PSYS_RND_DIST_SKIP * thread->ctx->skip[p]);
if((p+thread->num) % thread->tot == 0)
distribute_threads_exec(thread, NULL, cpa, p);
else /* thread skip */
rng_skip(thread->rng, PSYS_RND_DIST_SKIP);
}
}
else {
totpart= psys->totpart;
pa= psys->particles + thread->num;
for(p=thread->num; p<totpart; p+=thread->tot, pa+=thread->tot)
distribute_threads_exec(thread, pa, NULL, p);
}
return 0;
}
/* not thread safe, but qsort doesn't take userdata argument */
static int *COMPARE_ORIG_INDEX = NULL;
static int distribute_compare_orig_index(const void *p1, const void *p2)
{
int index1 = COMPARE_ORIG_INDEX[*(const int*)p1];
int index2 = COMPARE_ORIG_INDEX[*(const int*)p2];
if(index1 < index2)
return -1;
else if(index1 == index2) {
/* this pointer comparison appears to make qsort stable for glibc,
* and apparently on solaris too, makes the renders reproducable */
if(p1 < p2)
return -1;
else if(p1 == p2)
return 0;
else
return 1;
}
else
return 1;
}
static void distribute_invalid(Scene *scene, ParticleSystem *psys, int from)
{
if(from == PART_FROM_CHILD) {
ChildParticle *cpa;
int p, totchild = get_psys_tot_child(scene, psys);
if(psys->child && totchild) {
for(p=0,cpa=psys->child; p<totchild; p++,cpa++){
cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
cpa->foffset= 0.0f;
cpa->parent=0;
cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
cpa->num= -1;
}
}
}
else {
PARTICLE_P;
LOOP_PARTICLES {
pa->fuv[0]=pa->fuv[1]=pa->fuv[2]= pa->fuv[3]= 0.0;
pa->foffset= 0.0f;
pa->num= -1;
}
}
}
/* Creates a distribution of coordinates on a DerivedMesh */
/* This is to denote functionality that does not yet work with mesh - only derived mesh */
static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, DerivedMesh *finaldm, int from)
{
ParticleThreadContext *ctx= threads[0].ctx;
Object *ob= ctx->sim.ob;
ParticleSystem *psys= ctx->sim.psys;
ParticleData *pa=0, *tpars= 0;
ParticleSettings *part;
ParticleSeam *seams= 0;
KDTree *tree=0;
DerivedMesh *dm= NULL;
float *jit= NULL;
int i, seed, p=0, totthread= threads[0].tot;
int cfrom=0;
int totelem=0, totpart, *particle_element=0, children=0, totseam=0;
int jitlevel= 1, distr;
float *element_weight=NULL,*element_sum=NULL,*jitter_offset=NULL, *vweight=NULL;
float cur, maxweight=0.0, tweight, totweight, inv_totweight, co[3], nor[3], orco[3], ornor[3];
if(ELEM3(NULL, ob, psys, psys->part))
return 0;
part=psys->part;
totpart=psys->totpart;
if(totpart==0)
return 0;
if (!finaldm->deformedOnly && !finaldm->getFaceDataArray(finaldm, CD_ORIGINDEX)) {
printf("Can't create particles with the current modifier stack, disable destructive modifiers\n");
// XXX error("Can't paint with the current modifier stack, disable destructive modifiers");
return 0;
}
/* First handle special cases */
if(from == PART_FROM_CHILD) {
/* Simple children */
if(part->childtype != PART_CHILD_FACES) {
BLI_srandom(31415926 + psys->seed + psys->child_seed);
distribute_simple_children(scene, ob, finaldm, psys);
return 0;
}
}
else {
/* Grid distribution */
if(part->distr==PART_DISTR_GRID && from != PART_FROM_VERT){
BLI_srandom(31415926 + psys->seed);
dm= CDDM_from_mesh((Mesh*)ob->data, ob);
distribute_grid(dm,psys);
dm->release(dm);
return 0;
}
}
/* Create trees and original coordinates if needed */
if(from == PART_FROM_CHILD) {
distr=PART_DISTR_RAND;
BLI_srandom(31415926 + psys->seed + psys->child_seed);
dm= finaldm;
children=1;
tree=BLI_kdtree_new(totpart);
for(p=0,pa=psys->particles; p<totpart; p++,pa++){
psys_particle_on_dm(dm,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,ornor);
transform_mesh_orco_verts((Mesh*)ob->data, &orco, 1, 1);
BLI_kdtree_insert(tree, p, orco, ornor);
}
BLI_kdtree_balance(tree);
totpart = get_psys_tot_child(scene, psys);
cfrom = from = PART_FROM_FACE;
}
else {
distr = part->distr;
BLI_srandom(31415926 + psys->seed);
dm= CDDM_from_mesh((Mesh*)ob->data, ob);
/* we need orco for consistent distributions */
DM_add_vert_layer(dm, CD_ORCO, CD_ASSIGN, get_mesh_orco_verts(ob));
if(from == PART_FROM_VERT) {
MVert *mv= dm->getVertDataArray(dm, CD_MVERT);
float (*orcodata)[3]= dm->getVertDataArray(dm, CD_ORCO);
int totvert = dm->getNumVerts(dm);
tree=BLI_kdtree_new(totvert);
for(p=0; p<totvert; p++) {
if(orcodata) {
VECCOPY(co,orcodata[p])
transform_mesh_orco_verts((Mesh*)ob->data, &co, 1, 1);
}
else
VECCOPY(co,mv[p].co)
BLI_kdtree_insert(tree,p,co,NULL);
}
BLI_kdtree_balance(tree);
}
}
/* Get total number of emission elements and allocate needed arrays */
totelem = (from == PART_FROM_VERT) ? dm->getNumVerts(dm) : dm->getNumFaces(dm);
if(totelem == 0){
distribute_invalid(scene, psys, children ? PART_FROM_CHILD : 0);
if(G.f & G_DEBUG)
fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
if(dm != finaldm) dm->release(dm);
return 0;
}
element_weight = MEM_callocN(sizeof(float)*totelem, "particle_distribution_weights");
particle_element= MEM_callocN(sizeof(int)*totpart, "particle_distribution_indexes");
element_sum = MEM_callocN(sizeof(float)*(totelem+1), "particle_distribution_sum");
jitter_offset = MEM_callocN(sizeof(float)*totelem, "particle_distribution_jitoff");
/* Calculate weights from face areas */
if((part->flag&PART_EDISTR || children) && from != PART_FROM_VERT){
MVert *v1, *v2, *v3, *v4;
float totarea=0.f, co1[3], co2[3], co3[3], co4[3];
float (*orcodata)[3];
orcodata= dm->getVertDataArray(dm, CD_ORCO);
for(i=0; i<totelem; i++){
MFace *mf=dm->getFaceData(dm,i,CD_MFACE);
if(orcodata) {
VECCOPY(co1, orcodata[mf->v1]);
VECCOPY(co2, orcodata[mf->v2]);
VECCOPY(co3, orcodata[mf->v3]);
transform_mesh_orco_verts((Mesh*)ob->data, &co1, 1, 1);
transform_mesh_orco_verts((Mesh*)ob->data, &co2, 1, 1);
transform_mesh_orco_verts((Mesh*)ob->data, &co3, 1, 1);
if(mf->v4) {
VECCOPY(co4, orcodata[mf->v4]);
transform_mesh_orco_verts((Mesh*)ob->data, &co4, 1, 1);
}
}
else {
v1= (MVert*)dm->getVertData(dm,mf->v1,CD_MVERT);
v2= (MVert*)dm->getVertData(dm,mf->v2,CD_MVERT);
v3= (MVert*)dm->getVertData(dm,mf->v3,CD_MVERT);
VECCOPY(co1, v1->co);
VECCOPY(co2, v2->co);
VECCOPY(co3, v3->co);
if(mf->v4) {
v4= (MVert*)dm->getVertData(dm,mf->v4,CD_MVERT);
VECCOPY(co4, v4->co);
}
}
cur = mf->v4 ? area_quad_v3(co1, co2, co3, co4) : area_tri_v3(co1, co2, co3);
if(cur > maxweight)
maxweight = cur;
element_weight[i] = cur;
totarea += cur;
}
for(i=0; i<totelem; i++)
element_weight[i] /= totarea;
maxweight /= totarea;
}
else{
float min=1.0f/(float)(MIN2(totelem,totpart));
for(i=0; i<totelem; i++)
element_weight[i]=min;
maxweight=min;
}
/* Calculate weights from vgroup */
vweight = psys_cache_vgroup(dm,psys,PSYS_VG_DENSITY);
if(vweight){
if(from==PART_FROM_VERT) {
for(i=0;i<totelem; i++)
element_weight[i]*=vweight[i];
}
else { /* PART_FROM_FACE / PART_FROM_VOLUME */
for(i=0;i<totelem; i++){
MFace *mf=dm->getFaceData(dm,i,CD_MFACE);
tweight = vweight[mf->v1] + vweight[mf->v2] + vweight[mf->v3];
if(mf->v4) {
tweight += vweight[mf->v4];
tweight /= 4.0f;
}
else {
tweight /= 3.0f;
}
element_weight[i]*=tweight;
}
}
MEM_freeN(vweight);
}
/* Calculate total weight of all elements */
totweight= 0.0f;
for(i=0;i<totelem; i++)
totweight += element_weight[i];
inv_totweight = (totweight > 0.f ? 1.f/totweight : 0.f);
/* Calculate cumulative weights */
element_sum[0]= 0.0f;
for(i=0; i<totelem; i++)
element_sum[i+1]= element_sum[i] + element_weight[i] * inv_totweight;
/* Finally assign elements to particles */
if((part->flag&PART_TRAND) || (part->simplify_flag&PART_SIMPLIFY_ENABLE)) {
float pos;
for(p=0; p<totpart; p++) {
/* In theory element_sum[totelem] should be 1.0, but due to float errors this is not necessarily always true, so scale pos accordingly. */
pos= BLI_frand() * element_sum[totelem];
particle_element[p]= distribute_binary_search(element_sum, totelem, pos);
particle_element[p]= MIN2(totelem-1, particle_element[p]);
jitter_offset[particle_element[p]]= pos;
}
}
else {
double step, pos;
step= (totpart < 2) ? 0.5 : 1.0/(double)totpart;
pos= 1e-6; /* tiny offset to avoid zero weight face */
i= 0;
for(p=0; p<totpart; p++, pos+=step) {
while((i < totelem) && (pos > element_sum[i+1]))
i++;
particle_element[p]= MIN2(totelem-1, i);
/* avoid zero weight face */
if(p == totpart-1 && element_weight[particle_element[p]] == 0.0f)
particle_element[p]= particle_element[p-1];
jitter_offset[particle_element[p]]= pos;
}
}
MEM_freeN(element_sum);
/* For hair, sort by origindex (allows optimizations in rendering), */
/* however with virtual parents the children need to be in random order. */
if(part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents!=0.0f)) {
COMPARE_ORIG_INDEX = NULL;
if(from == PART_FROM_VERT) {
if(dm->numVertData)
COMPARE_ORIG_INDEX= dm->getVertDataArray(dm, CD_ORIGINDEX);
}
else {
if(dm->numFaceData)
COMPARE_ORIG_INDEX= dm->getFaceDataArray(dm, CD_ORIGINDEX);
}
if(COMPARE_ORIG_INDEX) {
qsort(particle_element, totpart, sizeof(int), distribute_compare_orig_index);
COMPARE_ORIG_INDEX = NULL;
}
}
/* Create jittering if needed */
if(distr==PART_DISTR_JIT && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
jitlevel= part->userjit;
if(jitlevel == 0) {
jitlevel= totpart/totelem;
if(part->flag & PART_EDISTR) jitlevel*= 2; /* looks better in general, not very scietific */
if(jitlevel<3) jitlevel= 3;
}
jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit");
/* for small amounts of particles we use regular jitter since it looks
* a bit better, for larger amounts we switch to hammersley sequence
* because it is much faster */
if(jitlevel < 25)
init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
else
hammersley_create(jit, jitlevel+1, psys->seed, part->jitfac);
BLI_array_randomize(jit, 2*sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */
}
/* Setup things for threaded distribution */
ctx->tree= tree;
ctx->seams= seams;
ctx->totseam= totseam;
ctx->sim.psys= psys;
ctx->index= particle_element;
ctx->jit= jit;
ctx->jitlevel= jitlevel;
ctx->jitoff= jitter_offset;
ctx->weight= element_weight;
ctx->maxweight= maxweight;
ctx->from= (children)? PART_FROM_CHILD: from;
ctx->cfrom= cfrom;
ctx->distr= distr;
ctx->dm= dm;
ctx->tpars= tpars;
if(children) {
totpart= psys_render_simplify_distribution(ctx, totpart);
alloc_child_particles(psys, totpart);
}
if(!children || psys->totchild < 10000)
totthread= 1;
seed= 31415926 + ctx->sim.psys->seed;
for(i=0; i<totthread; i++) {
threads[i].rng= rng_new(seed);
threads[i].tot= totthread;
}
return 1;
}
static void distribute_particles_on_dm(ParticleSimulationData *sim, int from)
{
DerivedMesh *finaldm = sim->psmd->dm;
ListBase threads;
ParticleThread *pthreads;
ParticleThreadContext *ctx;
int i, totthread;
pthreads= psys_threads_create(sim);
if(!distribute_threads_init_data(pthreads, sim->scene, finaldm, from)) {
psys_threads_free(pthreads);
return;
}
totthread= pthreads[0].tot;
if(totthread > 1) {
BLI_init_threads(&threads, distribute_threads_exec_cb, totthread);
for(i=0; i<totthread; i++)
BLI_insert_thread(&threads, &pthreads[i]);
BLI_end_threads(&threads);
}
else
distribute_threads_exec_cb(&pthreads[0]);
psys_calc_dmcache(sim->ob, finaldm, sim->psys);
ctx= pthreads[0].ctx;
if(ctx->dm != finaldm)
ctx->dm->release(ctx->dm);
psys_threads_free(pthreads);
}
/* ready for future use, to emit particles without geometry */
static void distribute_particles_on_shape(ParticleSimulationData *sim, int UNUSED(from))
{
distribute_invalid(sim->scene, sim->psys, 0);
fprintf(stderr,"Shape emission not yet possible!\n");
}
static void distribute_particles(ParticleSimulationData *sim, int from)
{
PARTICLE_PSMD;
int distr_error=0;
if(psmd){
if(psmd->dm)
distribute_particles_on_dm(sim, from);
else
distr_error=1;
}
else
distribute_particles_on_shape(sim, from);
if(distr_error){
distribute_invalid(sim->scene, sim->psys, from);
fprintf(stderr,"Particle distribution error!\n");
}
}
/* threaded child particle distribution and path caching */
ParticleThread *psys_threads_create(ParticleSimulationData *sim)
{
ParticleThread *threads;
ParticleThreadContext *ctx;
int i, totthread;
if(sim->scene->r.mode & R_FIXED_THREADS)
totthread= sim->scene->r.threads;
else
totthread= BLI_system_thread_count();
threads= MEM_callocN(sizeof(ParticleThread)*totthread, "ParticleThread");
ctx= MEM_callocN(sizeof(ParticleThreadContext), "ParticleThreadContext");
ctx->sim = *sim;
ctx->dm= ctx->sim.psmd->dm;
ctx->ma= give_current_material(sim->ob, sim->psys->part->omat);
memset(threads, 0, sizeof(ParticleThread)*totthread);
for(i=0; i<totthread; i++) {
threads[i].ctx= ctx;
threads[i].num= i;
threads[i].tot= totthread;
}
return threads;
}
void psys_threads_free(ParticleThread *threads)
{
ParticleThreadContext *ctx= threads[0].ctx;
int i, totthread= threads[0].tot;
/* path caching */
if(ctx->vg_length)
MEM_freeN(ctx->vg_length);
if(ctx->vg_clump)
MEM_freeN(ctx->vg_clump);
if(ctx->vg_kink)
MEM_freeN(ctx->vg_kink);
if(ctx->vg_rough1)
MEM_freeN(ctx->vg_rough1);
if(ctx->vg_rough2)
MEM_freeN(ctx->vg_rough2);
if(ctx->vg_roughe)
MEM_freeN(ctx->vg_roughe);
if(ctx->sim.psys->lattice){
end_latt_deform(ctx->sim.psys->lattice);
ctx->sim.psys->lattice= NULL;
}
/* distribution */
if(ctx->jit) MEM_freeN(ctx->jit);
if(ctx->jitoff) MEM_freeN(ctx->jitoff);
if(ctx->weight) MEM_freeN(ctx->weight);
if(ctx->index) MEM_freeN(ctx->index);
if(ctx->skip) MEM_freeN(ctx->skip);
if(ctx->seams) MEM_freeN(ctx->seams);
//if(ctx->vertpart) MEM_freeN(ctx->vertpart);
BLI_kdtree_free(ctx->tree);
/* threads */
for(i=0; i<totthread; i++) {
if(threads[i].rng)
rng_free(threads[i].rng);
if(threads[i].rng_path)
rng_free(threads[i].rng_path);
}
MEM_freeN(ctx);
MEM_freeN(threads);
}
/* set particle parameters that don't change during particle's life */
void initialize_particle(ParticleSimulationData *sim, ParticleData *pa, int p)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
ParticleTexture ptex;
pa->flag &= ~PARS_UNEXIST;
if(part->type != PART_FLUID) {
psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f);
if(ptex.exist < PSYS_FRAND(p+125))
pa->flag |= PARS_UNEXIST;
pa->time = (part->type == PART_HAIR) ? 0.f : part->sta + (part->end - part->sta)*ptex.time;
}
pa->hair_index = 0;
/* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
/* usage other than straight after distribute has to handle this index by itself - jahka*/
//pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we dont have a derived mesh face */
}
static void initialize_all_particles(ParticleSimulationData *sim)
{
ParticleSystem *psys = sim->psys;
PARTICLE_P;
psys->totunexist = 0;
LOOP_PARTICLES {
if((pa->flag & PARS_UNEXIST)==0)
initialize_particle(sim, pa, p);
if(pa->flag & PARS_UNEXIST)
psys->totunexist++;
}
/* Free unexisting particles. */
if(psys->totpart && psys->totunexist == psys->totpart) {
if(psys->particles->boid)
MEM_freeN(psys->particles->boid);
MEM_freeN(psys->particles);
psys->particles = NULL;
psys->totpart = psys->totunexist = 0;
}
if(psys->totunexist) {
int newtotpart = psys->totpart - psys->totunexist;
ParticleData *npa, *newpars;
npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles");
for(p=0, pa=psys->particles; p<newtotpart; p++, pa++, npa++) {
while(pa->flag & PARS_UNEXIST)
pa++;
memcpy(npa, pa, sizeof(ParticleData));
}
if(psys->particles->boid)
MEM_freeN(psys->particles->boid);
MEM_freeN(psys->particles);
psys->particles = newpars;
psys->totpart -= psys->totunexist;
if(psys->particles->boid) {
BoidParticle *newboids = MEM_callocN(psys->totpart * sizeof(BoidParticle), "boid particles");
LOOP_PARTICLES
pa->boid = newboids++;
}
}
}
void psys_get_birth_coordinates(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, float dtime, float cfra)
{
Object *ob = sim->ob;
ParticleSystem *psys = sim->psys;
ParticleSettings *part;
ParticleTexture ptex;
float fac, phasefac, nor[3]={0,0,0},loc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4];
float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3]={0.0,0.0,0.0};
float x_vec[3]={1.0,0.0,0.0}, utan[3]={0.0,1.0,0.0}, vtan[3]={0.0,0.0,1.0}, rot_vec[3]={0.0,0.0,0.0};
float q_phase[4];
int p = pa - psys->particles;
part=psys->part;
/* get birth location from object */
if(part->tanfac != 0.f)
psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
else
psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0,0);
/* get possible textural influence */
psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra);
/* particles live in global space so */
/* let's convert: */
/* -location */
mul_m4_v3(ob->obmat, loc);
/* -normal */
mul_mat3_m4_v3(ob->obmat, nor);
normalize_v3(nor);
/* -tangent */
if(part->tanfac!=0.0f){
//float phase=vg_rot?2.0f*(psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
float phase=0.0f;
mul_v3_fl(vtan,-(float)cos((float)M_PI*(part->tanphase+phase)));
fac=-(float)sin((float)M_PI*(part->tanphase+phase));
VECADDFAC(vtan,vtan,utan,fac);
mul_mat3_m4_v3(ob->obmat,vtan);
VECCOPY(utan,nor);
mul_v3_fl(utan,dot_v3v3(vtan,nor));
VECSUB(vtan,vtan,utan);
normalize_v3(vtan);
}
/* -velocity (boids need this even if there's no random velocity) */
if(part->randfac != 0.0f || (part->phystype==PART_PHYS_BOIDS && pa->boid)){
r_vel[0] = 2.0f * (PSYS_FRAND(p + 10) - 0.5f);
r_vel[1] = 2.0f * (PSYS_FRAND(p + 11) - 0.5f);
r_vel[2] = 2.0f * (PSYS_FRAND(p + 12) - 0.5f);
mul_mat3_m4_v3(ob->obmat, r_vel);
normalize_v3(r_vel);
}
/* -angular velocity */
if(part->avemode==PART_AVE_RAND){
r_ave[0] = 2.0f * (PSYS_FRAND(p + 13) - 0.5f);
r_ave[1] = 2.0f * (PSYS_FRAND(p + 14) - 0.5f);
r_ave[2] = 2.0f * (PSYS_FRAND(p + 15) - 0.5f);
mul_mat3_m4_v3(ob->obmat,r_ave);
normalize_v3(r_ave);
}
/* -rotation */
if(part->randrotfac != 0.0f){
r_rot[0] = 2.0f * (PSYS_FRAND(p + 16) - 0.5f);
r_rot[1] = 2.0f * (PSYS_FRAND(p + 17) - 0.5f);
r_rot[2] = 2.0f * (PSYS_FRAND(p + 18) - 0.5f);
r_rot[3] = 2.0f * (PSYS_FRAND(p + 19) - 0.5f);
normalize_qt(r_rot);
mat4_to_quat(rot,ob->obmat);
mul_qt_qtqt(r_rot,r_rot,rot);
}
if(part->phystype==PART_PHYS_BOIDS && pa->boid) {
float dvec[3], q[4], mat[3][3];
copy_v3_v3(state->co,loc);
/* boids don't get any initial velocity */
zero_v3(state->vel);
/* boids store direction in ave */
if(fabsf(nor[2])==1.0f) {
sub_v3_v3v3(state->ave, loc, ob->obmat[3]);
normalize_v3(state->ave);
}
else {
VECCOPY(state->ave, nor);
}
/* calculate rotation matrix */
project_v3_v3v3(dvec, r_vel, state->ave);
sub_v3_v3v3(mat[0], state->ave, dvec);
normalize_v3(mat[0]);
negate_v3_v3(mat[2], r_vel);
normalize_v3(mat[2]);
cross_v3_v3v3(mat[1], mat[2], mat[0]);
/* apply rotation */
mat3_to_quat_is_ok( q,mat);
copy_qt_qt(state->rot, q);
}
else {
/* conversion done so now we apply new: */
/* -velocity from: */
/* *reactions */
if(dtime > 0.f){
sub_v3_v3v3(vel, pa->state.vel, pa->prev_state.vel);
}
/* *emitter velocity */
if(dtime != 0.f && part->obfac != 0.f){
sub_v3_v3v3(vel, loc, state->co);
mul_v3_fl(vel, part->obfac/dtime);
}
/* *emitter normal */
if(part->normfac != 0.f)
madd_v3_v3fl(vel, nor, part->normfac);
/* *emitter tangent */
if(sim->psmd && part->tanfac != 0.f)
madd_v3_v3fl(vel, vtan, part->tanfac);
/* *emitter object orientation */
if(part->ob_vel[0] != 0.f) {
normalize_v3_v3(vec, ob->obmat[0]);
madd_v3_v3fl(vel, vec, part->ob_vel[0]);
}
if(part->ob_vel[1] != 0.f) {
normalize_v3_v3(vec, ob->obmat[1]);
madd_v3_v3fl(vel, vec, part->ob_vel[1]);
}
if(part->ob_vel[2] != 0.f) {
normalize_v3_v3(vec, ob->obmat[2]);
madd_v3_v3fl(vel, vec, part->ob_vel[2]);
}
/* *texture */
/* TODO */
/* *random */
if(part->randfac != 0.f)
madd_v3_v3fl(vel, r_vel, part->randfac);
/* *particle */
if(part->partfac != 0.f)
madd_v3_v3fl(vel, p_vel, part->partfac);
mul_v3_v3fl(state->vel, vel, ptex.ivel);
/* -location from emitter */
copy_v3_v3(state->co,loc);
/* -rotation */
unit_qt(state->rot);
if(part->rotmode){
/* create vector into which rotation is aligned */
switch(part->rotmode){
case PART_ROT_NOR:
copy_v3_v3(rot_vec, nor);
break;
case PART_ROT_VEL:
copy_v3_v3(rot_vec, vel);
break;
case PART_ROT_GLOB_X:
case PART_ROT_GLOB_Y:
case PART_ROT_GLOB_Z:
rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
break;
case PART_ROT_OB_X:
case PART_ROT_OB_Y:
case PART_ROT_OB_Z:
copy_v3_v3(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
break;
}
/* create rotation quat */
negate_v3(rot_vec);
vec_to_quat( q2,rot_vec, OB_POSX, OB_POSZ);
/* randomize rotation quat */
if(part->randrotfac!=0.0f)
interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
else
copy_qt_qt(rot,q2);
/* rotation phase */
phasefac = part->phasefac;
if(part->randphasefac != 0.0f)
phasefac += part->randphasefac * PSYS_FRAND(p + 20);
axis_angle_to_quat( q_phase,x_vec, phasefac*(float)M_PI);
/* combine base rotation & phase */
mul_qt_qtqt(state->rot, rot, q_phase);
}
/* -angular velocity */
zero_v3(state->ave);
if(part->avemode){
switch(part->avemode){
case PART_AVE_SPIN:
copy_v3_v3(state->ave, vel);
break;
case PART_AVE_RAND:
copy_v3_v3(state->ave, r_ave);
break;
}
normalize_v3(state->ave);
mul_v3_fl(state->ave, part->avefac);
}
}
}
/* sets particle to the emitter surface with initial velocity & rotation */
void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, float cfra)
{
Object *ob = sim->ob;
ParticleSystem *psys = sim->psys;
ParticleSettings *part;
ParticleTexture ptex;
int p = pa - psys->particles;
part=psys->part;
/* get precise emitter matrix if particle is born */
if(part->type!=PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) {
/* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */
while(ob) {
BKE_animsys_evaluate_animdata(sim->scene, &ob->id, ob->adt, pa->time, ADT_RECALC_ANIM);
ob = ob->parent;
}
ob = sim->ob;
where_is_object_time(sim->scene, ob, pa->time);
}
psys_get_birth_coordinates(sim, pa, &pa->state, dtime, cfra);
if(part->phystype==PART_PHYS_BOIDS && pa->boid) {
BoidParticle *bpa = pa->boid;
/* and gravity in r_ve */
bpa->gravity[0] = bpa->gravity[1] = 0.0f;
bpa->gravity[2] = -1.0f;
if((sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY)
&& sim->scene->physics_settings.gravity[2]!=0.0f)
bpa->gravity[2] = sim->scene->physics_settings.gravity[2];
bpa->data.health = part->boids->health;
bpa->data.mode = eBoidMode_InAir;
bpa->data.state_id = ((BoidState*)part->boids->states.first)->id;
bpa->data.acc[0]=bpa->data.acc[1]=bpa->data.acc[2]=0.0f;
}
if(part->type == PART_HAIR){
pa->lifetime = 100.0f;
}
else{
/* get possible textural influence */
psys_get_texture(sim, pa, &ptex, PAMAP_LIFE, cfra);
pa->lifetime = part->lifetime * ptex.life;
if(part->randlife != 0.0f)
pa->lifetime *= 1.0f - part->randlife * PSYS_FRAND(p + 21);
}
pa->dietime = pa->time + pa->lifetime;
if(sim->psys->pointcache && sim->psys->pointcache->flag & PTCACHE_BAKED &&
sim->psys->pointcache->mem_cache.first) {
float dietime = psys_get_dietime_from_cache(sim->psys->pointcache, p);
pa->dietime = MIN2(pa->dietime, dietime);
}
if(pa->time > cfra)
pa->alive = PARS_UNBORN;
else if(pa->dietime <= cfra)
pa->alive = PARS_DEAD;
else
pa->alive = PARS_ALIVE;
pa->state.time = cfra;
}
static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
{
ParticleData *pa;
int p, totpart=sim->psys->totpart;
for(p=from, pa=sim->psys->particles+from; p<totpart; p++, pa++)
reset_particle(sim, pa, dtime, cfra);
}
/************************************************/
/* Particle targets */
/************************************************/
ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt)
{
ParticleSystem *psys = NULL;
if(pt->ob == NULL || pt->ob == ob)
psys = BLI_findlink(&ob->particlesystem, pt->psys-1);
else
psys = BLI_findlink(&pt->ob->particlesystem, pt->psys-1);
if(psys)
pt->flag |= PTARGET_VALID;
else
pt->flag &= ~PTARGET_VALID;
return psys;
}
/************************************************/
/* Keyed particles */
/************************************************/
/* Counts valid keyed targets */
void psys_count_keyed_targets(ParticleSimulationData *sim)
{
ParticleSystem *psys = sim->psys, *kpsys;
ParticleTarget *pt = psys->targets.first;
int keys_valid = 1;
psys->totkeyed = 0;
for(; pt; pt=pt->next) {
kpsys = psys_get_target_system(sim->ob, pt);
if(kpsys && kpsys->totpart) {
psys->totkeyed += keys_valid;
if(psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
psys->totkeyed += 1;
}
else {
keys_valid = 0;
}
}
psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
}
static void set_keyed_keys(ParticleSimulationData *sim)
{
ParticleSystem *psys = sim->psys;
ParticleSimulationData ksim= {0};
ParticleTarget *pt;
PARTICLE_P;
ParticleKey *key;
int totpart = psys->totpart, k, totkeys = psys->totkeyed;
int keyed_flag = 0;
ksim.scene= sim->scene;
/* no proper targets so let's clear and bail out */
if(psys->totkeyed==0) {
free_keyed_keys(psys);
psys->flag &= ~PSYS_KEYED;
return;
}
if(totpart && psys->particles->totkey != totkeys) {
free_keyed_keys(psys);
key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
LOOP_PARTICLES {
pa->keys = key;
pa->totkey = totkeys;
key += totkeys;
}
}
psys->flag &= ~PSYS_KEYED;
pt = psys->targets.first;
for(k=0; k<totkeys; k++) {
ksim.ob = pt->ob ? pt->ob : sim->ob;
ksim.psys = BLI_findlink(&ksim.ob->particlesystem, pt->psys - 1);
keyed_flag = (ksim.psys->flag & PSYS_KEYED);
ksim.psys->flag &= ~PSYS_KEYED;
LOOP_PARTICLES {
key = pa->keys + k;
key->time = -1.0; /* use current time */
psys_get_particle_state(&ksim, p%ksim.psys->totpart, key, 1);
if(psys->flag & PSYS_KEYED_TIMING){
key->time = pa->time + pt->time;
if(pt->duration != 0.0f && k+1 < totkeys) {
copy_particle_key(key+1, key, 1);
(key+1)->time = pa->time + pt->time + pt->duration;
}
}
else if(totkeys > 1)
key->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
else
key->time = pa->time;
}
if(psys->flag & PSYS_KEYED_TIMING && pt->duration!=0.0f)
k++;
ksim.psys->flag |= keyed_flag;
pt = (pt->next && pt->next->flag & PTARGET_VALID)? pt->next : psys->targets.first;
}
psys->flag |= PSYS_KEYED;
}
/************************************************/
/* Point Cache */
/************************************************/
void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys)
{
PointCache *cache = psys->pointcache;
if(cache->flag & PTCACHE_DISK_CACHE && cache->mem_cache.first == NULL) {
PTCacheID pid;
BKE_ptcache_id_from_particles(&pid, ob, psys);
cache->flag &= ~PTCACHE_DISK_CACHE;
BKE_ptcache_disk_to_mem(&pid);
cache->flag |= PTCACHE_DISK_CACHE;
}
}
static void psys_clear_temp_pointcache(ParticleSystem *psys)
{
if(psys->pointcache->flag & PTCACHE_DISK_CACHE)
BKE_ptcache_free_mem(&psys->pointcache->mem_cache);
}
void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
{
ParticleSettings *part = psys->part;
*sfra = MAX2(1, (int)part->sta);
*efra = MIN2((int)(part->end + part->lifetime + 1.0f), scene->r.efra);
}
/************************************************/
/* Effectors */
/************************************************/
static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra)
{
if(psys) {
PARTICLE_P;
int totpart = 0;
if(!psys->bvhtree || psys->bvhtree_frame != cfra) {
LOOP_SHOWN_PARTICLES {
totpart++;
}
BLI_bvhtree_free(psys->bvhtree);
psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6);
LOOP_SHOWN_PARTICLES {
if(pa->alive == PARS_ALIVE) {
if(pa->state.time == cfra)
BLI_bvhtree_insert(psys->bvhtree, p, pa->prev_state.co, 1);
else
BLI_bvhtree_insert(psys->bvhtree, p, pa->state.co, 1);
}
}
BLI_bvhtree_balance(psys->bvhtree);
psys->bvhtree_frame = cfra;
}
}
}
void psys_update_particle_tree(ParticleSystem *psys, float cfra)
{
if(psys) {
PARTICLE_P;
int totpart = 0;
if(!psys->tree || psys->tree_frame != cfra) {
LOOP_SHOWN_PARTICLES {
totpart++;
}
BLI_kdtree_free(psys->tree);
psys->tree = BLI_kdtree_new(psys->totpart);
LOOP_SHOWN_PARTICLES {
if(pa->alive == PARS_ALIVE) {
if(pa->state.time == cfra)
BLI_kdtree_insert(psys->tree, p, pa->prev_state.co, NULL);
else
BLI_kdtree_insert(psys->tree, p, pa->state.co, NULL);
}
}
BLI_kdtree_balance(psys->tree);
psys->tree_frame = cfra;
}
}
}
static void psys_update_effectors(ParticleSimulationData *sim)
{
pdEndEffectors(&sim->psys->effectors);
sim->psys->effectors = pdInitEffectors(sim->scene, sim->ob, sim->psys, sim->psys->part->effector_weights);
precalc_guides(sim, sim->psys->effectors);
}
static void integrate_particle(ParticleSettings *part, ParticleData *pa, float dtime, float *external_acceleration, void (*force_func)(void *forcedata, ParticleKey *state, float *force, float *impulse), void *forcedata)
{
ParticleKey states[5];
float force[3],acceleration[3],impulse[3],dx[4][3],dv[4][3],oldpos[3];
float pa_mass= (part->flag & PART_SIZEMASS ? part->mass * pa->size : part->mass);
int i, steps=1;
int integrator = part->integrator;
copy_v3_v3(oldpos, pa->state.co);
/* Verlet integration behaves strangely with moving emitters, so do first step with euler. */
if(pa->prev_state.time < 0.f && integrator == PART_INT_VERLET)
integrator = PART_INT_EULER;
switch(integrator){
case PART_INT_EULER:
steps=1;
break;
case PART_INT_MIDPOINT:
steps=2;
break;
case PART_INT_RK4:
steps=4;
break;
case PART_INT_VERLET:
steps=1;
break;
}
copy_particle_key(states, &pa->state, 1);
states->time = 0.f;
for(i=0; i<steps; i++){
zero_v3(force);
zero_v3(impulse);
force_func(forcedata, states+i, force, impulse);
/* force to acceleration*/
mul_v3_v3fl(acceleration, force, 1.0f/pa_mass);
if(external_acceleration)
add_v3_v3(acceleration, external_acceleration);
/* calculate next state */
add_v3_v3(states[i].vel, impulse);
switch(integrator){
case PART_INT_EULER:
madd_v3_v3v3fl(pa->state.co, states->co, states->vel, dtime);
madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
break;
case PART_INT_MIDPOINT:
if(i==0){
madd_v3_v3v3fl(states[1].co, states->co, states->vel, dtime*0.5f);
madd_v3_v3v3fl(states[1].vel, states->vel, acceleration, dtime*0.5f);
states[1].time = dtime*0.5f;
/*fra=sim->psys->cfra+0.5f*dfra;*/
}
else{
madd_v3_v3v3fl(pa->state.co, states->co, states[1].vel, dtime);
madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
}
break;
case PART_INT_RK4:
switch(i){
case 0:
copy_v3_v3(dx[0], states->vel);
mul_v3_fl(dx[0], dtime);
copy_v3_v3(dv[0], acceleration);
mul_v3_fl(dv[0], dtime);
madd_v3_v3v3fl(states[1].co, states->co, dx[0], 0.5f);
madd_v3_v3v3fl(states[1].vel, states->vel, dv[0], 0.5f);
states[1].time = dtime*0.5f;
/*fra=sim->psys->cfra+0.5f*dfra;*/
break;
case 1:
madd_v3_v3v3fl(dx[1], states->vel, dv[0], 0.5f);
mul_v3_fl(dx[1], dtime);
copy_v3_v3(dv[1], acceleration);
mul_v3_fl(dv[1], dtime);
madd_v3_v3v3fl(states[2].co, states->co, dx[1], 0.5f);
madd_v3_v3v3fl(states[2].vel, states->vel, dv[1], 0.5f);
states[2].time = dtime*0.5f;
break;
case 2:
madd_v3_v3v3fl(dx[2], states->vel, dv[1], 0.5f);
mul_v3_fl(dx[2], dtime);
copy_v3_v3(dv[2], acceleration);
mul_v3_fl(dv[2], dtime);
add_v3_v3v3(states[3].co, states->co, dx[2]);
add_v3_v3v3(states[3].vel, states->vel, dv[2]);
states[3].time = dtime;
/*fra=cfra;*/
break;
case 3:
add_v3_v3v3(dx[3], states->vel, dv[2]);
mul_v3_fl(dx[3], dtime);
copy_v3_v3(dv[3], acceleration);
mul_v3_fl(dv[3], dtime);
madd_v3_v3v3fl(pa->state.co, states->co, dx[0], 1.0f/6.0f);
madd_v3_v3fl(pa->state.co, dx[1], 1.0f/3.0f);
madd_v3_v3fl(pa->state.co, dx[2], 1.0f/3.0f);
madd_v3_v3fl(pa->state.co, dx[3], 1.0f/6.0f);
madd_v3_v3v3fl(pa->state.vel, states->vel, dv[0], 1.0f/6.0f);
madd_v3_v3fl(pa->state.vel, dv[1], 1.0f/3.0f);
madd_v3_v3fl(pa->state.vel, dv[2], 1.0f/3.0f);
madd_v3_v3fl(pa->state.vel, dv[3], 1.0f/6.0f);
}
break;
case PART_INT_VERLET: /* Verlet integration */
madd_v3_v3v3fl(pa->state.vel, pa->prev_state.vel, acceleration, dtime);
madd_v3_v3v3fl(pa->state.co, pa->prev_state.co, pa->state.vel, dtime);
sub_v3_v3v3(pa->state.vel, pa->state.co, oldpos);
mul_v3_fl(pa->state.vel, 1.0f/dtime);
break;
}
}
}
/*********************************************************************************************************
SPH fluid physics
In theory, there could be unlimited implementation of SPH simulators
This code uses in some parts adapted algorithms from the pseudo code as outlined in the Research paper:
Titled: Particle-based Viscoelastic Fluid Simulation.
Authors: Simon Clavet, Philippe Beaudoin and Pierre Poulin
Website: http://www.iro.umontreal.ca/labs/infographie/papers/Clavet-2005-PVFS/
Presented at Siggraph, (2005)
***********************************************************************************************************/
#define PSYS_FLUID_SPRINGS_INITIAL_SIZE 256
static ParticleSpring *sph_spring_add(ParticleSystem *psys, ParticleSpring *spring)
{
/* Are more refs required? */
if(psys->alloc_fluidsprings == 0 || psys->fluid_springs == NULL) {
psys->alloc_fluidsprings = PSYS_FLUID_SPRINGS_INITIAL_SIZE;
psys->fluid_springs = (ParticleSpring*)MEM_callocN(psys->alloc_fluidsprings * sizeof(ParticleSpring), "Particle Fluid Springs");
}
else if(psys->tot_fluidsprings == psys->alloc_fluidsprings) {
/* Double the number of refs allocated */
psys->alloc_fluidsprings *= 2;
psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring));
}
memcpy(psys->fluid_springs + psys->tot_fluidsprings, spring, sizeof(ParticleSpring));
psys->tot_fluidsprings++;
return psys->fluid_springs + psys->tot_fluidsprings - 1;
}
static void sph_spring_delete(ParticleSystem *psys, int j)
{
if (j != psys->tot_fluidsprings - 1)
psys->fluid_springs[j] = psys->fluid_springs[psys->tot_fluidsprings - 1];
psys->tot_fluidsprings--;
if (psys->tot_fluidsprings < psys->alloc_fluidsprings/2 && psys->alloc_fluidsprings > PSYS_FLUID_SPRINGS_INITIAL_SIZE){
psys->alloc_fluidsprings /= 2;
psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring));
}
}
static void sph_springs_modify(ParticleSystem *psys, float dtime){
SPHFluidSettings *fluid = psys->part->fluid;
ParticleData *pa1, *pa2;
ParticleSpring *spring = psys->fluid_springs;
float h, d, Rij[3], rij, Lij;
int i;
float yield_ratio = fluid->yield_ratio;
float plasticity = fluid->plasticity_constant;
/* scale things according to dtime */
float timefix = 25.f * dtime;
if((fluid->flag & SPH_VISCOELASTIC_SPRINGS)==0 || fluid->spring_k == 0.f)
return;
/* Loop through the springs */
for(i=0; i<psys->tot_fluidsprings; i++, spring++) {
pa1 = psys->particles + spring->particle_index[0];
pa2 = psys->particles + spring->particle_index[1];
sub_v3_v3v3(Rij, pa2->prev_state.co, pa1->prev_state.co);
rij = normalize_v3(Rij);
/* adjust rest length */
Lij = spring->rest_length;
d = yield_ratio * timefix * Lij;
if (rij > Lij + d) // Stretch
spring->rest_length += plasticity * (rij - Lij - d) * timefix;
else if(rij < Lij - d) // Compress
spring->rest_length -= plasticity * (Lij - d - rij) * timefix;
h = 4.f*pa1->size;
if(spring->rest_length > h)
spring->delete_flag = 1;
}
/* Loop through springs backwaqrds - for efficient delete function */
for (i=psys->tot_fluidsprings-1; i >= 0; i--) {
if(psys->fluid_springs[i].delete_flag)
sph_spring_delete(psys, i);
}
}
static EdgeHash *sph_springhash_build(ParticleSystem *psys)
{
EdgeHash *springhash = NULL;
ParticleSpring *spring;
int i = 0;
springhash = BLI_edgehash_new();
for(i=0, spring=psys->fluid_springs; i<psys->tot_fluidsprings; i++, spring++)
BLI_edgehash_insert(springhash, spring->particle_index[0], spring->particle_index[1], SET_INT_IN_POINTER(i+1));
return springhash;
}
typedef struct SPHNeighbor
{
ParticleSystem *psys;
int index;
} SPHNeighbor;
typedef struct SPHRangeData
{
SPHNeighbor neighbors[128];
int tot_neighbors;
float density, near_density;
float h;
ParticleSystem *npsys;
ParticleData *pa;
float massfac;
int use_size;
/* Same as SPHData::element_size */
float element_size;
float flow[3];
} SPHRangeData;
typedef struct SPHData {
ParticleSystem *psys[10];
ParticleData *pa;
float mass;
EdgeHash *eh;
float *gravity;
/* Average distance to neighbours (other particles in the support domain),
for calculating the Courant number (adaptive time step). */
float element_size;
float flow[3];
}SPHData;
static void sph_density_accum_cb(void *userdata, int index, float squared_dist)
{
SPHRangeData *pfr = (SPHRangeData *)userdata;
ParticleData *npa = pfr->npsys->particles + index;
float q;
float dist;
if(npa == pfr->pa || squared_dist < FLT_EPSILON)
return;
/* Ugh! One particle has over 128 neighbors! Really shouldn't happen,
* but even if it does it shouldn't do any terrible harm if all are
* not taken into account - jahka
*/
if(pfr->tot_neighbors >= 128)
return;
pfr->neighbors[pfr->tot_neighbors].index = index;
pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
pfr->tot_neighbors++;
dist = sqrtf(squared_dist);
q = (1.f - dist/pfr->h) * pfr->massfac;
add_v3_v3(pfr->flow, npa->state.vel);
pfr->element_size += dist;
if(pfr->use_size)
q *= npa->size;
pfr->density += q*q;
pfr->near_density += q*q*q;
}
static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
{
SPHData *sphdata = (SPHData *)sphdata_v;
ParticleSystem **psys = sphdata->psys;
ParticleData *pa = sphdata->pa;
SPHFluidSettings *fluid = psys[0]->part->fluid;
ParticleSpring *spring = NULL;
SPHRangeData pfr;
SPHNeighbor *pfn;
float mass = sphdata->mass;
float *gravity = sphdata->gravity;
EdgeHash *springhash = sphdata->eh;
float q, u, rij, dv[3];
float pressure, near_pressure;
float visc = fluid->viscosity_omega;
float stiff_visc = fluid->viscosity_beta * (fluid->flag & SPH_FAC_VISCOSITY ? fluid->viscosity_omega : 1.f);
float inv_mass = 1.0f/mass;
float spring_constant = fluid->spring_k;
float h = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.f*pa->size : 1.f); /* 4.0 seems to be a pretty good value */
float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.f); /* 4.77 is an experimentally determined density factor */
float rest_length = fluid->rest_length * (fluid->flag & SPH_FAC_REST_LENGTH ? 2.588f * pa->size : 1.f);
float stiffness = fluid->stiffness_k;
float stiffness_near_fac = fluid->stiffness_knear * (fluid->flag & SPH_FAC_REPULSION ? fluid->stiffness_k : 1.f);
ParticleData *npa;
float vec[3];
float vel[3];
float co[3];
int i, spring_index, index = pa - psys[0]->particles;
pfr.tot_neighbors = 0;
pfr.density = pfr.near_density = 0.f;
pfr.h = h;
pfr.pa = pa;
pfr.element_size = fluid->radius;
pfr.flow[0] = pfr.flow[1] = pfr.flow[2] = 0.0f;
for(i=0; i<10 && psys[i]; i++) {
pfr.npsys = psys[i];
pfr.massfac = psys[i]->part->mass*inv_mass;
pfr.use_size = psys[i]->part->flag & PART_SIZEMASS;
BLI_bvhtree_range_query(psys[i]->bvhtree, state->co, h, sph_density_accum_cb, &pfr);
}
if (pfr.tot_neighbors > 0) {
pfr.element_size /= pfr.tot_neighbors;
mul_v3_fl(pfr.flow, 1.0f / pfr.tot_neighbors);
} else {
pfr.element_size = MAXFLOAT;
}
sphdata->element_size = pfr.element_size;
VECCOPY(sphdata->flow, pfr.flow);
pressure = stiffness * (pfr.density - rest_density);
near_pressure = stiffness_near_fac * pfr.near_density;
pfn = pfr.neighbors;
for(i=0; i<pfr.tot_neighbors; i++, pfn++) {
npa = pfn->psys->particles + pfn->index;
madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
sub_v3_v3v3(vec, co, state->co);
rij = normalize_v3(vec);
q = (1.f - rij/h) * pfn->psys->part->mass * inv_mass;
if(pfn->psys->part->flag & PART_SIZEMASS)
q *= npa->size;
copy_v3_v3(vel, npa->prev_state.vel);
/* Double Density Relaxation */
madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q);
/* Viscosity */
if(visc > 0.f || stiff_visc > 0.f) {
sub_v3_v3v3(dv, vel, state->vel);
u = dot_v3v3(vec, dv);
if(u < 0.f && visc > 0.f)
madd_v3_v3fl(force, vec, 0.5f * q * visc * u );
if(u > 0.f && stiff_visc > 0.f)
madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u );
}
if(spring_constant > 0.f) {
/* Viscoelastic spring force */
if (pfn->psys == psys[0] && fluid->flag & SPH_VISCOELASTIC_SPRINGS && springhash) {
spring_index = GET_INT_FROM_POINTER(BLI_edgehash_lookup(springhash, index, pfn->index));
if(spring_index) {
spring = psys[0]->fluid_springs + spring_index - 1;
madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (spring->rest_length - rij));
}
else if(fluid->spring_frames == 0 || (pa->prev_state.time-pa->time) <= fluid->spring_frames){
ParticleSpring temp_spring;
temp_spring.particle_index[0] = index;
temp_spring.particle_index[1] = pfn->index;
temp_spring.rest_length = (fluid->flag & SPH_CURRENT_REST_LENGTH) ? rij : rest_length;
temp_spring.delete_flag = 0;
sph_spring_add(psys[0], &temp_spring);
}
}
else {/* PART_SPRING_HOOKES - Hooke's spring force */
madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (rest_length - rij));
}
}
}
/* Artificial buoyancy force in negative gravity direction */
if (fluid->buoyancy > 0.f && gravity)
madd_v3_v3fl(force, gravity, fluid->buoyancy * (pfr.density-rest_density));
}
static void sph_integrate(ParticleSimulationData *sim, ParticleData *pa, float dfra, float *gravity, EdgeHash *springhash, float *element_size, float flow[3]) {
ParticleTarget *pt;
int i;
ParticleSettings *part = sim->psys->part;
// float timestep = psys_get_timestep(sim); // UNUSED
float pa_mass = part->mass * (part->flag & PART_SIZEMASS ? pa->size : 1.f);
float dtime = dfra*psys_get_timestep(sim);
// int steps = 1; // UNUSED
float effector_acceleration[3];
SPHData sphdata;
sphdata.psys[0] = sim->psys;
for(i=1, pt=sim->psys->targets.first; i<10; i++, pt=(pt?pt->next:NULL))
sphdata.psys[i] = pt ? psys_get_target_system(sim->ob, pt) : NULL;
sphdata.pa = pa;
sphdata.gravity = gravity;
sphdata.mass = pa_mass;
sphdata.eh = springhash;
//sphdata.element_size and sphdata.flow are set in the callback.
/* restore previous state and treat gravity & effectors as external acceleration*/
sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel);
mul_v3_fl(effector_acceleration, 1.f/dtime);
copy_particle_key(&pa->state, &pa->prev_state, 0);
integrate_particle(part, pa, dtime, effector_acceleration, sph_force_cb, &sphdata);
*element_size = sphdata.element_size;
VECCOPY(flow, sphdata.flow);
}
/************************************************/
/* Basic physics */
/************************************************/
typedef struct EfData
{
ParticleTexture ptex;
ParticleSimulationData *sim;
ParticleData *pa;
} EfData;
static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
{
EfData *efdata = (EfData *)efdata_v;
ParticleSimulationData *sim = efdata->sim;
ParticleSettings *part = sim->psys->part;
ParticleData *pa = efdata->pa;
EffectedPoint epoint;
/* add effectors */
pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint);
if(part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)
pdDoEffectors(sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse);
mul_v3_fl(force, efdata->ptex.field);
mul_v3_fl(impulse, efdata->ptex.field);
/* calculate air-particle interaction */
if(part->dragfac != 0.0f)
madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel));
/* brownian force */
if(part->brownfac != 0.0f){
force[0] += (BLI_frand()-0.5f) * part->brownfac;
force[1] += (BLI_frand()-0.5f) * part->brownfac;
force[2] += (BLI_frand()-0.5f) * part->brownfac;
}
}
/* gathers all forces that effect particles and calculates a new state for the particle */
static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
{
ParticleSettings *part = sim->psys->part;
ParticleData *pa = sim->psys->particles + p;
ParticleKey tkey;
float dtime=dfra*psys_get_timestep(sim), time;
float *gravity = NULL, gr[3];
EfData efdata;
psys_get_texture(sim, pa, &efdata.ptex, PAMAP_PHYSICS, cfra);
efdata.pa = pa;
efdata.sim = sim;
/* add global acceleration (gravitation) */
if(psys_uses_gravity(sim)
/* normal gravity is too strong for hair so it's disabled by default */
&& (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)) {
zero_v3(gr);
madd_v3_v3fl(gr, sim->scene->physics_settings.gravity, part->effector_weights->global_gravity * efdata.ptex.gravity);
gravity = gr;
}
/* maintain angular velocity */
copy_v3_v3(pa->state.ave, pa->prev_state.ave);
integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata);
/* damp affects final velocity */
if(part->dampfac != 0.f)
mul_v3_fl(pa->state.vel, 1.f - part->dampfac * efdata.ptex.damp * 25.f * dtime);
//VECCOPY(pa->state.ave, states->ave);
/* finally we do guides */
time=(cfra-pa->time)/pa->lifetime;
CLAMP(time, 0.0f, 1.0f);
VECCOPY(tkey.co,pa->state.co);
VECCOPY(tkey.vel,pa->state.vel);
tkey.time=pa->state.time;
if(part->type != PART_HAIR) {
if(do_guides(sim->psys->effectors, &tkey, p, time)) {
VECCOPY(pa->state.co,tkey.co);
/* guides don't produce valid velocity */
VECSUB(pa->state.vel,tkey.co,pa->prev_state.co);
mul_v3_fl(pa->state.vel,1.0f/dtime);
pa->state.time=tkey.time;
}
}
}
static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
{
float rotfac, rot1[4], rot2[4]={1.0,0.0,0.0,0.0}, dtime=dfra*timestep;
if((part->flag & PART_ROT_DYN)==0){
if(part->avemode==PART_AVE_SPIN){
float angle;
float len1 = len_v3(pa->prev_state.vel);
float len2 = len_v3(pa->state.vel);
if(len1==0.0f || len2==0.0f)
pa->state.ave[0]=pa->state.ave[1]=pa->state.ave[2]=0.0f;
else{
cross_v3_v3v3(pa->state.ave,pa->prev_state.vel,pa->state.vel);
normalize_v3(pa->state.ave);
angle=dot_v3v3(pa->prev_state.vel,pa->state.vel)/(len1*len2);
mul_v3_fl(pa->state.ave,saacos(angle)/dtime);
}
axis_angle_to_quat(rot2,pa->state.vel,dtime*part->avefac);
}
}
rotfac=len_v3(pa->state.ave);
if(rotfac == 0.0f){ /* unit_qt(in VecRotToQuat) doesn't give unit quat [1,0,0,0]?? */
rot1[0]=1.0f;
rot1[1]=rot1[2]=rot1[3]=0;
}
else{
axis_angle_to_quat(rot1,pa->state.ave,rotfac*dtime);
}
mul_qt_qtqt(pa->state.rot,rot1,pa->prev_state.rot);
mul_qt_qtqt(pa->state.rot,rot2,pa->state.rot);
/* keep rotation quat in good health */
normalize_qt(pa->state.rot);
}
/************************************************/
/* Collisions */
/************************************************/
#define COLLISION_MAX_COLLISIONS 10
#define COLLISION_MIN_RADIUS 0.001f
#define COLLISION_MIN_DISTANCE 0.0001f
#define COLLISION_ZERO 0.00001f
typedef float (*NRDistanceFunc)(float *p, float radius, ParticleCollisionElement *pce, float *nor);
static float nr_signed_distance_to_plane(float *p, float radius, ParticleCollisionElement *pce, float *nor)
{
float p0[3], e1[3], e2[3], d;
sub_v3_v3v3(e1, pce->x1, pce->x0);
sub_v3_v3v3(e2, pce->x2, pce->x0);
sub_v3_v3v3(p0, p, pce->x0);
cross_v3_v3v3(nor, e1, e2);
normalize_v3(nor);
d = dot_v3v3(p0, nor);
if(pce->inv_nor == -1) {
if(d < 0.f)
pce->inv_nor = 1;
else
pce->inv_nor = 0;
}
if(pce->inv_nor == 1) {
mul_v3_fl(nor, -1.f);
d = -d;
}
return d - radius;
}
static float nr_distance_to_edge(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
{
float v0[3], v1[3], v2[3], c[3];
sub_v3_v3v3(v0, pce->x1, pce->x0);
sub_v3_v3v3(v1, p, pce->x0);
sub_v3_v3v3(v2, p, pce->x1);
cross_v3_v3v3(c, v1, v2);
return fabsf(len_v3(c)/len_v3(v0)) - radius;
}
static float nr_distance_to_vert(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
{
return len_v3v3(p, pce->x0) - radius;
}
static void collision_interpolate_element(ParticleCollisionElement *pce, float t, float fac, ParticleCollision *col)
{
/* t is the current time for newton rhapson */
/* fac is the starting factor for current collision iteration */
/* the col->fac's are factors for the particle subframe step start and end during collision modifier step */
float f = fac + t*(1.f-fac);
float mul = col->fac1 + f * (col->fac2-col->fac1);
if(pce->tot > 0) {
madd_v3_v3v3fl(pce->x0, pce->x[0], pce->v[0], mul);
if(pce->tot > 1) {
madd_v3_v3v3fl(pce->x1, pce->x[1], pce->v[1], mul);
if(pce->tot > 2)
madd_v3_v3v3fl(pce->x2, pce->x[2], pce->v[2], mul);
}
}
}
static void collision_point_velocity(ParticleCollisionElement *pce)
{
float v[3];
copy_v3_v3(pce->vel, pce->v[0]);
if(pce->tot > 1) {
sub_v3_v3v3(v, pce->v[1], pce->v[0]);
madd_v3_v3fl(pce->vel, v, pce->uv[0]);
if(pce->tot > 2) {
sub_v3_v3v3(v, pce->v[2], pce->v[0]);
madd_v3_v3fl(pce->vel, v, pce->uv[1]);
}
}
}
static float collision_point_distance_with_normal(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor)
{
if(fac >= 0.f)
collision_interpolate_element(pce, 0.f, fac, col);
switch(pce->tot) {
case 1:
{
sub_v3_v3v3(nor, p, pce->x0);
return normalize_v3(nor);
}
case 2:
{
float u, e[3], vec[3];
sub_v3_v3v3(e, pce->x1, pce->x0);
sub_v3_v3v3(vec, p, pce->x0);
u = dot_v3v3(vec, e) / dot_v3v3(e, e);
madd_v3_v3v3fl(nor, vec, e, -u);
return normalize_v3(nor);
}
case 3:
return nr_signed_distance_to_plane(p, 0.f, pce, nor);
}
return 0;
}
static void collision_point_on_surface(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *co)
{
collision_interpolate_element(pce, 0.f, fac, col);
switch(pce->tot) {
case 1:
{
sub_v3_v3v3(co, p, pce->x0);
normalize_v3(co);
madd_v3_v3v3fl(co, pce->x0, co, col->radius);
break;
}
case 2:
{
float u, e[3], vec[3], nor[3];
sub_v3_v3v3(e, pce->x1, pce->x0);
sub_v3_v3v3(vec, p, pce->x0);
u = dot_v3v3(vec, e) / dot_v3v3(e, e);
madd_v3_v3v3fl(nor, vec, e, -u);
normalize_v3(nor);
madd_v3_v3v3fl(co, pce->x0, e, pce->uv[0]);
madd_v3_v3fl(co, nor, col->radius);
break;
}
case 3:
{
float p0[3], e1[3], e2[3], nor[3];
sub_v3_v3v3(e1, pce->x1, pce->x0);
sub_v3_v3v3(e2, pce->x2, pce->x0);
sub_v3_v3v3(p0, p, pce->x0);
cross_v3_v3v3(nor, e1, e2);
normalize_v3(nor);
if(pce->inv_nor == 1)
mul_v3_fl(nor, -1.f);
madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
madd_v3_v3fl(co, e1, pce->uv[0]);
madd_v3_v3fl(co, e2, pce->uv[1]);
break;
}
}
}
/* find first root in range [0-1] starting from 0 */
static float collision_newton_rhapson(ParticleCollision *col, float radius, ParticleCollisionElement *pce, NRDistanceFunc distance_func)
{
float t0, t1, d0, d1, dd, n[3];
int iter;
pce->inv_nor = -1;
/* start from the beginning */
t0 = 0.f;
collision_interpolate_element(pce, t0, col->f, col);
d0 = distance_func(col->co1, radius, pce, n);
t1 = 0.001f;
d1 = 0.f;
for(iter=0; iter<10; iter++) {//, itersum++) {
/* get current location */
collision_interpolate_element(pce, t1, col->f, col);
interp_v3_v3v3(pce->p, col->co1, col->co2, t1);
d1 = distance_func(pce->p, radius, pce, n);
/* no movement, so no collision */
if(d1 == d0) {
return -1.f;
}
/* particle already inside face, so report collision */
if(iter == 0 && d0 < 0.f && d0 > -radius) {
copy_v3_v3(pce->p, col->co1);
copy_v3_v3(pce->nor, n);
pce->inside = 1;
return 0.f;
}
dd = (t1-t0)/(d1-d0);
t0 = t1;
d0 = d1;
t1 -= d1*dd;
/* particle movin away from plane could also mean a strangely rotating face, so check from end */
if(iter == 0 && t1 < 0.f) {
t0 = 1.f;
collision_interpolate_element(pce, t0, col->f, col);
d0 = distance_func(col->co2, radius, pce, n);
t1 = 0.999f;
d1 = 0.f;
continue;
}
else if(iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.f))
return -1.f;
if(d1 <= COLLISION_ZERO && d1 >= -COLLISION_ZERO) {
if(t1 >= -COLLISION_ZERO && t1 <= 1.f) {
if(distance_func == nr_signed_distance_to_plane)
copy_v3_v3(pce->nor, n);
CLAMP(t1, 0.f, 1.f);
return t1;
}
else
return -1.f;
}
}
return -1.0;
}
static int collision_sphere_to_tri(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
{
ParticleCollisionElement *result = &col->pce;
float ct, u, v;
pce->inv_nor = -1;
pce->inside = 0;
ct = collision_newton_rhapson(col, radius, pce, nr_signed_distance_to_plane);
if(ct >= 0.f && ct < *t && (result->inside==0 || pce->inside==1) ) {
float e1[3], e2[3], p0[3];
float e1e1, e1e2, e1p0, e2e2, e2p0, inv;
sub_v3_v3v3(e1, pce->x1, pce->x0);
sub_v3_v3v3(e2, pce->x2, pce->x0);
/* XXX: add radius correction here? */
sub_v3_v3v3(p0, pce->p, pce->x0);
e1e1 = dot_v3v3(e1, e1);
e1e2 = dot_v3v3(e1, e2);
e1p0 = dot_v3v3(e1, p0);
e2e2 = dot_v3v3(e2, e2);
e2p0 = dot_v3v3(e2, p0);
inv = 1.f/(e1e1 * e2e2 - e1e2 * e1e2);
u = (e2e2 * e1p0 - e1e2 * e2p0) * inv;
v = (e1e1 * e2p0 - e1e2 * e1p0) * inv;
if(u>=0.f && u<=1.f && v>=0.f && u+v<=1.f) {
*result = *pce;
/* normal already calculated in pce */
result->uv[0] = u;
result->uv[1] = v;
*t = ct;
return 1;
}
}
return 0;
}
static int collision_sphere_to_edges(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
{
ParticleCollisionElement edge[3], *cur = NULL, *hit = NULL;
ParticleCollisionElement *result = &col->pce;
float ct;
int i;
for(i=0; i<3; i++) {
/* in case of a quad, no need to check "edge" that goes through face twice */
if((pce->x[3] && i==2))
continue;
cur = edge+i;
cur->x[0] = pce->x[i]; cur->x[1] = pce->x[(i+1)%3];
cur->v[0] = pce->v[i]; cur->v[1] = pce->v[(i+1)%3];
cur->tot = 2;
cur->inside = 0;
ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_edge);
if(ct >= 0.f && ct < *t) {
float u, e[3], vec[3];
sub_v3_v3v3(e, cur->x1, cur->x0);
sub_v3_v3v3(vec, cur->p, cur->x0);
u = dot_v3v3(vec, e) / dot_v3v3(e, e);
if(u < 0.f || u > 1.f)
break;
*result = *cur;
madd_v3_v3v3fl(result->nor, vec, e, -u);
normalize_v3(result->nor);
result->uv[0] = u;
hit = cur;
*t = ct;
}
}
return hit != NULL;
}
static int collision_sphere_to_verts(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
{
ParticleCollisionElement vert[3], *cur = NULL, *hit = NULL;
ParticleCollisionElement *result = &col->pce;
float ct;
int i;
for(i=0; i<3; i++) {
/* in case of quad, only check one vert the first time */
if(pce->x[3] && i != 1)
continue;
cur = vert+i;
cur->x[0] = pce->x[i];
cur->v[0] = pce->v[i];
cur->tot = 1;
cur->inside = 0;
ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert);
if(ct >= 0.f && ct < *t) {
*result = *cur;
sub_v3_v3v3(result->nor, cur->p, cur->x0);
normalize_v3(result->nor);
hit = cur;
*t = ct;
}
}
return hit != NULL;
}
/* Callback for BVHTree near test */
void BKE_psys_collision_neartest_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
{
ParticleCollision *col = (ParticleCollision *) userdata;
ParticleCollisionElement pce;
MFace *face = col->md->mfaces + index;
MVert *x = col->md->x;
MVert *v = col->md->current_v;
float t = hit->dist/col->original_ray_length;
int collision = 0;
pce.x[0] = x[face->v1].co;
pce.x[1] = x[face->v2].co;
pce.x[2] = x[face->v3].co;
pce.x[3] = face->v4 ? x[face->v4].co : NULL;
pce.v[0] = v[face->v1].co;
pce.v[1] = v[face->v2].co;
pce.v[2] = v[face->v3].co;
pce.v[3] = face->v4 ? v[face->v4].co : NULL;
pce.tot = 3;
pce.inside = 0;
pce.index = index;
/* don't collide with same face again */
if(col->hit == col->current && col->pce.index == index && col->pce.tot == 3)
return;
do
{
collision = collision_sphere_to_tri(col, ray->radius, &pce, &t);
if(col->pce.inside == 0) {
collision += collision_sphere_to_edges(col, ray->radius, &pce, &t);
collision += collision_sphere_to_verts(col, ray->radius, &pce, &t);
}
if(collision) {
hit->dist = col->original_ray_length * t;
hit->index = index;
collision_point_velocity(&col->pce);
col->hit = col->current;
}
pce.x[1] = pce.x[2];
pce.x[2] = pce.x[3];
pce.x[3] = NULL;
pce.v[1] = pce.v[2];
pce.v[2] = pce.v[3];
pce.v[3] = NULL;
} while(pce.x[2]);
}
static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, ListBase *colliders)
{
ColliderCache *coll;
float ray_dir[3];
if(colliders->first == NULL)
return 0;
sub_v3_v3v3(ray_dir, col->co2, col->co1);
hit->index = -1;
hit->dist = col->original_ray_length = len_v3(ray_dir);
col->pce.inside = 0;
/* even if particle is stationary we want to check for moving colliders */
/* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
if(hit->dist == 0.0f)
hit->dist = col->original_ray_length = 0.000001f;
for(coll = colliders->first; coll; coll=coll->next){
/* for boids: don't check with current ground object */
if(coll->ob == col->skip)
continue;
/* particles should not collide with emitter at birth */
if(coll->ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra)
continue;
col->current = coll->ob;
col->md = coll->collmd;
col->fac1 = (col->old_cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
col->fac2 = (col->cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
if(col->md && col->md->bvhtree)
BLI_bvhtree_ray_cast(col->md->bvhtree, col->co1, ray_dir, col->radius, hit, BKE_psys_collision_neartest_cb, col);
}
return hit->index >= 0;
}
static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation)
{
ParticleCollisionElement *pce = &col->pce;
PartDeflect *pd = col->hit->pd;
float co[3]; /* point of collision */
float x = hit->dist/col->original_ray_length; /* location factor of collision between this iteration */
float f = col->f + x * (1.0f - col->f); /* time factor of collision between timestep */
float dt1 = (f - col->f) * col->total_time; /* time since previous collision (in seconds) */
float dt2 = (1.0f - f) * col->total_time; /* time left after collision (in seconds) */
int through = (BLI_frand() < pd->pdef_perm) ? 1 : 0; /* did particle pass through the collision surface? */
/* calculate exact collision location */
interp_v3_v3v3(co, col->co1, col->co2, x);
/* particle dies in collision */
if(through == 0 && (kill || pd->flag & PDEFLE_KILL_PART)) {
pa->alive = PARS_DYING;
pa->dietime = col->old_cfra + (col->cfra - col->old_cfra) * f;
copy_v3_v3(pa->state.co, co);
interp_v3_v3v3(pa->state.vel, pa->prev_state.vel, pa->state.vel, f);
interp_qt_qtqt(pa->state.rot, pa->prev_state.rot, pa->state.rot, f);
interp_v3_v3v3(pa->state.ave, pa->prev_state.ave, pa->state.ave, f);
/* particle is dead so we don't need to calculate further */
return 0;
}
/* figure out velocity and other data after collision */
else {
float v0[3]; /* velocity directly before collision to be modified into velocity directly after collision */
float v0_nor[3];/* normal component of v0 */
float v0_tan[3];/* tangential component of v0 */
float vc_tan[3];/* tangential component of collision surface velocity */
float v0_dot, vc_dot;
float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_frand() - 0.5f);
float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_frand() - 0.5f);
float distance, nor[3], dot;
CLAMP(damp,0.0f, 1.0f);
CLAMP(frict,0.0f, 1.0f);
/* get exact velocity right before collision */
madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1);
/* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */
mul_v3_fl(pce->vel, col->inv_timestep);
/* calculate tangential particle velocity */
v0_dot = dot_v3v3(pce->nor, v0);
madd_v3_v3v3fl(v0_tan, v0, pce->nor, -v0_dot);
/* calculate tangential collider velocity */
vc_dot = dot_v3v3(pce->nor, pce->vel);
madd_v3_v3v3fl(vc_tan, pce->vel, pce->nor, -vc_dot);
/* handle friction effects (tangential and angular velocity) */
if(frict > 0.0f) {
/* angular <-> linear velocity */
if(dynamic_rotation) {
float vr_tan[3], v1_tan[3], ave[3];
/* linear velocity of particle surface */
cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave);
mul_v3_fl(vr_tan, pa->size);
/* change to coordinates that move with the collision plane */
sub_v3_v3v3(v1_tan, v0_tan, vc_tan);
/* The resulting velocity is a weighted average of particle cm & surface
* velocity. This weight (related to particle's moment of inertia) could
* be made a parameter for angular <-> linear conversion.
*/
madd_v3_v3fl(v1_tan, vr_tan, -0.4);
mul_v3_fl(v1_tan, 1.0f/1.4f); /* 1/(1+0.4) */
/* rolling friction is around 0.01 of sliding friction (could be made a parameter) */
mul_v3_fl(v1_tan, 1.0f - 0.01f * frict);
/* surface_velocity is opposite to cm velocity */
mul_v3_v3fl(vr_tan, v1_tan, -1.0f);
/* get back to global coordinates */
add_v3_v3(v1_tan, vc_tan);
/* convert to angular velocity*/
cross_v3_v3v3(ave, vr_tan, pce->nor);
mul_v3_fl(ave, 1.0f/MAX2(pa->size, 0.001f));
/* only friction will cause change in linear & angular velocity */
interp_v3_v3v3(pa->state.ave, pa->state.ave, ave, frict);
interp_v3_v3v3(v0_tan, v0_tan, v1_tan, frict);
}
else {
/* just basic friction (unphysical due to the friction model used in Blender) */
interp_v3_v3v3(v0_tan, v0_tan, vc_tan, frict);
}
}
/* stickness was possibly added before, so cancel that before calculating new normal velocity */
/* otherwise particles go flying out of the surface because of high reversed sticky velocity */
if(v0_dot < 0.0f) {
v0_dot += pd->pdef_stickness;
if(v0_dot > 0.0f)
v0_dot = 0.0f;
}
/* damping and flipping of velocity around normal */
v0_dot *= 1.0f - damp;
vc_dot *= through ? damp : 1.0f;
/* calculate normal particle velocity */
/* special case for object hitting the particle from behind */
if(through==0 && ((vc_dot>0.0f && v0_dot>0.0f && vc_dot>v0_dot) || (vc_dot<0.0f && v0_dot<0.0f && vc_dot<v0_dot)))
mul_v3_v3fl(v0_nor, pce->nor, vc_dot);
else if(v0_dot > 0.f)
mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? -1.0f : 1.0f) * v0_dot);
else
mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? 1.0f : -1.0f) * v0_dot);
/* combine components together again */
add_v3_v3v3(v0, v0_nor, v0_tan);
if(col->boid) {
/* keep boids above ground */
BoidParticle *bpa = pa->boid;
if(bpa->data.mode == eBoidMode_OnLand || co[2] <= col->boid_z) {
co[2] = col->boid_z;
v0[2] = 0.0f;
}
}
/* re-apply acceleration to final location and velocity */
madd_v3_v3v3fl(pa->state.co, co, v0, dt2);
madd_v3_v3fl(pa->state.co, col->acc, 0.5f*dt2*dt2);
madd_v3_v3v3fl(pa->state.vel, v0, col->acc, dt2);
/* make sure particle stays on the right side of the surface */
if(!through) {
distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor);
if(distance < col->radius + COLLISION_MIN_DISTANCE)
madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
dot = dot_v3v3(nor, v0);
if(dot < 0.f)
madd_v3_v3fl(v0, nor, -dot);
distance = collision_point_distance_with_normal(pa->state.co, pce, 1.f, col, nor);
if(distance < col->radius + COLLISION_MIN_DISTANCE)
madd_v3_v3fl(pa->state.co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
dot = dot_v3v3(nor, pa->state.vel);
if(dot < 0.f)
madd_v3_v3fl(pa->state.vel, nor, -dot);
}
/* add stickness to surface */
madd_v3_v3fl(pa->state.vel, pce->nor, -pd->pdef_stickness);
/* set coordinates for next iteration */
copy_v3_v3(col->co1, co);
copy_v3_v3(col->co2, pa->state.co);
copy_v3_v3(col->ve1, v0);
copy_v3_v3(col->ve2, pa->state.vel);
col->f = f;
}
col->prev = col->hit;
col->prev_index = hit->index;
return 1;
}
static void collision_fail(ParticleData *pa, ParticleCollision *col)
{
/* final chance to prevent total failure, so stick to the surface and hope for the best */
collision_point_on_surface(col->co1, &col->pce, 1.f, col, pa->state.co);
copy_v3_v3(pa->state.vel, col->pce.vel);
mul_v3_fl(pa->state.vel, col->inv_timestep);
/* printf("max iterations\n"); */
}
/* Particle - Mesh collision detection and response
* Features:
* -friction and damping
* -angular momentum <-> linear momentum
* -high accuracy by re-applying particle acceleration after collision
* -handles moving, rotating and deforming meshes
* -uses Newton-Rhapson iteration to find the collisions
* -handles spherical particles and (nearly) point like particles
*/
static void collision_check(ParticleSimulationData *sim, int p, float dfra, float cfra){
ParticleSettings *part = sim->psys->part;
ParticleData *pa = sim->psys->particles + p;
ParticleCollision col;
BVHTreeRayHit hit;
int collision_count=0;
float timestep = psys_get_timestep(sim);
memset(&col, 0, sizeof(ParticleCollision));
col.total_time = timestep * dfra;
col.inv_timestep = 1.0f/timestep;
col.cfra = cfra;
col.old_cfra = sim->psys->cfra;
/* get acceleration (from gravity, forcefields etc. to be re-applied in collision response) */
sub_v3_v3v3(col.acc, pa->state.vel, pa->prev_state.vel);
mul_v3_fl(col.acc, 1.f/col.total_time);
/* set values for first iteration */
copy_v3_v3(col.co1, pa->prev_state.co);
copy_v3_v3(col.co2, pa->state.co);
copy_v3_v3(col.ve1, pa->prev_state.vel);
copy_v3_v3(col.ve2, pa->state.vel);
col.f = 0.0f;
col.radius = ((part->flag & PART_SIZE_DEFL) || (part->phystype == PART_PHYS_BOIDS)) ? pa->size : COLLISION_MIN_RADIUS;
/* override for boids */
if(part->phystype == PART_PHYS_BOIDS && part->boids->options & BOID_ALLOW_LAND) {
col.boid = 1;
col.boid_z = pa->state.co[2];
col.skip = pa->boid->ground;
}
/* 10 iterations to catch multiple collisions */
while(collision_count < COLLISION_MAX_COLLISIONS){
if(collision_detect(pa, &col, &hit, sim->colliders)) {
collision_count++;
if(collision_count == COLLISION_MAX_COLLISIONS)
collision_fail(pa, &col);
else if(collision_response(pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0)
return;
}
else
return;
}
}
/************************************************/
/* Hair */
/************************************************/
/* check if path cache or children need updating and do it if needed */
static void psys_update_path_cache(ParticleSimulationData *sim, float cfra)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
int distr=0, alloc=0, skip=0;
if((psys->part->childtype && psys->totchild != get_psys_tot_child(sim->scene, psys)) || psys->recalc&PSYS_RECALC_RESET)
alloc=1;
if(alloc || psys->recalc&PSYS_RECALC_CHILD || (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT)))
distr=1;
if(distr){
if(alloc)
realloc_particles(sim, sim->psys->totpart);
if(get_psys_tot_child(sim->scene, psys)) {
/* don't generate children while computing the hair keys */
if(!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
distribute_particles(sim, PART_FROM_CHILD);
if(part->childtype==PART_CHILD_FACES && part->parents != 0.0f)
psys_find_parents(sim);
}
}
else
psys_free_children(psys);
}
if((part->type==PART_HAIR || psys->flag&PSYS_KEYED || psys->pointcache->flag & PTCACHE_BAKED)==0)
skip = 1; /* only hair, keyed and baked stuff can have paths */
else if(part->ren_as != PART_DRAW_PATH && !(part->type==PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)))
skip = 1; /* particle visualization must be set as path */
else if(!psys->renderdata) {
if(part->draw_as != PART_DRAW_REND)
skip = 1; /* draw visualization */
else if(psys->pointcache->flag & PTCACHE_BAKING)
skip = 1; /* no need to cache paths while baking dynamics */
else if(psys_in_edit_mode(sim->scene, psys)) {
if((pset->flag & PE_DRAW_PART)==0)
skip = 1;
else if(part->childtype==0 && (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED)==0)
skip = 1; /* in edit mode paths are needed for child particles and dynamic hair */
}
}
if(!skip) {
psys_cache_paths(sim, cfra);
/* for render, child particle paths are computed on the fly */
if(part->childtype) {
if(!psys->totchild)
skip = 1;
else if(psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE)==0)
skip = 1;
if(!skip)
psys_cache_child_paths(sim, cfra, 0);
}
}
else if(psys->pathcache)
psys_free_path_cache(psys, NULL);
}
static void do_hair_dynamics(ParticleSimulationData *sim)
{
ParticleSystem *psys = sim->psys;
DerivedMesh *dm = psys->hair_in_dm;
MVert *mvert = NULL;
MEdge *medge = NULL;
MDeformVert *dvert = NULL;
HairKey *key;
PARTICLE_P;
int totpoint = 0;
int totedge;
int k;
float hairmat[4][4];
if(!psys->clmd) {
psys->clmd = (ClothModifierData*)modifier_new(eModifierType_Cloth);
psys->clmd->sim_parms->goalspring = 0.0f;
psys->clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_GOAL|CLOTH_SIMSETTINGS_FLAG_NO_SPRING_COMPRESS;
psys->clmd->coll_parms->flags &= ~CLOTH_COLLSETTINGS_FLAG_SELF;
}
/* create a dm from hair vertices */
LOOP_PARTICLES
totpoint += pa->totkey;
totedge = totpoint;
totpoint += psys->totpart;
if(dm && (totpoint != dm->getNumVerts(dm) || totedge != dm->getNumEdges(dm))) {
dm->release(dm);
dm = psys->hair_in_dm = NULL;
}
if(!dm) {
dm = psys->hair_in_dm = CDDM_new(totpoint, totedge, 0);
DM_add_vert_layer(dm, CD_MDEFORMVERT, CD_CALLOC, NULL);
}
mvert = CDDM_get_verts(dm);
medge = CDDM_get_edges(dm);
dvert = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
psys->clmd->sim_parms->vgroup_mass = 1;
/* make vgroup for pin roots etc.. */
psys->particles->hair_index = 1;
LOOP_PARTICLES {
if(p)
pa->hair_index = (pa-1)->hair_index + (pa-1)->totkey + 1;
psys_mat_hair_to_object(sim->ob, sim->psmd->dm, psys->part->from, pa, hairmat);
for(k=0, key=pa->hair; k<pa->totkey; k++,key++) {
/* create fake root before actual root to resist bending */
if(k==0) {
float temp[3];
VECSUB(temp, key->co, (key+1)->co);
VECCOPY(mvert->co, key->co);
VECADD(mvert->co, mvert->co, temp);
mul_m4_v3(hairmat, mvert->co);
mvert++;
medge->v1 = pa->hair_index - 1;
medge->v2 = pa->hair_index;
medge++;
if(dvert) {
if(!dvert->totweight) {
dvert->dw = MEM_callocN (sizeof(MDeformWeight), "deformWeight");
dvert->totweight = 1;
}
dvert->dw->weight = 1.0f;
dvert++;
}
}
VECCOPY(mvert->co, key->co);
mul_m4_v3(hairmat, mvert->co);
mvert++;
if(k) {
medge->v1 = pa->hair_index + k - 1;
medge->v2 = pa->hair_index + k;
medge++;
}
if(dvert) {
if(!dvert->totweight) {
dvert->dw = MEM_callocN (sizeof(MDeformWeight), "deformWeight");
dvert->totweight = 1;
}
/* roots should be 1.0, the rest can be anything from 0.0 to 1.0 */
dvert->dw->weight = key->weight;
dvert++;
}
}
}
if(psys->hair_out_dm)
psys->hair_out_dm->release(psys->hair_out_dm);
psys->clmd->point_cache = psys->pointcache;
psys->clmd->sim_parms->effector_weights = psys->part->effector_weights;
psys->hair_out_dm = clothModifier_do(psys->clmd, sim->scene, sim->ob, dm);
psys->clmd->sim_parms->effector_weights = NULL;
}
static void hair_step(ParticleSimulationData *sim, float cfra)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
PARTICLE_P;
float disp = (float)psys_get_current_display_percentage(psys)/100.0f;
LOOP_PARTICLES {
pa->size = part->size;
if(part->randsize > 0.0f)
pa->size *= 1.0f - part->randsize * PSYS_FRAND(p + 1);
if(PSYS_FRAND(p) > disp)
pa->flag |= PARS_NO_DISP;
else
pa->flag &= ~PARS_NO_DISP;
}
if(psys->recalc & PSYS_RECALC_RESET) {
/* need this for changing subsurf levels */
psys_calc_dmcache(sim->ob, sim->psmd->dm, psys);
if(psys->clmd)
cloth_free_modifier(psys->clmd);
}
/* dynamics with cloth simulation, psys->particles can be NULL with 0 particles [#25519] */
if(psys->part->type==PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS && psys->particles)
do_hair_dynamics(sim);
/* following lines were removed r29079 but cause bug [#22811], see report for details */
psys_update_effectors(sim);
psys_update_path_cache(sim, cfra);
psys->flag |= PSYS_HAIR_UPDATED;
}
static void save_hair(ParticleSimulationData *sim, float UNUSED(cfra)){
Object *ob = sim->ob;
ParticleSystem *psys = sim->psys;
HairKey *key, *root;
PARTICLE_P;
invert_m4_m4(ob->imat, ob->obmat);
psys->lattice= psys_get_lattice(sim);
if(psys->totpart==0) return;
/* save new keys for elements if needed */
LOOP_PARTICLES {
/* first time alloc */
if(pa->totkey==0 || pa->hair==NULL) {
pa->hair = MEM_callocN((psys->part->hair_step + 1) * sizeof(HairKey), "HairKeys");
pa->totkey = 0;
}
key = root = pa->hair;
key += pa->totkey;
/* convert from global to geometry space */
copy_v3_v3(key->co, pa->state.co);
mul_m4_v3(ob->imat, key->co);
if(pa->totkey) {
VECSUB(key->co, key->co, root->co);
psys_vec_rot_to_face(sim->psmd->dm, pa, key->co);
}
key->time = pa->state.time;
key->weight = 1.0f - key->time / 100.0f;
pa->totkey++;
/* root is always in the origin of hair space so we set it to be so after the last key is saved*/
if(pa->totkey == psys->part->hair_step + 1)
root->co[0] = root->co[1] = root->co[2] = 0.0f;
}
}
/* Code for an adaptive time step based on the Courant-Friedrichs-Lewy
condition. */
#define MIN_TIMESTEP 1.0f / 101.0f
/* Tolerance of 1.5 means the last subframe neither favours growing nor
shrinking (e.g if it were 1.3, the last subframe would tend to be too
small). */
#define TIMESTEP_EXPANSION_TOLERANCE 1.5f
/* Calculate the speed of the particle relative to the local scale of the
simulation. This should be called once per particle during a simulation
step, after the velocity has been updated. element_size defines the scale of
the simulation, and is typically the distance to neighbourning particles. */
void update_courant_num(ParticleSimulationData *sim, ParticleData *pa,
float dtime, float element_size, float flow[3])
{
float relative_vel[3];
float speed;
sub_v3_v3v3(relative_vel, pa->state.vel, flow);
speed = len_v3(relative_vel);
if (sim->courant_num < speed * dtime / element_size)
sim->courant_num = speed * dtime / element_size;
}
/* Update time step size to suit current conditions. */
float update_timestep(ParticleSystem *psys, ParticleSimulationData *sim,
float t_frac)
{
if (sim->courant_num == 0.0f)
psys->dt_frac = 1.0f;
else
psys->dt_frac *= (psys->part->courant_target / sim->courant_num);
CLAMP(psys->dt_frac, MIN_TIMESTEP, 1.0f);
/* Sync with frame end if it's close. */
if (t_frac == 1.0f)
return psys->dt_frac;
else if (t_frac + (psys->dt_frac * TIMESTEP_EXPANSION_TOLERANCE) >= 1.0f)
return 1.0f - t_frac;
else
return psys->dt_frac;
}
/************************************************/
/* System Core */
/************************************************/
/* unbaked particles are calculated dynamically */
static void dynamics_step(ParticleSimulationData *sim, float cfra)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part=psys->part;
BoidBrainData bbd;
ParticleTexture ptex;
PARTICLE_P;
float timestep;
/* frame & time changes */
float dfra, dtime;
float birthtime, dietime;
/* where have we gone in time since last time */
dfra= cfra - psys->cfra;
timestep = psys_get_timestep(sim);
dtime= dfra*timestep;
if(dfra < 0.0f) {
LOOP_EXISTING_PARTICLES {
psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra);
pa->size = part->size*ptex.size;
if(part->randsize > 0.0f)
pa->size *= 1.0f - part->randsize * PSYS_FRAND(p + 1);
reset_particle(sim, pa, dtime, cfra);
}
return;
}
BLI_srandom(31415926 + (int)cfra + psys->seed);
psys_update_effectors(sim);
if(part->type != PART_HAIR)
sim->colliders = get_collider_cache(sim->scene, sim->ob, NULL);
/* initialize physics type specific stuff */
switch(part->phystype) {
case PART_PHYS_BOIDS:
{
ParticleTarget *pt = psys->targets.first;
bbd.sim = sim;
bbd.part = part;
bbd.cfra = cfra;
bbd.dfra = dfra;
bbd.timestep = timestep;
psys_update_particle_tree(psys, cfra);
boids_precalc_rules(part, cfra);
for(; pt; pt=pt->next) {
if(pt->ob)
psys_update_particle_tree(BLI_findlink(&pt->ob->particlesystem, pt->psys-1), cfra);
}
break;
}
case PART_PHYS_FLUID:
{
ParticleTarget *pt = psys->targets.first;
psys_update_particle_bvhtree(psys, psys->cfra);
for(; pt; pt=pt->next) { /* Updating others systems particle tree for fluid-fluid interaction */
if(pt->ob)
psys_update_particle_bvhtree(BLI_findlink(&pt->ob->particlesystem, pt->psys-1), psys->cfra);
}
break;
}
}
/* initialize all particles for dynamics */
LOOP_SHOWN_PARTICLES {
copy_particle_key(&pa->prev_state,&pa->state,1);
psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra);
pa->size = part->size*ptex.size;
if(part->randsize > 0.0f)
pa->size *= 1.0f - part->randsize * PSYS_FRAND(p + 1);
birthtime = pa->time;
dietime = pa->dietime;
/* store this, so we can do multiple loops over particles */
pa->state.time = dfra;
if(dietime <= cfra && psys->cfra < dietime){
/* particle dies some time between this and last step */
pa->state.time = dietime - ((birthtime > psys->cfra) ? birthtime : psys->cfra);
pa->alive = PARS_DYING;
}
else if(birthtime <= cfra && birthtime >= psys->cfra){
/* particle is born some time between this and last step*/
reset_particle(sim, pa, dfra*timestep, cfra);
pa->alive = PARS_ALIVE;
pa->state.time = cfra - birthtime;
}
else if(dietime < cfra){
/* nothing to be done when particle is dead */
}
/* only reset unborn particles if they're shown or if the particle is born soon*/
if(pa->alive==PARS_UNBORN
&& (part->flag & PART_UNBORN || cfra + psys->pointcache->step > pa->time))
reset_particle(sim, pa, dtime, cfra);
else if(part->phystype == PART_PHYS_NO)
reset_particle(sim, pa, dtime, cfra);
if(ELEM(pa->alive, PARS_ALIVE, PARS_DYING)==0 || (pa->flag & (PARS_UNEXIST|PARS_NO_DISP)))
pa->state.time = -1.f;
}
switch(part->phystype) {
case PART_PHYS_NEWTON:
{
LOOP_DYNAMIC_PARTICLES {
/* do global forces & effectors */
basic_integrate(sim, p, pa->state.time, cfra);
/* deflection */
if(sim->colliders)
collision_check(sim, p, pa->state.time, cfra);
/* rotations */
basic_rotate(part, pa, pa->state.time, timestep);
}
break;
}
case PART_PHYS_BOIDS:
{
LOOP_DYNAMIC_PARTICLES {
bbd.goal_ob = NULL;
boid_brain(&bbd, p, pa);
if(pa->alive != PARS_DYING) {
boid_body(&bbd, pa);
/* deflection */
if(sim->colliders)
collision_check(sim, p, pa->state.time, cfra);
}
}
break;
}
case PART_PHYS_FLUID:
{
EdgeHash *springhash = sph_springhash_build(psys);
float *gravity = NULL;
float element_size, flow[3];
if(psys_uses_gravity(sim))
gravity = sim->scene->physics_settings.gravity;
LOOP_DYNAMIC_PARTICLES {
/* do global forces & effectors */
basic_integrate(sim, p, pa->state.time, cfra);
/* actual fluids calculations */
sph_integrate(sim, pa, pa->state.time, gravity, springhash,
&element_size, flow);
if(sim->colliders)
collision_check(sim, p, pa->state.time, cfra);
/* SPH particles are not physical particles, just interpolation particles, thus rotation has not a direct sense for them */
basic_rotate(part, pa, pa->state.time, timestep);
if (part->time_flag & PART_TIME_AUTOSF)
update_courant_num(sim, pa, dtime, element_size, flow);
}
sph_springs_modify(psys, timestep);
if(springhash) {
BLI_edgehash_free(springhash, NULL);
springhash = NULL;
}
break;
}
}
/* finalize particle state and time after dynamics */
LOOP_DYNAMIC_PARTICLES {
if(pa->alive == PARS_DYING){
pa->alive=PARS_DEAD;
pa->state.time=pa->dietime;
}
else
pa->state.time=cfra;
}
free_collider_cache(&sim->colliders);
}
static void update_children(ParticleSimulationData *sim)
{
if((sim->psys->part->type == PART_HAIR) && (sim->psys->flag & PSYS_HAIR_DONE)==0)
/* don't generate children while growing hair - waste of time */
psys_free_children(sim->psys);
else if(sim->psys->part->childtype) {
if(sim->psys->totchild != get_psys_tot_child(sim->scene, sim->psys))
distribute_particles(sim, PART_FROM_CHILD);
else
; /* Children are up to date, nothing to do. */
}
else
psys_free_children(sim->psys);
}
/* updates cached particles' alive & other flags etc..*/
static void cached_step(ParticleSimulationData *sim, float cfra)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
ParticleTexture ptex;
PARTICLE_P;
float disp, dietime;
psys_update_effectors(sim);
disp= (float)psys_get_current_display_percentage(psys)/100.0f;
LOOP_PARTICLES {
psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra);
pa->size = part->size*ptex.size;
if(part->randsize > 0.0f)
pa->size *= 1.0f - part->randsize * PSYS_FRAND(p + 1);
psys->lattice= psys_get_lattice(sim);
dietime = pa->dietime;
/* update alive status and push events */
if(pa->time > cfra) {
pa->alive = PARS_UNBORN;
if(part->flag & PART_UNBORN && (psys->pointcache->flag & PTCACHE_EXTERNAL) == 0)
reset_particle(sim, pa, 0.0f, cfra);
}
else if(dietime <= cfra)
pa->alive = PARS_DEAD;
else
pa->alive = PARS_ALIVE;
if(psys->lattice){
end_latt_deform(psys->lattice);
psys->lattice= NULL;
}
if(PSYS_FRAND(p) > disp)
pa->flag |= PARS_NO_DISP;
else
pa->flag &= ~PARS_NO_DISP;
}
}
static void particles_fluid_step(ParticleSimulationData *sim, int UNUSED(cfra))
{
ParticleSystem *psys = sim->psys;
if(psys->particles){
MEM_freeN(psys->particles);
psys->particles = 0;
psys->totpart = 0;
}
/* fluid sim particle import handling, actual loading of particles from file */
#ifndef DISABLE_ELBEEM
{
FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(sim->ob, eModifierType_Fluidsim);
if( fluidmd && fluidmd->fss) {
FluidsimSettings *fss= fluidmd->fss;
ParticleSettings *part = psys->part;
ParticleData *pa=NULL;
char filename[256];
char debugStrBuffer[256];
int curFrame = sim->scene->r.cfra -1; // warning - sync with derived mesh fsmesh loading
int p, j, totpart;
int readMask, activeParts = 0, fileParts = 0;
gzFile gzf;
// XXX if(ob==G.obedit) // off...
// return;
// ok, start loading
BLI_snprintf(filename, sizeof(filename), "%sfluidsurface_particles_####.gz", fss->surfdataPath);
BLI_path_abs(filename, G.main->name);
BLI_path_frame(filename, curFrame, 0); // fixed #frame-no
gzf = gzopen(filename, "rb");
if (!gzf) {
BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer),"readFsPartData::error - Unable to open file for reading '%s' \n", filename);
// XXX bad level call elbeemDebugOut(debugStrBuffer);
return;
}
gzread(gzf, &totpart, sizeof(totpart));
totpart = (G.rendering)?totpart:(part->disp*totpart)/100;
part->totpart= totpart;
part->sta=part->end = 1.0f;
part->lifetime = sim->scene->r.efra + 1;
/* allocate particles */
realloc_particles(sim, part->totpart);
// set up reading mask
readMask = fss->typeFlags;
for(p=0, pa=psys->particles; p<totpart; p++, pa++) {
int ptype=0;
gzread(gzf, &ptype, sizeof( ptype ));
if(ptype&readMask) {
activeParts++;
gzread(gzf, &(pa->size), sizeof( float ));
pa->size /= 10.0f;
for(j=0; j<3; j++) {
float wrf;
gzread(gzf, &wrf, sizeof( wrf ));
pa->state.co[j] = wrf;
//fprintf(stderr,"Rj%d ",j);
}
for(j=0; j<3; j++) {
float wrf;
gzread(gzf, &wrf, sizeof( wrf ));
pa->state.vel[j] = wrf;
}
pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0f;
pa->state.rot[0] = 1.0;
pa->state.rot[1] = pa->state.rot[2] = pa->state.rot[3] = 0.0;
pa->time = 1.f;
pa->dietime = sim->scene->r.efra + 1;
pa->lifetime = sim->scene->r.efra;
pa->alive = PARS_ALIVE;
//if(a<25) fprintf(stderr,"FSPARTICLE debug set %s , a%d = %f,%f,%f , life=%f \n", filename, a, pa->co[0],pa->co[1],pa->co[2], pa->lifetime );
} else {
// skip...
for(j=0; j<2*3+1; j++) {
float wrf; gzread(gzf, &wrf, sizeof( wrf ));
}
}
fileParts++;
}
gzclose( gzf );
totpart = psys->totpart = activeParts;
BLI_snprintf(debugStrBuffer,sizeof(debugStrBuffer),"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d \n", psys->totpart,activeParts,fileParts,readMask);
// bad level call
// XXX elbeemDebugOut(debugStrBuffer);
} // fluid sim particles done
}
#endif // DISABLE_ELBEEM
}
static int emit_particles(ParticleSimulationData *sim, PTCacheID *pid, float UNUSED(cfra))
{
ParticleSystem *psys = sim->psys;
int oldtotpart = psys->totpart;
int totpart = tot_particles(psys, pid);
if(totpart != oldtotpart)
realloc_particles(sim, totpart);
return totpart - oldtotpart;
}
/* Calculates the next state for all particles of the system
* In particles code most fra-ending are frames, time-ending are fra*timestep (seconds)
* 1. Emit particles
* 2. Check cache (if used) and return if frame is cached
* 3. Do dynamics
* 4. Save to cache */
static void system_step(ParticleSimulationData *sim, float cfra)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
PointCache *cache = psys->pointcache;
PTCacheID ptcacheid, *pid = NULL;
PARTICLE_P;
float disp, cache_cfra = cfra; /*, *vg_vel= 0, *vg_tan= 0, *vg_rot= 0, *vg_size= 0; */
int startframe = 0, endframe = 100, oldtotpart = 0;
/* cache shouldn't be used for hair or "continue physics" */
if(part->type != PART_HAIR && BKE_ptcache_get_continue_physics() == 0) {
psys_clear_temp_pointcache(psys);
/* set suitable cache range automatically */
if((cache->flag & (PTCACHE_BAKING|PTCACHE_BAKED))==0)
psys_get_pointcache_start_end(sim->scene, psys, &cache->startframe, &cache->endframe);
pid = &ptcacheid;
BKE_ptcache_id_from_particles(pid, sim->ob, psys);
BKE_ptcache_id_time(pid, sim->scene, 0.0f, &startframe, &endframe, NULL);
/* clear everythin on start frame */
if(cfra == startframe) {
BKE_ptcache_id_reset(sim->scene, pid, PTCACHE_RESET_OUTDATED);
BKE_ptcache_validate(cache, startframe);
cache->flag &= ~PTCACHE_REDO_NEEDED;
}
CLAMP(cache_cfra, startframe, endframe);
}
/* 1. emit particles and redo particles if needed */
oldtotpart = psys->totpart;
if(emit_particles(sim, pid, cfra) || psys->recalc & PSYS_RECALC_RESET) {
distribute_particles(sim, part->from);
initialize_all_particles(sim);
/* reset only just created particles (on startframe all particles are recreated) */
reset_all_particles(sim, 0.0, cfra, oldtotpart);
if (psys->fluid_springs) {
MEM_freeN(psys->fluid_springs);
psys->fluid_springs = NULL;
}
psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
/* flag for possible explode modifiers after this system */
sim->psmd->flag |= eParticleSystemFlag_Pars;
BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfra);
}
/* 2. try to read from the cache */
if(pid) {
int cache_result = BKE_ptcache_read(pid, cache_cfra);
if(ELEM(cache_result, PTCACHE_READ_EXACT, PTCACHE_READ_INTERPOLATED)) {
cached_step(sim, cfra);
update_children(sim);
psys_update_path_cache(sim, cfra);
BKE_ptcache_validate(cache, (int)cache_cfra);
if(cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED)
BKE_ptcache_write(pid, (int)cache_cfra);
return;
}
/* Cache is supposed to be baked, but no data was found so bail out */
else if(cache->flag & PTCACHE_BAKED) {
psys_reset(psys, PSYS_RESET_CACHE_MISS);
return;
}
else if(cache_result == PTCACHE_READ_OLD) {
psys->cfra = (float)cache->simframe;
cached_step(sim, psys->cfra);
}
/* if on second frame, write cache for first frame */
if(psys->cfra == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0))
BKE_ptcache_write(pid, startframe);
}
else
BKE_ptcache_invalidate(cache);
/* 3. do dynamics */
/* set particles to be not calculated TODO: can't work with pointcache */
disp= (float)psys_get_current_display_percentage(psys)/100.0f;
LOOP_PARTICLES {
if(PSYS_FRAND(p) > disp)
pa->flag |= PARS_NO_DISP;
else
pa->flag &= ~PARS_NO_DISP;
}
if(psys->totpart) {
int dframe, totframesback = 0;
float t_frac, dt_frac;
/* handle negative frame start at the first frame by doing
* all the steps before the first frame */
if((int)cfra == startframe && part->sta < startframe)
totframesback = (startframe - (int)part->sta);
if (!(part->time_flag & PART_TIME_AUTOSF)) {
/* Constant time step */
psys->dt_frac = 1.0f / (float) (part->subframes + 1);
} else if ((int)cfra == startframe) {
/* Variable time step; use a very conservative value at the start.
* If it doesn't need to be so small, it will quickly grow. */
psys->dt_frac = 1.0;
} else if (psys->dt_frac < MIN_TIMESTEP) {
psys->dt_frac = MIN_TIMESTEP;
}
for(dframe=-totframesback; dframe<=0; dframe++) {
/* simulate each subframe */
dt_frac = psys->dt_frac;
for (t_frac = dt_frac; t_frac <= 1.0f; t_frac += dt_frac) {
sim->courant_num = 0.0f;
dynamics_step(sim, cfra+dframe+t_frac - 1.f);
psys->cfra = cfra+dframe+t_frac - 1.f;
#if 0
printf("%f,%f,%f,%f\n", cfra+dframe+t_frac - 1.f, t_frac, dt_frac, sim->courant_num);
#endif
if (part->time_flag & PART_TIME_AUTOSF)
dt_frac = update_timestep(psys, sim, t_frac);
}
}
}
/* 4. only write cache starting from second frame */
if(pid) {
BKE_ptcache_validate(cache, (int)cache_cfra);
if((int)cache_cfra != startframe)
BKE_ptcache_write(pid, (int)cache_cfra);
}
update_children(sim);
/* cleanup */
if(psys->lattice){
end_latt_deform(psys->lattice);
psys->lattice= NULL;
}
}
/* system type has changed so set sensible defaults and clear non applicable flags */
static void psys_changed_type(ParticleSimulationData *sim)
{
ParticleSettings *part = sim->psys->part;
PTCacheID pid;
BKE_ptcache_id_from_particles(&pid, sim->ob, sim->psys);
if(part->phystype != PART_PHYS_KEYED)
sim->psys->flag &= ~PSYS_KEYED;
if(part->type == PART_HAIR) {
if(ELEM4(part->ren_as, PART_DRAW_NOT, PART_DRAW_PATH, PART_DRAW_OB, PART_DRAW_GR)==0)
part->ren_as = PART_DRAW_PATH;
if(part->distr == PART_DISTR_GRID)
part->distr = PART_DISTR_JIT;
if(ELEM3(part->draw_as, PART_DRAW_NOT, PART_DRAW_REND, PART_DRAW_PATH)==0)
part->draw_as = PART_DRAW_REND;
CLAMP(part->path_start, 0.0f, 100.0f);
CLAMP(part->path_end, 0.0f, 100.0f);
BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_ALL, 0);
}
else {
free_hair(sim->ob, sim->psys, 1);
CLAMP(part->path_start, 0.0f, MAX2(100.0f, part->end + part->lifetime));
CLAMP(part->path_end, 0.0f, MAX2(100.0f, part->end + part->lifetime));
}
psys_reset(sim->psys, PSYS_RESET_ALL);
}
void psys_check_boid_data(ParticleSystem *psys)
{
BoidParticle *bpa;
PARTICLE_P;
pa = psys->particles;
if(!pa)
return;
if(psys->part && psys->part->phystype==PART_PHYS_BOIDS) {
if(!pa->boid) {
bpa = MEM_callocN(psys->totpart * sizeof(BoidParticle), "Boid Data");
LOOP_PARTICLES
pa->boid = bpa++;
}
}
else if(pa->boid){
MEM_freeN(pa->boid);
LOOP_PARTICLES
pa->boid = NULL;
}
}
static void fluid_default_settings(ParticleSettings *part){
SPHFluidSettings *fluid = part->fluid;
fluid->spring_k = 0.f;
fluid->plasticity_constant = 0.1f;
fluid->yield_ratio = 0.1f;
fluid->rest_length = 1.f;
fluid->viscosity_omega = 2.f;
fluid->viscosity_beta = 0.1f;
fluid->stiffness_k = 1.f;
fluid->stiffness_knear = 1.f;
fluid->rest_density = 1.f;
fluid->buoyancy = 0.f;
fluid->radius = 1.f;
fluid->flag |= SPH_FAC_REPULSION|SPH_FAC_DENSITY|SPH_FAC_RADIUS|SPH_FAC_VISCOSITY|SPH_FAC_REST_LENGTH;
}
static void psys_prepare_physics(ParticleSimulationData *sim)
{
ParticleSettings *part = sim->psys->part;
if(ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)) {
PTCacheID pid;
BKE_ptcache_id_from_particles(&pid, sim->ob, sim->psys);
BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_ALL, 0);
}
else {
free_keyed_keys(sim->psys);
sim->psys->flag &= ~PSYS_KEYED;
}
if(part->phystype == PART_PHYS_BOIDS && part->boids == NULL) {
BoidState *state;
part->boids = MEM_callocN(sizeof(BoidSettings), "Boid Settings");
boid_default_settings(part->boids);
state = boid_new_state(part->boids);
BLI_addtail(&state->rules, boid_new_rule(eBoidRuleType_Separate));
BLI_addtail(&state->rules, boid_new_rule(eBoidRuleType_Flock));
((BoidRule*)state->rules.first)->flag |= BOIDRULE_CURRENT;
state->flag |= BOIDSTATE_CURRENT;
BLI_addtail(&part->boids->states, state);
}
else if(part->phystype == PART_PHYS_FLUID && part->fluid == NULL) {
part->fluid = MEM_callocN(sizeof(SPHFluidSettings), "SPH Fluid Settings");
fluid_default_settings(part);
}
psys_check_boid_data(sim->psys);
}
static int hair_needs_recalc(ParticleSystem *psys)
{
if(!(psys->flag & PSYS_EDITED) && (!psys->edit || !psys->edit->edited) &&
((psys->flag & PSYS_HAIR_DONE)==0 || psys->recalc & PSYS_RECALC_RESET || (psys->part->flag & PART_HAIR_REGROW && !psys->edit))) {
return 1;
}
return 0;
}
/* main particle update call, checks that things are ok on the large scale and
* then advances in to actual particle calculations depending on particle type */
void particle_system_update(Scene *scene, Object *ob, ParticleSystem *psys)
{
ParticleSimulationData sim= {0};
ParticleSettings *part = psys->part;
float cfra;
/* drawdata is outdated after ANY change */
if(psys->pdd) psys->pdd->flag &= ~PARTICLE_DRAW_DATA_UPDATED;
if(!psys_check_enabled(ob, psys))
return;
cfra= BKE_curframe(scene);
sim.scene= scene;
sim.ob= ob;
sim.psys= psys;
sim.psmd= psys_get_modifier(ob, psys);
/* system was already updated from modifier stack */
if(sim.psmd->flag & eParticleSystemFlag_psys_updated) {
sim.psmd->flag &= ~eParticleSystemFlag_psys_updated;
/* make sure it really was updated to cfra */
if(psys->cfra == cfra)
return;
}
if(!sim.psmd->dm)
return;
/* execute drivers only, as animation has already been done */
BKE_animsys_evaluate_animdata(scene, &part->id, part->adt, cfra, ADT_RECALC_DRIVERS);
if(psys->recalc & PSYS_RECALC_TYPE)
psys_changed_type(&sim);
if(psys->recalc & PSYS_RECALC_RESET)
psys->totunexist = 0;
/* setup necessary physics type dependent additional data if it doesn't yet exist */
psys_prepare_physics(&sim);
switch(part->type) {
case PART_HAIR:
{
/* nothing to do so bail out early */
if(psys->totpart == 0 && part->totpart == 0) {
psys_free_path_cache(psys, NULL);
free_hair(ob, psys, 0);
}
/* (re-)create hair */
else if(hair_needs_recalc(psys)) {
float hcfra=0.0f;
int i, recalc = psys->recalc;
free_hair(ob, psys, 0);
if(psys->edit && psys->free_edit) {
psys->free_edit(psys->edit);
psys->edit = NULL;
psys->free_edit = NULL;
}
/* first step is negative so particles get killed and reset */
psys->cfra= 1.0f;
for(i=0; i<=part->hair_step; i++){
hcfra=100.0f*(float)i/(float)psys->part->hair_step;
if((part->flag & PART_HAIR_REGROW)==0)
BKE_animsys_evaluate_animdata(scene, &part->id, part->adt, hcfra, ADT_RECALC_ANIM);
system_step(&sim, hcfra);
psys->cfra = hcfra;
psys->recalc = 0;
save_hair(&sim, hcfra);
}
psys->flag |= PSYS_HAIR_DONE;
psys->recalc = recalc;
}
else if(psys->flag & PSYS_EDITED)
psys->flag |= PSYS_HAIR_DONE;
if(psys->flag & PSYS_HAIR_DONE)
hair_step(&sim, cfra);
break;
}
case PART_FLUID:
{
particles_fluid_step(&sim, (int)cfra);
break;
}
default:
{
switch(part->phystype) {
case PART_PHYS_NO:
case PART_PHYS_KEYED:
{
PARTICLE_P;
float disp = (float)psys_get_current_display_percentage(psys)/100.0f;
/* Particles without dynamics haven't been reset yet because they don't use pointcache */
if(psys->recalc & PSYS_RECALC_RESET)
psys_reset(psys, PSYS_RESET_ALL);
if(emit_particles(&sim, NULL, cfra) || (psys->recalc & PSYS_RECALC_RESET)) {
free_keyed_keys(psys);
distribute_particles(&sim, part->from);
initialize_all_particles(&sim);
/* flag for possible explode modifiers after this system */
sim.psmd->flag |= eParticleSystemFlag_Pars;
}
LOOP_EXISTING_PARTICLES {
pa->size = part->size;
if(part->randsize > 0.0f)
pa->size *= 1.0f - part->randsize * PSYS_FRAND(p + 1);
reset_particle(&sim, pa, 0.0, cfra);
if(PSYS_FRAND(p) > disp)
pa->flag |= PARS_NO_DISP;
else
pa->flag &= ~PARS_NO_DISP;
}
if(part->phystype == PART_PHYS_KEYED) {
psys_count_keyed_targets(&sim);
set_keyed_keys(&sim);
psys_update_path_cache(&sim,(int)cfra);
}
break;
}
default:
{
/* the main dynamic particle system step */
system_step(&sim, cfra);
break;
}
}
break;
}
}
if(psys->cfra < cfra) {
/* make sure emitter is left at correct time (particle emission can change this) */
while(ob) {
BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, cfra, ADT_RECALC_ANIM);
ob = ob->parent;
}
ob = sim.ob;
where_is_object_time(scene, ob, cfra);
}
psys->cfra = cfra;
psys->recalc = 0;
/* save matrix for duplicators, at rendertime the actual dupliobject's matrix is used so don't update! */
if(psys->renderdata==0)
invert_m4_m4(psys->imat, ob->obmat);
}
| 27.945686 | 219 | 0.652553 |
28500a05d1902c9111712029248a79422dd9b2cf | 1,839 | h | C | of_v0.11.2_vs2017/apps/CLC-LC/src/ParticleSystem/ForceField.h | lexvandersluijs/clc_laser | 25fbc8f9a2654d8a4ef253b5ab4c711d8d8876b9 | [
"MIT"
] | 1 | 2021-11-06T22:07:36.000Z | 2021-11-06T22:07:36.000Z | Easter2014/src/ParticleSystem/ForceField.h | lexvandersluijs/clc | 0ff940b32c24642f9b443748b95964bf6263ed44 | [
"MIT"
] | null | null | null | Easter2014/src/ParticleSystem/ForceField.h | lexvandersluijs/clc | 0ff940b32c24642f9b443748b95964bf6263ed44 | [
"MIT"
] | null | null | null | namespace ParticleSystem
{
static const float EPSILON = 0.0001f;
class ForceField
{
protected:
public:
// function that computes the new position and speed of a particle based on its current state
// for a forcefield, the current position is the most important
ForceField()
{
}
virtual ofVec2f ComputeForce(Particle* particle)
{
return ofVec2f::zero();
}
};
class PointForceField : public ForceField
{
// positive factor pushes out, negative pulls in
private:
ofVec2f _center;
float _factor;
public:
PointForceField(ofVec2f center, float factor)
{
_factor = 1.0f;
_center = center;
_factor = factor;
}
virtual ofVec2f ComputeForce(Particle* particle)
{
ofVec2f force = ofVec2f::zero();
ofVec2f delta = particle->Position - _center;
// FF wants to move particle in a certain direcion
// the simulation will collect all forces, then compute a resultant force,
// and apply it to the particle
float l = delta.length();
if(l > EPSILON)
{
force = delta * (_factor / l);
}
return force;
}
};
class VortexForceField : public ForceField
{
// positive factor pushes out, negative pulls in
private:
ofVec2f _center;
float _factor;
// possible addition: specify the axis around which the forces rotate
public:
VortexForceField(ofVec2f center, float factor)
{
_factor = 1.0f;
_center = center;
_factor = factor;
}
virtual ofVec2f ComputeForce(Particle* particle)
{
ofVec2f force = ofVec2f::zero();
ofVec2f delta = particle->Position - _center;
// to get a ´rotation´ ForceField, we take the direction from the FF center
// and take the perpendicular. but first, normalize.
float l = delta.length();
if(l > EPSILON)
{
delta *= (1.0f / l);
force.x = -delta.y * _factor;
force.y = delta.x * _factor;
}
return force;
}
};
}; | 19.357895 | 94 | 0.690049 |
285318b764bdc65f67e8ed1755fddb7a8993f9fb | 892 | h | C | csvfix/inc/csved_check.h | moissinac/csvfix | 06cd5638e3a3bb0049fb7138c72211aef972c8d4 | [
"MIT"
] | 4 | 2022-01-25T15:54:29.000Z | 2022-03-18T21:32:16.000Z | csvfix/inc/csved_check.h | moissinac/csvfix | 06cd5638e3a3bb0049fb7138c72211aef972c8d4 | [
"MIT"
] | 1 | 2020-11-23T20:19:38.000Z | 2021-04-10T15:05:39.000Z | csvfix/inc/csved_check.h | moissinac/csvfix | 06cd5638e3a3bb0049fb7138c72211aef972c8d4 | [
"MIT"
] | 5 | 2021-12-14T05:42:52.000Z | 2022-03-11T04:23:47.000Z | //---------------------------------------------------------------------------
// csved_check.h
//
// check CSV records actually are CSV
//
// Copyright (C) 2011 Neil Butterworth
//---------------------------------------------------------------------------
#ifndef INC_CSVED_CHECK_H
#define INC_CSVED_CHECK_H
#include "a_base.h"
#include "csved_command.h"
namespace CSVED {
//---------------------------------------------------------------------------
class CheckCommand : public Command {
public:
CheckCommand( const std::string & name,
const std::string & desc );
int Execute( ALib::CommandLine & cmd );
private:
void ProcessFlags( const ALib::CommandLine & cmd );
bool mQuiet, mEmbedNLOk, mVerbose;
char mSep;
};
//------------------------------------------------------------------------
} // end namespace
#endif
| 20.744186 | 78 | 0.421525 |
285342ad68353b646766672557e8bbe72c74276e | 367 | h | C | EZLayout/UIView+EZLayout_Private.h | jhurray/EZLayout | b3524be5532a535d0f96930eef006e9bde91ca67 | [
"MIT"
] | 314 | 2015-06-26T04:03:25.000Z | 2021-06-03T18:56:01.000Z | EZLayout/UIView+EZLayout_Private.h | jhurray/EZLayout | b3524be5532a535d0f96930eef006e9bde91ca67 | [
"MIT"
] | 2 | 2015-08-17T18:05:07.000Z | 2016-01-01T09:42:18.000Z | EZLayout/UIView+EZLayout_Private.h | jhurray/EZLayout | b3524be5532a535d0f96930eef006e9bde91ca67 | [
"MIT"
] | 18 | 2015-06-26T04:03:27.000Z | 2020-12-26T05:37:09.000Z | //
// UIView+EZLayout_Private.h
// EZLayoutExample
//
// Created by Jeff Hurray on 5/24/15.
// Copyright (c) 2015 Jeff Hurray. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (EZLayout_Private)
- (void) calculateSizeAndAlignmentValuesInContainerRect:(CGRect) containerRect;
- (void) calculateViewInContainerRect:(CGRect) containerRect;
@end
| 21.588235 | 79 | 0.752044 |
28543bd9fad0665f3e41022026f9f810af8cd70c | 420 | h | C | C++/RemoveException.h | Pavlo-Andrianatos/Basic-Linear-Data-Structures | fef230284624fa79c1709f087ab9798917cb73d1 | [
"MIT"
] | null | null | null | C++/RemoveException.h | Pavlo-Andrianatos/Basic-Linear-Data-Structures | fef230284624fa79c1709f087ab9798917cb73d1 | [
"MIT"
] | null | null | null | C++/RemoveException.h | Pavlo-Andrianatos/Basic-Linear-Data-Structures | fef230284624fa79c1709f087ab9798917cb73d1 | [
"MIT"
] | null | null | null | #ifndef REMOVEEXCEPT
#define REMOVEEXCEPT
#include <iostream>
using namespace std;
/*
A simple class that you can use to indicate errors
in removing from structures. In Java, this class
will have to conform to the Throwable interface.
*/
class RemoveException
{
public:
RemoveException(string s)
{
message = s;
}
string getMessage()
{
return message;
}
private:
string message;
};
#endif | 13.548387 | 50 | 0.709524 |
2855c4ca47f8d092f594e097fa304b733c647286 | 430 | h | C | HappyTravelShow/HappyTravelShow/Classes/Scenes/ViewController/HomepageVC/ScrollVC.h | AmazingLW/HappyTravelShow | 6001a6116e9fc2e8c7c64f2a838fbb4b62a750f5 | [
"MIT"
] | 1 | 2015-10-15T09:29:04.000Z | 2015-10-15T09:29:04.000Z | HappyTravelShow/HappyTravelShow/Classes/Scenes/ViewController/HomepageVC/ScrollVC.h | AmazingLW/HappyTravelShow | 6001a6116e9fc2e8c7c64f2a838fbb4b62a750f5 | [
"MIT"
] | null | null | null | HappyTravelShow/HappyTravelShow/Classes/Scenes/ViewController/HomepageVC/ScrollVC.h | AmazingLW/HappyTravelShow | 6001a6116e9fc2e8c7c64f2a838fbb4b62a750f5 | [
"MIT"
] | null | null | null | //
// ScrollVC.h
// HappyTravelShow
//
// Created by lanou3g on 15/10/15.
// Copyright (c) 2015年 com.liuwei. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "FinderMainModel.h"
@interface ScrollVC : UIViewController
//绑定的model,用于传值
@property(nonatomic,strong) FinderMainModel *model;
//字符串用于传值(标题)
@property(nonatomic,strong) NSString *titleString;
@property(nonatomic,strong) NSString *cityCode,*cityNum;
@end
| 20.47619 | 57 | 0.734884 |
285c1517ab575b794a3858140692de7b0adb90b8 | 2,912 | h | C | content/common/page_messages.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/common/page_messages.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/common/page_messages.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_PAGE_MESSAGES_H_
#define CONTENT_COMMON_PAGE_MESSAGES_H_
#include "content/public/common/common_param_traits.h"
#include "content/public/common/page_visibility_state.h"
#include "content/public/common/screen_info.h"
#include "ipc/ipc_message_macros.h"
#include "third_party/blink/public/platform/web_text_autosizer_page_info.h"
#include "ui/gfx/geometry/rect.h"
// IPC messages for page-level actions.
// TODO(https://crbug.com/775827): Convert to mojo.
#undef IPC_MESSAGE_EXPORT
#define IPC_MESSAGE_EXPORT CONTENT_EXPORT
#define IPC_MESSAGE_START PageMsgStart
// Messages sent from the browser to the renderer.
// TODO(yuzus): Migrate this as a part of blink::mojom::SetPageLifecycleState.
IPC_MESSAGE_ROUTED1(PageMsg_VisibilityChanged, content::PageVisibilityState)
// Sent when the history for this page is altered from another process. The
// history list should be reset to |history_length| length, and the offset
// should be reset to |history_offset|.
IPC_MESSAGE_ROUTED2(PageMsg_SetHistoryOffsetAndLength,
int /* history_offset */,
int /* history_length */)
IPC_MESSAGE_ROUTED1(PageMsg_AudioStateChanged, bool /* is_audio_playing */)
// Sent to all renderers, instructing them to freeze or unfreeze all frames that
// belongs to this page.
IPC_MESSAGE_ROUTED1(PageMsg_SetPageFrozen, bool /* frozen */)
// Sent to all renderers to freeze all frames and dispatch page visibility
// events for bfcache.
IPC_MESSAGE_ROUTED0(PageMsg_PutPageIntoBackForwardCache)
// Sent to all renderers to resume all frames and dispatch page visibility
// events for bfcache.
IPC_MESSAGE_ROUTED1(PageMsg_RestorePageFromBackForwardCache,
base::TimeTicks /* navigation_start */)
// Sent to all renderers when the mainframe state required by
// blink::TextAutosizer changes in the main frame's renderer.
IPC_MESSAGE_ROUTED1(PageMsg_UpdateTextAutosizerPageInfoForRemoteMainFrames,
blink::WebTextAutosizerPageInfo /* page_info */)
// Sends updated preferences to the renderer.
IPC_MESSAGE_ROUTED1(PageMsg_SetRendererPrefs, blink::mojom::RendererPreferences)
// Sent to all renderers when a portal web contents is activated or if a
// web contents is adopted as a portal.
IPC_MESSAGE_ROUTED1(PageMsg_SetInsidePortal, bool /* inside_portal */)
// -----------------------------------------------------------------------------
// Messages sent from the renderer to the browser.
// Adding a new message? Stick to the sort order above: first platform
// independent PageMsg, then ifdefs for platform specific PageMsg, then platform
// independent PageHostMsg, then ifdefs for platform specific PageHostMsg.
#endif // CONTENT_COMMON_PAGE_MESSAGES_H_
| 41.6 | 80 | 0.762019 |
285da75768593ea3a20783823009fa5ff4b37df2 | 83 | h | C | include/varargs.h | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | 3 | 2021-05-04T17:09:06.000Z | 2021-10-04T07:19:26.000Z | include/varargs.h | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | include/varargs.h | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | /* varargs.h 4.1 83/05/03 */
#include <sys/cdefs.h>
#include <machine/stdarg.h>
| 11.857143 | 28 | 0.638554 |
285eee647580f5badfee409d41272d80e73b7d85 | 287 | c | C | src/keys.c | jimjag/x6502 | 0adfe0e879070547465404bb275aebdf1c7e9924 | [
"BSD-4-Clause"
] | 13 | 2020-01-14T05:50:23.000Z | 2022-01-16T00:40:08.000Z | src/keys.c | jimjag/x6502 | 0adfe0e879070547465404bb275aebdf1c7e9924 | [
"BSD-4-Clause"
] | null | null | null | src/keys.c | jimjag/x6502 | 0adfe0e879070547465404bb275aebdf1c7e9924 | [
"BSD-4-Clause"
] | 4 | 2020-01-14T23:46:23.000Z | 2022-01-19T09:00:50.000Z | #include "keys.h"
#include <stdlib.h>
#include <stdio.h>
keys * new_keys() {
keys *k = malloc(sizeof(keys));
k->key_up = false;
k->key_down = false;
k->key_left = false;
k->key_right = false;
k->key_enter = false;
return k;
}
void destroy_keys(keys* k) {
free(k);
}
| 13.666667 | 33 | 0.609756 |
285f25f0afb93d2b075f90e42f4e351f3c13b582 | 313 | h | C | Rand.h | dontpanic5/rpge-4ume | e7048ef52e4b92d83547daa8d392165bb7cab15e | [
"MIT"
] | null | null | null | Rand.h | dontpanic5/rpge-4ume | e7048ef52e4b92d83547daa8d392165bb7cab15e | [
"MIT"
] | null | null | null | Rand.h | dontpanic5/rpge-4ume | e7048ef52e4b92d83547daa8d392165bb7cab15e | [
"MIT"
] | null | null | null | #pragma once
#include <random>
template<typename T>
class Rand {
public:
Rand(T high, T low) :dist(low, high)
{
std::random_device r;
re.seed(r());
};
T operator()() { return dist(re); };
void seed(T s) { re.seed(s); }
private:
std::default_random_engine re;
std::uniform_int_distribution<T> dist;
}; | 17.388889 | 39 | 0.658147 |
286035861e7101b2f1fc983ab72bf3fa2533c58d | 9,479 | h | C | linux-apps/lucene-r2p2/inc/lucene++/NumericUtils.h | gsol10/r2p2 | 6305d2eb31a6ee87c7f873d0caa03b7a7df042b9 | [
"MIT"
] | 2 | 2015-09-23T13:25:57.000Z | 2015-11-06T11:13:12.000Z | linux-apps/lucene-r2p2/inc/lucene++/NumericUtils.h | gsol10/r2p2 | 6305d2eb31a6ee87c7f873d0caa03b7a7df042b9 | [
"MIT"
] | 1 | 2015-10-28T16:51:44.000Z | 2015-11-06T11:13:03.000Z | linux-apps/lucene-r2p2/inc/lucene++/NumericUtils.h | gsol10/r2p2 | 6305d2eb31a6ee87c7f873d0caa03b7a7df042b9 | [
"MIT"
] | 3 | 2015-10-12T15:26:56.000Z | 2020-01-24T11:40:06.000Z | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2014 Alan Wright. All rights reserved.
// Distributable under the terms of either the Apache License (Version 2.0)
// or the GNU Lesser General Public License.
/////////////////////////////////////////////////////////////////////////////
#ifndef NUMERICUTILS_H
#define NUMERICUTILS_H
#include "LuceneObject.h"
namespace Lucene {
/// This is a helper class to generate prefix-encoded representations for numerical values and supplies converters
/// to represent double values as sortable integers/longs.
///
/// To quickly execute range queries in Apache Lucene, a range is divided recursively into multiple intervals for
/// searching: The center of the range is searched only with the lowest possible precision in the trie, while the
/// boundaries are matched more exactly. This reduces the number of terms dramatically.
///
/// This class generates terms to achieve this: First the numerical integer values need to be converted to strings.
/// For that integer values (32 bit or 64 bit) are made unsigned and the bits are converted to ASCII chars with each
/// 7 bit. The resulting string is sortable like the original integer value. Each value is also prefixed (in the
/// first char) by the shift value (number of bits removed) used during encoding.
///
/// To also index floating point numbers, this class supplies two methods to convert them to integer values by
/// changing their bit layout: {@link #doubleToSortableLong}, {@link #doubleToSortableInt}. You will have no precision
/// loss by converting floating point numbers to integers and back (only that the integer form is not usable). Other
/// data types like dates can easily converted to longs or ints (eg. date to long).
///
/// For easy usage, the trie algorithm is implemented for indexing inside {@link NumericTokenStream} that can index
/// int, long, and double. For querying, {@link NumericRangeQuery} and {@link NumericRangeFilter} implement the query
/// part for the same data types.
///
/// This class can also be used, to generate lexicographically sortable (according {@link std::string#compare})
/// representations of numeric data types for other usages (eg. sorting).
class LPPAPI NumericUtils : public LuceneObject {
public:
virtual ~NumericUtils();
LUCENE_CLASS(NumericUtils);
public:
/// The default precision step used by {@link NumericField}, {@link NumericTokenStream}, {@link NumericRangeQuery},
/// and {@link NumericRangeFilter} as default.
static const int32_t PRECISION_STEP_DEFAULT;
/// Longs are stored at lower precision by shifting off lower bits. The shift count is stored as SHIFT_START_LONG +
/// shift in the first character.
static const wchar_t SHIFT_START_LONG;
/// The maximum term length (used for char[] buffer size) for encoding long values.
/// @see #longToPrefixCoded(long,int,char[])
static const int32_t BUF_SIZE_LONG;
/// Integers are stored at lower precision by shifting off lower bits. The shift count is stored as SHIFT_START_INT +
/// shift in the first character.
static const wchar_t SHIFT_START_INT;
/// The maximum term length (used for char[] buffer size) for encoding int values.
/// @see #intToPrefixCoded(int,int,char[])
static const int32_t BUF_SIZE_INT;
public:
/// Returns prefix coded bits after reducing the precision by shift bits. This is method is used by
/// {@link NumericTokenStream}.
/// @param val the numeric value
/// @param shift how many bits to strip from the right
/// @param buffer that will contain the encoded chars, must be at least of {@link #BUF_SIZE_LONG} length
/// @return number of chars written to buffer
static int32_t longToPrefixCoded(int64_t val, int32_t shift, CharArray buffer);
/// Returns prefix coded bits after reducing the precision by shift bits. This is method is used by
/// {@link LongRangeBuilder}.
/// @param val the numeric value
/// @param shift how many bits to strip from the right
static String longToPrefixCoded(int64_t val, int32_t shift);
/// This is a convenience method, that returns prefix coded bits of a long without reducing the precision.
/// It can be used to store the full precision value as a stored field in index.
/// To decode, use {@link #prefixCodedToLong}.
static String longToPrefixCoded(int64_t val);
/// Returns prefix coded bits after reducing the precision by shift bits. This is method is used by {@link
/// NumericTokenStream}.
/// @param val the numeric value
/// @param shift how many bits to strip from the right
/// @param buffer that will contain the encoded chars, must be at least of {@link #BUF_SIZE_INT} length
/// @return number of chars written to buffer
static int32_t intToPrefixCoded(int32_t val, int32_t shift, CharArray buffer);
/// Returns prefix coded bits after reducing the precision by shift bits. This is method is used by {@link
/// IntRangeBuilder}.
/// @param val the numeric value
/// @param shift how many bits to strip from the right
static String intToPrefixCoded(int32_t val, int32_t shift);
/// This is a convenience method, that returns prefix coded bits of an int without reducing the precision.
/// It can be used to store the full precision value as a stored field in index.
/// To decode, use {@link #prefixCodedToInt}.
static String intToPrefixCoded(int32_t val);
/// Returns a long from prefixCoded characters. Rightmost bits will be zero for lower precision codes.
/// This method can be used to decode eg. a stored field.
/// @see #longToPrefixCoded(int64_t)
static int64_t prefixCodedToLong(const String& prefixCoded);
/// Returns an int from prefixCoded characters. Rightmost bits will be zero for lower precision codes.
/// This method can be used to decode eg. a stored field.
/// @see #intToPrefixCoded(int32_t)
static int32_t prefixCodedToInt(const String& prefixCoded);
/// Converts a double value to a sortable signed long. The value is converted by getting their IEEE 754
/// floating-point "double format" bit layout and then some bits are swapped, to be able to compare the
/// result as int64_t. By this the precision is not reduced, but the value can easily used as a int64_t.
/// @see #sortableLongToDouble
static int64_t doubleToSortableLong(double val);
/// Convenience method: this just returns: longToPrefixCoded(doubleToSortableLong(val))
static String doubleToPrefixCoded(double val);
/// Converts a sortable long back to a double.
/// @see #doubleToSortableLong
static double sortableLongToDouble(int64_t val);
/// Convenience method: this just returns: sortableLongToDouble(prefixCodedToLong(val))
static double prefixCodedToDouble(const String& val);
/// Splits a int64_t range recursively. You may implement a builder that adds clauses to a {@link BooleanQuery}
/// for each call to its {@link LongRangeBuilder#addRange(String,String)} method.
/// This method is used by {@link NumericRangeQuery}.
static void splitLongRange(const LongRangeBuilderPtr& builder, int32_t precisionStep, int64_t minBound, int64_t maxBound);
/// Splits an int32_t range recursively. You may implement a builder that adds clauses to a {@link BooleanQuery}
/// for each call to its {@link IntRangeBuilder#addRange(String,String)} method.
/// This method is used by {@link NumericRangeQuery}.
static void splitIntRange(const IntRangeBuilderPtr& builder, int32_t precisionStep, int32_t minBound, int32_t maxBound);
/// This helper does the splitting for both 32 and 64 bit.
static void splitRange(const LuceneObjectPtr& builder, int32_t valSize, int32_t precisionStep, int64_t minBound, int64_t maxBound);
/// Helper that delegates to correct range builder
static void addRange(const LuceneObjectPtr& builder, int32_t valSize, int64_t minBound, int64_t maxBound, int32_t shift);
};
/// Callback for {@link #splitLongRange}. You need to overwrite only one of the methods.
/// NOTE: This is a very low-level interface, the method signatures may change in later versions.
class LPPAPI LongRangeBuilder : public LuceneObject {
public:
virtual ~LongRangeBuilder();
public:
/// Overwrite this method, if you like to receive the already prefix encoded range bounds. You can directly build
/// classical (inclusive) range queries from them.
virtual void addRange(const String& minPrefixCoded, const String& maxPrefixCoded);
/// Overwrite this method, if you like to receive the raw long range bounds. You can use this for eg. debugging
/// purposes (print out range bounds).
virtual void addRange(int64_t min, int64_t max, int32_t shift);
};
class LPPAPI IntRangeBuilder : public LuceneObject {
public:
virtual ~IntRangeBuilder();
public:
/// Overwrite this method, if you like to receive the already prefix encoded range bounds. You can directly build
/// classical range (inclusive) queries from them.
virtual void addRange(const String& minPrefixCoded, const String& maxPrefixCoded);
/// Overwrite this method, if you like to receive the raw int range bounds. You can use this for eg. debugging
/// purposes (print out range bounds).
virtual void addRange(int32_t min, int32_t max, int32_t shift);
};
}
#endif
| 52.955307 | 135 | 0.726764 |
2865afa5ebcc0ce8accc0bb32455a2c92af9ed29 | 27 | h | C | libs/cg_nui/surfel_container.h | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | libs/cg_nui/surfel_container.h | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | libs/cg_nui/surfel_container.h | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #pragma
// TODO: implement | 9 | 18 | 0.703704 |
286ec909b6a97a38f5e5b90cd488b31affad5e65 | 258 | h | C | libraries/ByPass-Xbee/XbeeCommunication.h | Sytten/ByPASS | c5b009d6ef9c986a7607332a7777af81b3752ab4 | [
"MIT"
] | 5 | 2017-12-11T16:11:55.000Z | 2021-02-10T14:20:28.000Z | libraries/ByPass-Xbee/XbeeCommunication.h | Sytten/ByPASS | c5b009d6ef9c986a7607332a7777af81b3752ab4 | [
"MIT"
] | null | null | null | libraries/ByPass-Xbee/XbeeCommunication.h | Sytten/ByPASS | c5b009d6ef9c986a7607332a7777af81b3752ab4 | [
"MIT"
] | null | null | null | #pragma once
#include "XbeeMessage.h"
#include "rtos.h"
extern Mail<XbeeMessage, 3> sending_mailbox;
extern Mail<XbeeMessage, 3> receiving_mailbox;
// Bidirectionnal async communication for a many-to-one configuration
void xbee_communication_run(); | 28.666667 | 70 | 0.77907 |
286fa1f91b059e7084af32289fa989a2d386c0d5 | 745 | c | C | lista2/ex34.c | Joel-Graf/Listas_de_exercicios_C_UFU | f030b0c9f78997cc3c372e76e935452ffd3df838 | [
"MIT"
] | null | null | null | lista2/ex34.c | Joel-Graf/Listas_de_exercicios_C_UFU | f030b0c9f78997cc3c372e76e935452ffd3df838 | [
"MIT"
] | null | null | null | lista2/ex34.c | Joel-Graf/Listas_de_exercicios_C_UFU | f030b0c9f78997cc3c372e76e935452ffd3df838 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main(int argc, char const *argv[]) {
float grade;
int absences, conceptPosition;
char concept[] = {'A', 'B', 'C', 'D', 'E'};
printf("Insert student grade: ");
scanf("%f", &grade);
if (grade < 0 || grade > 10) {
printf("Invalid grade");
return 1;
}
if (grade >= 9) {
conceptPosition = 0;
} else if (grade >= 7.5) {
conceptPosition = 1;
} else if (grade >= 5) {
conceptPosition = 2;
} else if (grade >= 4) {
conceptPosition = 3;
} else {
conceptPosition = 4;
}
printf("Insert student absences: ");
scanf("%d", &absences);
if (absences > 20 && conceptPosition < 4) conceptPosition++;
printf("Student concept is %c", concept[conceptPosition]);
return 0;
}
| 21.285714 | 62 | 0.579866 |
28717745e9dd0cd0b3d58d7f2cb9f6b84ff6d1dc | 259 | h | C | Tests/test_material_models.h | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | null | null | null | Tests/test_material_models.h | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | 2 | 2020-10-19T02:03:11.000Z | 2021-03-19T16:34:39.000Z | Tests/test_material_models.h | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | 1 | 2020-04-28T00:33:14.000Z | 2020-04-28T00:33:14.000Z | #ifndef __Test_Material_Models_h__
#define __Test_Material_Models_h__
void test_mat_model_utils();
void test_model_container();
void test_mcc_get_Su();
void test_mcc_compression();
void test_undrained_mcc();
void test_von_mises();
void test_tresca();
#endif | 21.583333 | 34 | 0.830116 |
2871c1d9e0c7d2058b4693270c3f1ac05f48df67 | 414 | h | C | colorwhelldialog.h | emako/colorcap | b1fcbc9de42c9c0cfcfad9545f046371bc0ee8cd | [
"MIT"
] | null | null | null | colorwhelldialog.h | emako/colorcap | b1fcbc9de42c9c0cfcfad9545f046371bc0ee8cd | [
"MIT"
] | null | null | null | colorwhelldialog.h | emako/colorcap | b1fcbc9de42c9c0cfcfad9545f046371bc0ee8cd | [
"MIT"
] | null | null | null | #ifndef COLORWHELLDIALOG_H
#define COLORWHELLDIALOG_H
#include "colorwheel.h"
#include <QDialog>
namespace Ui {
class ColorWhellDialog;
}
class ColorWhellDialog : public QDialog
{
Q_OBJECT
public:
explicit ColorWhellDialog(QWidget *parent = nullptr);
~ColorWhellDialog();
ColorWheel *mColorWhell;
private:
Ui::ColorWhellDialog *ui;
};
#endif // COLORWHELLDIALOG_H
| 16.56 | 58 | 0.702899 |
2871dac5f1f0c4a079c605fb6b744ff9b320e72d | 1,312 | h | C | src/Shape/NuiDevicePointCloud.h | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | 3 | 2016-07-14T13:04:35.000Z | 2017-04-01T09:58:27.000Z | src/Shape/NuiDevicePointCloud.h | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | null | null | null | src/Shape/NuiDevicePointCloud.h | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | 1 | 2021-11-21T15:33:35.000Z | 2021-11-21T15:33:35.000Z | #pragma once
#include "stdafx.h"
#include "NuiImageBuffer.h"
#include <vector>
struct NuiDevicePoint
{
Point4D fVertex;
BGRQUAD fBGRA;
bool fIsValid;
BYTE fBodyIndex;
float fNormal_x;
float fNormal_y;
float fNormal_z;
float fColorSpaceU;
float fColorSpaceV;
};
class NuiDevicePointCloud
{
public:
NuiDevicePointCloud();
~NuiDevicePointCloud();
void DeepCopy (const NuiDevicePointCloud& other);
NuiDevicePointCloud (const NuiDevicePointCloud& other){ DeepCopy(other); }
NuiDevicePointCloud& operator = (const NuiDevicePointCloud& other) { DeepCopy(other); return *this; }
void Clear();
UINT GetPointsNum() const { return m_nPointNum; }
NuiDevicePoint* AllocatePoints(UINT num);
NuiDevicePoint* AccessPoint(UINT id) const;
bool SetPoint(UINT id, const NuiDevicePoint& pt);
bool ReadPoint(UINT id, NuiDevicePoint* pPt) const;
bool SetPointVertex(UINT id, const Point4D& vt);
void SetWidthStep(UINT width) { m_nWidthStep = width; }
UINT GetWidthStep() const { return m_nWidthStep; }
void SetColorImage(const NuiColorImage& image) { m_colorImage = image; }
const NuiColorImage& GetColorImage() const { return m_colorImage; }
private:
UINT m_nPointNum;
UINT m_nWidthStep;
NuiDevicePoint* m_pCloudPoints;
NuiColorImage m_colorImage;
}; | 26.24 | 102 | 0.74314 |
2873d462c6ceec3d8f665671186c3b9ae80a52ca | 1,524 | h | C | Scripts/Template/Headers/java/beans/IntrospectionException.h | mbeloded/J2ObjC-FrameworkMb | 35dc7171cb7d08edf6824ed3c9f34311c8be3347 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/java/beans/IntrospectionException.h | mbeloded/J2ObjC-FrameworkMb | 35dc7171cb7d08edf6824ed3c9f34311c8be3347 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/java/beans/IntrospectionException.h | mbeloded/J2ObjC-FrameworkMb | 35dc7171cb7d08edf6824ed3c9f34311c8be3347 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: apache_harmony/classlib/modules/beans/src/main/java/java/beans/IntrospectionException.java
//
#include "../../J2ObjC_header.h"
#pragma push_macro("JavaBeansIntrospectionException_INCLUDE_ALL")
#ifdef JavaBeansIntrospectionException_RESTRICT
#define JavaBeansIntrospectionException_INCLUDE_ALL 0
#else
#define JavaBeansIntrospectionException_INCLUDE_ALL 1
#endif
#undef JavaBeansIntrospectionException_RESTRICT
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if !defined (JavaBeansIntrospectionException_) && (JavaBeansIntrospectionException_INCLUDE_ALL || defined(JavaBeansIntrospectionException_INCLUDE))
#define JavaBeansIntrospectionException_
#define JavaLangException_RESTRICT 1
#define JavaLangException_INCLUDE 1
#include "../../java/lang/Exception.h"
@interface JavaBeansIntrospectionException : JavaLangException
#pragma mark Public
- (instancetype)initWithNSString:(NSString *)message;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaBeansIntrospectionException)
FOUNDATION_EXPORT void JavaBeansIntrospectionException_initWithNSString_(JavaBeansIntrospectionException *self, NSString *message);
FOUNDATION_EXPORT JavaBeansIntrospectionException *new_JavaBeansIntrospectionException_initWithNSString_(NSString *message) NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(JavaBeansIntrospectionException)
#endif
#pragma clang diagnostic pop
#pragma pop_macro("JavaBeansIntrospectionException_INCLUDE_ALL")
| 32.425532 | 148 | 0.858924 |
2873e82f541c04bc779c39d10657a428978334a4 | 1,947 | h | C | module/mpc-be/SRC/src/AudioTools/Mixer.h | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | module/mpc-be/SRC/src/AudioTools/Mixer.h | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | module/mpc-be/SRC/src/AudioTools/Mixer.h | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | /*
* (C) 2014-2020 see Authors.txt
*
* This file is part of MPC-BE.
*
* MPC-BE 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.
*
* MPC-BE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "SampleFormat.h"
struct SwrContext;
class CMixer
{
private:
SwrContext* m_pSWRCxt;
double* m_matrix_dbl;
double m_center_level;
double m_surround_level;
bool m_normalize_matrix;
bool m_dummy_channels;
bool m_ActualContext;
SampleFormat m_in_sf;
SampleFormat m_out_sf;
DWORD m_in_layout;
DWORD m_out_layout;
int m_in_samplerate;
int m_out_samplerate;
enum AVSampleFormat m_in_avsf;
enum AVSampleFormat m_out_avsf;
public:
CMixer();
~CMixer();
private:
bool Init();
public:
void SetOptions(double center_level, double suround_level, bool normalize_matrix, bool dummy_channels);
void UpdateInput (SampleFormat in_sf, DWORD in_layout, int in_samplerate = 48000);
void UpdateOutput(SampleFormat out_sf, DWORD out_layout, int out_samplerate = 48000);
int Mixing(BYTE* pOutput, int out_samples, BYTE* pInput, int in_samples);
int Receive(BYTE* pOutput, int out_samples); // needed when using resampling
int64_t GetDelay(); // needed when using resampling
int CalcOutSamples(int in_samples); // needed when using resampling
void FlushBuffers(); // needed when using resampling
};
| 29.059701 | 104 | 0.721109 |
287a74295c666ae0614c717c64b11084ceecc7d8 | 356 | h | C | code/components/esp32-camera-master/sensors/private_include/nt99141.h | burjakremen/AI-on-the-edge-device | b7e836df90b623ad9ed0b17c2a20e9c07646e6d7 | [
"MIT"
] | 2,040 | 2020-08-13T06:11:55.000Z | 2022-03-28T23:08:34.000Z | code/components/esp32-camera-master/sensors/private_include/nt99141.h | burjakremen/AI-on-the-edge-device | b7e836df90b623ad9ed0b17c2a20e9c07646e6d7 | [
"MIT"
] | 631 | 2020-08-13T06:20:47.000Z | 2022-03-31T17:34:13.000Z | code/components/esp32-camera-master/sensors/private_include/nt99141.h | burjakremen/AI-on-the-edge-device | b7e836df90b623ad9ed0b17c2a20e9c07646e6d7 | [
"MIT"
] | 298 | 2020-07-29T19:59:10.000Z | 2022-03-31T10:38:20.000Z | /*
* This file is part of the OpenMV project.
* Copyright (c) 2013/2014 Ibrahim Abdelkader <i.abdalkader@gmail.com>
* This work is licensed under the MIT license, see the file LICENSE for details.
*
* NT99141 driver.
*
*/
#ifndef __NT99141_H__
#define __NT99141_H__
#include "sensor.h"
int NT99141_init(sensor_t *sensor);
#endif // __NT99141_H__
| 20.941176 | 81 | 0.733146 |
287ba6a38567c793270f975ecabdffca1f02e5b5 | 3,413 | h | C | _studio/mfx_lib/encode_hw/hevc/agnostic/g9/hevcehw_g9_alloc.h | ndomnina/MediaSDK | 32d2f64ca34d675c49025fcc941e59e40431e17a | [
"MIT"
] | 1 | 2020-09-08T15:30:11.000Z | 2020-09-08T15:30:11.000Z | _studio/mfx_lib/encode_hw/hevc/agnostic/g9/hevcehw_g9_alloc.h | ndomnina/MediaSDK | 32d2f64ca34d675c49025fcc941e59e40431e17a | [
"MIT"
] | null | null | null | _studio/mfx_lib/encode_hw/hevc/agnostic/g9/hevcehw_g9_alloc.h | ndomnina/MediaSDK | 32d2f64ca34d675c49025fcc941e59e40431e17a | [
"MIT"
] | null | null | null | // Copyright (c) 2019 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice 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 "mfx_common.h"
#if defined(MFX_ENABLE_H265_VIDEO_ENCODE)
#include "hevcehw_base.h"
#include "hevcehw_g9_data.h"
#include "mfxstructures.h"
#include <vector>
namespace HEVCEHW
{
namespace Gen9
{
class MfxFrameAllocResponse
: public mfxFrameAllocResponse
, public IAllocation
{
public:
MfxFrameAllocResponse(VideoCORE& core);
~MfxFrameAllocResponse();
virtual
mfxStatus Alloc(
mfxFrameAllocRequest & req
, bool isCopyRequired) override;
virtual
mfxStatus AllocOpaque(
const mfxFrameInfo & info
, mfxU16 type
, mfxFrameSurface1 **surfaces
, mfxU16 numSurface) override;
virtual
const mfxFrameAllocResponse& Response() const override
{
return *this;
}
virtual
const mfxFrameInfo& Info() const override
{
return m_info;
}
virtual
Resource Acquire() override;
virtual
void Release(mfxU32 idx) override
{
Unlock(idx);
}
virtual void ClearFlag(mfxU32 idx) override;
virtual void SetFlag(mfxU32 idx, mfxU32 flag) override;
virtual mfxU32 GetFlag(mfxU32 idx) override;
virtual void Unlock() override;
mfxU32 Lock(mfxU32 idx);
mfxU32 Unlock(mfxU32 idx);
mfxU32 Locked(mfxU32 idx) const;
virtual void Free();
bool isExternal() { return m_isExternal; };
mfxFrameInfo m_info = {};
protected:
MfxFrameAllocResponse(MfxFrameAllocResponse const &) = delete;
MfxFrameAllocResponse & operator =(MfxFrameAllocResponse const &) = delete;
VideoCORE& m_core;
mfxU16 m_numFrameActualReturnedByAllocFrames = 0;
std::vector<mfxFrameAllocResponse> m_responseQueue;
std::vector<mfxMemId> m_mids;
std::vector<mfxU32> m_locked;
std::vector<mfxU32> m_flag;
bool m_isExternal = true;
bool m_isOpaque = false;
};
class Allocator
: public FeatureBase
{
public:
#define DECL_BLOCK_LIST\
DECL_BLOCK(Init)
#define DECL_FEATURE_NAME "G9_Allocator"
#include "hevcehw_decl_blocks.h"
Allocator(mfxU32 FeatureId)
: FeatureBase(FeatureId)
{}
protected:
virtual void InitAlloc(const FeatureBlocks& blocks, TPushIA Push) override;
};
} //Gen9
} //namespace HEVCEHW
#endif
| 26.253846 | 81 | 0.705538 |
288073ae64bee465055904a66f0cde73daa0de73 | 1,706 | h | C | src/arch/microblaze/kernel/context.h | nikitavlaev/embox | 7ab7a5b649d8a408ecbdaafee8318b1c3dc9cf62 | [
"BSD-2-Clause"
] | 809 | 2015-04-12T00:57:55.000Z | 2022-03-18T13:39:59.000Z | src/arch/microblaze/kernel/context.h | nikitavlaev/embox | 7ab7a5b649d8a408ecbdaafee8318b1c3dc9cf62 | [
"BSD-2-Clause"
] | 819 | 2015-04-14T17:54:29.000Z | 2022-03-26T08:52:12.000Z | src/arch/microblaze/kernel/context.h | nikitavlaev/embox | 7ab7a5b649d8a408ecbdaafee8318b1c3dc9cf62 | [
"BSD-2-Clause"
] | 274 | 2015-04-15T16:11:52.000Z | 2022-03-25T10:24:43.000Z | /**
* @file
* @brief
*
* @date 13.04.10
* @author Eldar Abusalimov
*/
#ifndef ARCH_MICROBLAZE_CONTEXT_H_
#define ARCH_MICROBLAZE_CONTEXT_H_
#ifndef __ASSEMBLER__
#include <stdint.h>
struct context {
/* 0x00 */ uint32_t r1; /* stack pointer */
/* 0x04 */ uint32_t r2;
/* r3-r12 are volatile register (caller-save) */
/* dedicated registers */
/* 0x08 */ uint32_t r13;
/* 0x0c */ uint32_t r14;
/* 0x10 */ uint32_t r15;
/* 0x14 */ uint32_t r16;
/* 0x18 */ uint32_t r17;
/* 0x1C */ uint32_t r18;
/* non-volatile registers Callee-save */
/* 0x20 */ uint32_t r19;
/* 0x24 */ uint32_t r20;
/* 0x28 */ uint32_t r21;
/* 0x2C */ uint32_t r22;
/* 0x30 */ uint32_t r23;
/* 0x34 */ uint32_t r24;
/* 0x38 */ uint32_t r25;
/* 0x3C */ uint32_t r26;
/* 0x40 */ uint32_t r27;
/* 0x44 */ uint32_t r28;
/* 0x48 */ uint32_t r29;
/* 0x4C */ uint32_t r30;
/* 0x50 */ uint32_t r31;
/* special purpose registers */
/* 0x50 */ uint32_t msr;
/* 0x54 */ uint32_t ear;
/* 0x58 */ uint32_t esr;
/* 0x60 */ uint32_t fsr;
};
#endif /* __ASSEMBLER__ */
#define CC_R1 0x00
#define CC_R2 0x04
#define CC_R13 0x08
#define CC_R14 0x0C
#define CC_R15 0x10
#define CC_R16 0x14
#define CC_R17 0x18
#define CC_R18 0x1C
#define CC_R19 0x20
#define CC_R20 0x24
#define CC_R21 0x28
#define CC_R22 0x2C
#define CC_R23 0x30
#define CC_R24 0x34
#define CC_R25 0x38
#define CC_R26 0x3C
#define CC_R27 0x40
#define CC_R28 0x44
#define CC_R29 0x48
#define CC_R30 0x4C
#define CC_R31 0x50
#define CC_RMSR 0x54
#define CC_REAR 0x58
#define CC_RESR 0x5C
#define CC_RFSR 0x60
#endif /* ARCH_MICROBLAZE_CONTEXT_H_ */
| 21.061728 | 49 | 0.639508 |
28808b35085b19128f79c54368cb85bf9e42379e | 27,424 | c | C | source/util_api/tls/components/TlsCryptoProvider/tls_cpo_public.c | lgirdk/ccsp-common-library | 8d912984e96f960df6dadb4b0e6bc76c76376776 | [
"Apache-2.0"
] | 4 | 2018-02-26T05:41:14.000Z | 2019-12-20T07:31:39.000Z | source/util_api/tls/components/TlsCryptoProvider/tls_cpo_public.c | rdkcmf/rdkb-CcspCommonLibrary | 3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1 | [
"Apache-2.0"
] | null | null | null | source/util_api/tls/components/TlsCryptoProvider/tls_cpo_public.c | rdkcmf/rdkb-CcspCommonLibrary | 3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1 | [
"Apache-2.0"
] | 3 | 2017-07-30T15:35:16.000Z | 2020-08-18T20:44:08.000Z | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2015 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.
*/
/**********************************************************************
Copyright [2014] [Cisco Systems, Inc.]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********************************************************************/
/**********************************************************************
module: tls_cpo_public.c
For Transport Layer Security Implementation (TLS),
BroadWay Service Delivery System
---------------------------------------------------------------
description:
This module implements the advanced public key related
crypto functions of the TLS Crypto Provider Object.
* TlsCpoEncrypt_RSA
* TlsCpoDecrypt_RSA
* TlsCpoSign
* TlsCpoSign_RSA
* TlsCpoSign_DSA
* TlsCpoVerify
* TlsCpoVerify_RSA
* TlsCpoVerify_DSA
---------------------------------------------------------------
environment:
platform independent
---------------------------------------------------------------
author:
Xuechen Yang
---------------------------------------------------------------
revision:
06/22/03 initial revision.
**********************************************************************/
#include "tls_cpo_global.h"
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
TlsCpoEncrypt_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_pub_key,
void* i_data,
ULONG i_data_size,
void* o_data,
PULONG o_data_size
);
description:
This function is called to perform RSA encryption by using
the specifies public key.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ANSC_X509_KEY* i_pub_key
Specifies the public key to be used for encryption.
void* i_data
Specifies the plain text data to be encrypted.
ULONG i_data_size
Specifies the size of the plain text data.
void* o_data
Specifies the output buffer of cipher text data.
PULONG o_data_size
As an input parameter, it specifies the size of the
output buffer; as an output parameter, it specifies
the size of the real output.
return: status of operation.
**********************************************************************/
ANSC_STATUS
TlsCpoEncrypt_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_pub_key,
void* i_data,
ULONG i_data_size,
void* o_data,
PULONG o_data_size
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PTLS_CRYPTO_PROVIDER_OBJECT pMyObject = (PTLS_CRYPTO_PROVIDER_OBJECT)hThisObject;
PANSC_CRYPTO_PUB_OBJECT pSSLCrypto = (PANSC_CRYPTO_PUB_OBJECT )pMyObject->hAnscCryptoPub;
ANSC_CRYPTO_PUB_KEY_PARAMS params;
PANSC_CRYPTO_PUB_KEY_GEN_PARAMS pGenParams;
ANSC_CRYPTO_PUB_ALGORITHM Alg;
ANSC_CRYPTO_PUB_OPERATION Op;
if( i_pub_key == NULL)
{
return ANSC_STATUS_FAILURE;
}
if( i_pub_key->KeyType != ANSC_CERT_keyType_rsa)
{
AnscTrace("TlsCpoEncrypt_RSA(): Invalid key type.");
return ANSC_STATUS_FAILURE;
}
pGenParams = (PANSC_CRYPTO_PUB_KEY_GEN_PARAMS)i_pub_key->KeyData;
params.Key.RSA.RsaPublicKey = pGenParams->PublicKey.RSA;
Alg = ANSC_CRYPTO_PUB_ALGORITHM_RSA_ENCRYPTION;
Op = ANSC_CRYPTO_PUB_OPERATION_ENCRYPT;
params.InputSize = i_data_size;
params.pInput = (PVOID)i_data;
params.OutputSize = *o_data_size;
params.pOutput = (PVOID)o_data;
returnStatus =
pSSLCrypto->Request
(
Alg,
Op,
(ANSC_HANDLE)¶ms,
NULL,
NULL
);
*o_data_size = params.OutputSize;
return returnStatus;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
TlsCpoDecrypt_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_prv_key,
void* i_data,
ULONG i_data_size,
void* o_data,
PULONG o_data_size
);
description:
This function is called to perform RSA decryption by using
the specifies private key.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ANSC_X509_KEY* i_prv_key
Specifies the private key to be used for decryption.
void* i_data
Specifies the cipher text data to be decrypted.
ULONG i_data_size
Specifies the size of the cihper text data.
void* o_data
Specifies the output buffer of plain text data.
PULONG o_data_size
As an input parameter, it specifies the size of the
output buffer; as an output parameter, it specifies
the size of the real output.
return: status of operation.
**********************************************************************/
ANSC_STATUS
TlsCpoDecrypt_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_prv_key,
void* i_data,
ULONG i_data_size,
void* o_data,
PULONG o_data_size
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PTLS_CRYPTO_PROVIDER_OBJECT pMyObject = (PTLS_CRYPTO_PROVIDER_OBJECT)hThisObject;
PANSC_CRYPTO_PUB_OBJECT pSSLCrypto = (PANSC_CRYPTO_PUB_OBJECT )pMyObject->hAnscCryptoPub;
ANSC_CRYPTO_PUB_KEY_PARAMS params;
PANSC_CRYPTO_PUB_KEY_GEN_PARAMS pGenParams;
ANSC_CRYPTO_PUB_ALGORITHM Alg;
ANSC_CRYPTO_PUB_OPERATION Op;
if( i_prv_key == NULL)
{
return ANSC_STATUS_FAILURE;
}
if( i_prv_key->KeyType != ANSC_CERT_keyType_rsa)
{
AnscTrace("TlsCpoEncrypt_RSA(): Invalid key type.");
return ANSC_STATUS_FAILURE;
}
pGenParams = (PANSC_CRYPTO_PUB_KEY_GEN_PARAMS)i_prv_key->KeyData;
params.Key.RSA.RsaPrivateKey = pGenParams->PrivateKey.RSA;
Alg = ANSC_CRYPTO_PUB_ALGORITHM_RSA_ENCRYPTION;
Op = ANSC_CRYPTO_PUB_OPERATION_DECRYPT;
params.InputSize = i_data_size;
params.pInput = (PVOID)i_data;
params.OutputSize = *o_data_size;
params.pOutput = (PVOID)o_data;
returnStatus =
pSSLCrypto->Request
(
Alg,
Op,
(ANSC_HANDLE)¶ms,
NULL,
NULL
);
*o_data_size = params.OutputSize;
return returnStatus;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
TlsCpoSign
(
ANSC_HANDLE hThisObject,
ULONG key_type,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* o_sig,
PULONG o_sig_size
);
description:
This function is called to generate a digital signature.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ULONG key_type
Specifie the private key type to be used.
ANSC_X509_KEY* i_key
Specifies the private key to be used for signing.
void* i_data
Specifies the plain text data to be signed.
ULONG i_data_size
Specifies the size of the plain text data.
void* o_sig
Specifies the output buffer of signature data.
PULONG o_sig_size
As an input parameter, it specifies the size of the
output buffer; as an output parameter, it specifies
the size of the real output.
return: status of operation.
**********************************************************************/
ANSC_STATUS
TlsCpoSign
(
ANSC_HANDLE hThisObject,
ULONG key_type,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* o_sig,
PULONG o_sig_size
)
{
if( key_type == ANSC_CERT_keyType_rsa)
{
return
TlsCpoSign_RSA
(
hThisObject,
i_key,
i_data,
i_data_size,
o_sig,
o_sig_size
);
}
else if( key_type == ANSC_CERT_keyType_dsa)
{
return
TlsCpoSign_DSA
(
hThisObject,
i_key,
i_data,
i_data_size,
o_sig,
o_sig_size
);
}
AnscTrace("Unsupported sign key type : '%d'\n", key_type);
return ANSC_STATUS_FAILURE;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
TlsCpoSign_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* o_sig,
PULONG o_sig_size
);
description:
This function is called to generate a RSA digital signature.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ANSC_X509_KEY* i_key
Specifies the private key to be used for signing.
void* i_data
Specifies the plain text data to be signed.
ULONG i_data_size
Specifies the size of the plain text data.
void* o_sig
Specifies the output buffer of signature data.
PULONG o_sig_size
As an input parameter, it specifies the size of the
output buffer; as an output parameter, it specifies
the size of the real output.
return: status of operation.
**********************************************************************/
ANSC_STATUS
TlsCpoSign_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* o_sig,
PULONG o_sig_size
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PTLS_CRYPTO_PROVIDER_OBJECT pMyObject = (PTLS_CRYPTO_PROVIDER_OBJECT)hThisObject;
PANSC_CRYPTO_PUB_OBJECT pSSLCrypto = (PANSC_CRYPTO_PUB_OBJECT )pMyObject->hAnscCryptoPub;
ANSC_CRYPTO_PUB_KEY_PARAMS params;
PANSC_CRYPTO_PUB_KEY_GEN_PARAMS pGenParams;
ANSC_CRYPTO_PUB_ALGORITHM Alg;
ANSC_CRYPTO_PUB_OPERATION Op;
pGenParams = (PANSC_CRYPTO_PUB_KEY_GEN_PARAMS)i_key->KeyData;
params.Key.RSA.RsaPrivateKey = pGenParams->PrivateKey.RSA;
/* actually, here in TLS is encryption with RSA private key */
Op = ANSC_CRYPTO_PUB_OPERATION_PRI_ENCRYPT;
Alg = ANSC_CRYPTO_PUB_ALGORITHM_RSA_ENCRYPTION;
params.InputSize = i_data_size;
params.pInput = (PVOID)i_data;
params.OutputSize = *o_sig_size;
params.pOutput = (PVOID)o_sig;
returnStatus =
pSSLCrypto->Request
(
Alg,
Op,
(ANSC_HANDLE)¶ms,
NULL,
NULL
);
*o_sig_size = params.OutputSize;
#if 0
{
char pTemp[512] = { 0 };
AnscTrace("TlsCpoSign_RSA()\n");
AnscFromHexToString( i_data, pTemp, i_data_size, FALSE);
AnscTrace("The input hash value is (L%d):\n %s\n", i_data_size, pTemp);
AnscFromHexToString( o_sig, pTemp, *o_sig_size, FALSE);
AnscTrace("The input signature value is (L%d):\n %s\n", *o_sig_size, pTemp);
}
#endif
return returnStatus;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
TlsCpoSign_DSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* o_sig,
PULONG o_sig_size
);
description:
This function is called to generate a DSA digital signature.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ANSC_X509_KEY* i_key
Specifies the private key to be used for signing.
void* i_data
Specifies the plain text data to be signed.
ULONG i_data_size
Specifies the size of the plain text data.
void* o_sig
Specifies the output buffer of signature data.
PULONG o_sig_size
As an input parameter, it specifies the size of the
output buffer; as an output parameter, it specifies
the size of the real output.
return: status of operation.
**********************************************************************/
ANSC_STATUS
TlsCpoSign_DSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* o_sig,
PULONG o_sig_size
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PTLS_CRYPTO_PROVIDER_OBJECT pMyObject = (PTLS_CRYPTO_PROVIDER_OBJECT)hThisObject;
PANSC_CRYPTO_PUB_OBJECT pSSLCrypto = (PANSC_CRYPTO_PUB_OBJECT )pMyObject->hAnscCryptoPub;
ANSC_CRYPTO_PUB_KEY_PARAMS params;
PANSC_CRYPTO_PUB_KEY_GEN_PARAMS pGenParams;
ANSC_CRYPTO_PUB_ALGORITHM Alg;
ANSC_CRYPTO_PUB_OPERATION Op;
pGenParams = (PANSC_CRYPTO_PUB_KEY_GEN_PARAMS)i_key->KeyData;
params.Key.DSA.DsaPrivateKey = pGenParams->PrivateKey.DSA;
/* init the operation method */
Op = ANSC_CRYPTO_PUB_OPERATION_SIGN;
Alg = ANSC_CRYPTO_PUB_ALGORITHM_DSA;
params.InputSize = i_data_size;
params.pInput = (PVOID)i_data;
params.OutputSize = *o_sig_size;
params.pOutput = (PVOID)o_sig;
returnStatus =
pSSLCrypto->Request
(
Alg,
Op,
(ANSC_HANDLE)¶ms,
NULL,
NULL
);
*o_sig_size = params.OutputSize;
return returnStatus;
}
/**********************************************************************
caller: owner of this object
prototype:
BOOL
TlsCpoVerify
(
ANSC_HANDLE hThisObject,
ULONG key_type,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* i_sig,
ULONG i_sig_size
);
description:
This function is called to verify a digital signature.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ULONG key_type
Specifie the public key type to be used.
ANSC_X509_KEY* i_key
Specifies the public key to be used for verifying.
void* i_data
Specifies the plain text data to be verified.
ULONG i_data_size
Specifies the size of the plain text data.
void* i_sig
Specifies the signature to be verified.
ULONG i_data_size
Specifies the size of the signature.
return: TRUE or FALSE.
**********************************************************************/
BOOL
TlsCpoVerify
(
ANSC_HANDLE hThisObject,
ULONG key_type,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* i_sig,
ULONG i_sig_size
)
{
if( key_type == ANSC_CERT_keyType_rsa)
{
return
TlsCpoVerify_RSA
(
hThisObject,
i_key,
i_data,
i_data_size,
i_sig,
i_sig_size
);
}
else if( key_type == ANSC_CERT_keyType_dsa)
{
return
TlsCpoVerify_DSA
(
hThisObject,
i_key,
i_data,
i_data_size,
i_sig,
i_sig_size
);
}
AnscTrace("Unsupported sign key type : '%d'\n", key_type);
return FALSE;
}
/**********************************************************************
caller: owner of this object
prototype:
BOOL
TlsCpoVerify_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* i_sig,
ULONG i_sig_size
);
description:
This function is called to verify a RSA digital signature.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ANSC_X509_KEY* i_key
Specifies the public key to be used for verifying.
void* i_data
Specifies the plain text data to be verified.
ULONG i_data_size
Specifies the size of the plain text data.
void* i_sig
Specifies the signature to be verified.
ULONG i_data_size
Specifies the size of the signature.
return: TRUE or FALSE.
**********************************************************************/
BOOL
TlsCpoVerify_RSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* i_sig,
ULONG i_sig_size
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PTLS_CRYPTO_PROVIDER_OBJECT pMyObject = (PTLS_CRYPTO_PROVIDER_OBJECT)hThisObject;
PANSC_CRYPTO_PUB_OBJECT pSSLCrypto = (PANSC_CRYPTO_PUB_OBJECT )pMyObject->hAnscCryptoPub;
ANSC_CRYPTO_PUB_KEY_PARAMS params;
PANSC_CRYPTO_PUB_KEY_GEN_PARAMS pGenParams;
ANSC_CRYPTO_PUB_ALGORITHM Alg;
ANSC_CRYPTO_PUB_OPERATION Op;
UCHAR pOutput[512] = { 0 };
ULONG lenOfOut = 512;
pGenParams = (PANSC_CRYPTO_PUB_KEY_GEN_PARAMS)i_key->KeyData;
params.Key.RSA.RsaPublicKey = pGenParams->PublicKey.RSA;
/* actually, here in TLS is decryption with RSA public key */
Op = ANSC_CRYPTO_PUB_OPERATION_PUB_DECRYPT;
Alg = ANSC_CRYPTO_PUB_ALGORITHM_RSA_ENCRYPTION;
params.InputSize = i_sig_size;
params.pInput = (PVOID)i_sig;
params.OutputSize = lenOfOut;
params.pOutput = (PVOID)pOutput;
returnStatus =
pSSLCrypto->Request
(
Alg,
Op,
(ANSC_HANDLE)¶ms,
NULL,
NULL
);
if( returnStatus != ANSC_STATUS_SUCCESS)
{
AnscTrace("Failed to decrypt with RSA publickey.\n");
return FALSE;
}
#if 0
{
char pTemp[512] = { 0 };
AnscTrace("TlsCpoVerify_RSA()\n");
AnscFromHexToString( pOutput, pTemp, params.OutputSize, FALSE);
AnscTrace("The decrypted data value is (L%d):\n %s\n", params.OutputSize, pTemp);
}
#endif
if( params.OutputSize != i_data_size)
{
return FALSE;
}
if(!AnscEqualMemory(params.pOutput, i_data, i_data_size))
{
return FALSE;
}
return TRUE;
}
/**********************************************************************
caller: owner of this object
prototype:
BOOL
TlsCpoVerify_DSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* i_sig,
ULONG i_sig_size
);
description:
This function is called to verify a DSA digital signature.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
ANSC_X509_KEY* i_key
Specifies the public key to be used for verifying.
void* i_data
Specifies the plain text data to be verified.
ULONG i_data_size
Specifies the size of the plain text data.
void* i_sig
Specifies the signature to be verified.
ULONG i_data_size
Specifies the size of the signature.
return: TRUE or FALSE.
**********************************************************************/
BOOL
TlsCpoVerify_DSA
(
ANSC_HANDLE hThisObject,
ANSC_X509_KEY* i_key,
void* i_data,
ULONG i_data_size,
void* i_sig,
ULONG i_sig_size
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PTLS_CRYPTO_PROVIDER_OBJECT pMyObject = (PTLS_CRYPTO_PROVIDER_OBJECT)hThisObject;
PANSC_CRYPTO_PUB_OBJECT pSSLCrypto = (PANSC_CRYPTO_PUB_OBJECT )pMyObject->hAnscCryptoPub;
ANSC_CRYPTO_PUB_KEY_PARAMS params;
PANSC_CRYPTO_PUB_KEY_GEN_PARAMS pGenParams;
ANSC_CRYPTO_PUB_ALGORITHM Alg;
ANSC_CRYPTO_PUB_OPERATION Op;
pGenParams = (PANSC_CRYPTO_PUB_KEY_GEN_PARAMS)i_key->KeyData;
params.Key.DSA.DsaPublicKey = pGenParams->PublicKey.DSA;
/* init the operation method */
Op = ANSC_CRYPTO_PUB_OPERATION_VERIFY;
Alg = ANSC_CRYPTO_PUB_ALGORITHM_DSA;
params.InputSize = i_data_size;
params.pInput = (PVOID)i_data;
params.OutputSize = i_sig_size;
params.pOutput = (PVOID)i_sig;
returnStatus =
pSSLCrypto->Request
(
Alg,
Op,
(ANSC_HANDLE)¶ms,
NULL,
NULL
);
return (returnStatus == ANSC_STATUS_SUCCESS);
}
| 30.369878 | 106 | 0.475058 |
2880ffd79bec698ab1f5d12b205dddaa98201938 | 296 | h | C | project2D/ShapeJoint.h | Master-Mas/2D-Physics-Exmaple | a4ee3401daeb9150b8d2c8953bf6b0e70cacf93a | [
"MIT"
] | null | null | null | project2D/ShapeJoint.h | Master-Mas/2D-Physics-Exmaple | a4ee3401daeb9150b8d2c8953bf6b0e70cacf93a | [
"MIT"
] | null | null | null | project2D/ShapeJoint.h | Master-Mas/2D-Physics-Exmaple | a4ee3401daeb9150b8d2c8953bf6b0e70cacf93a | [
"MIT"
] | null | null | null | #pragma once
#include "GameObject.h"
class ShapeJoint :
public GameObject
{
public:
ShapeJoint(RigidBody2D* join1, RigidBody2D* join2, float springConstant, float damping);
~ShapeJoint();
void update(float deltaTime) override;
void draw(aie::Renderer2D& renderer) override;
private:
};
| 17.411765 | 89 | 0.756757 |
2881331cc07340a867c0ee82a3c8d464e993ca5d | 953 | h | C | System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored/AIMDownloadEvent.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 11 | 2019-11-06T04:48:48.000Z | 2022-02-09T17:48:15.000Z | System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored/AIMDownloadEvent.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 1 | 2020-04-16T01:41:56.000Z | 2020-04-16T04:32:00.000Z | System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored/AIMDownloadEvent.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 3 | 2019-12-22T20:17:53.000Z | 2021-01-25T09:47:49.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:38:55 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <appstored/AIMEvent.h>
@class NSNumber, NSURL, NSURLSessionTaskMetrics;
@interface AIMDownloadEvent : AIMEvent
@property (assign) BOOL deltaPackage;
@property (retain) NSNumber * drmMode;
@property (retain) NSURL * packageURL;
@property (retain) NSURLSessionTaskMetrics * taskMetrics;
-(NSURLSessionTaskMetrics *)taskMetrics;
-(void)setTaskMetrics:(NSURLSessionTaskMetrics *)arg1 ;
-(NSURL *)packageURL;
-(void)setPackageURL:(NSURL *)arg1 ;
-(void)setDeltaPackage:(BOOL)arg1 ;
-(void)setDrmMode:(NSNumber *)arg1 ;
-(id)copyMetricsDictionary;
-(BOOL)deltaPackage;
-(NSNumber *)drmMode;
@end
| 31.766667 | 92 | 0.76915 |
2881ae1ca01a58ec0c109dc1790867920d9c0987 | 372 | h | C | Schneider.iPad/Schneider/iControl/IControlViewController.h | iStig/iMeasure | 0960b74ffe5190ae5decc35dadb3bc6428b03c3e | [
"MIT"
] | null | null | null | Schneider.iPad/Schneider/iControl/IControlViewController.h | iStig/iMeasure | 0960b74ffe5190ae5decc35dadb3bc6428b03c3e | [
"MIT"
] | null | null | null | Schneider.iPad/Schneider/iControl/IControlViewController.h | iStig/iMeasure | 0960b74ffe5190ae5decc35dadb3bc6428b03c3e | [
"MIT"
] | null | null | null | //
// IControlViewController.h
// Schneider
//
// Created by GongXuehan on 13-4-15.
// Copyright (c) 2013年 xhgong. All rights reserved.
//
#import "SystemStructViewController.h"
#import "SwitchView.h"
#import "ControlSpecialStruct.h"
@interface IControlViewController : BaseViewController <SwitchViewDelegate, UITextFieldDelegate, UIGestureRecognizerDelegate>
@end
| 23.25 | 125 | 0.776882 |
93037a53b8c79eb470d983344278d07d7d4424a1 | 601 | h | C | MasterSimulatorUI/src/MSIMSceneManager.h | ghorwin/MasterSim | 281b71e228435ca8fa02319bf2ce86b66b8b2b45 | [
"BSD-3-Clause"
] | 5 | 2021-11-17T07:12:54.000Z | 2022-03-16T15:06:39.000Z | MasterSimulatorUI/src/MSIMSceneManager.h | ghorwin/MasterSim | 281b71e228435ca8fa02319bf2ce86b66b8b2b45 | [
"BSD-3-Clause"
] | 25 | 2021-09-09T07:39:13.000Z | 2022-01-23T13:00:19.000Z | MasterSimulatorUI/src/MSIMSceneManager.h | ghorwin/MasterSim | 281b71e228435ca8fa02319bf2ce86b66b8b2b45 | [
"BSD-3-Clause"
] | null | null | null | #ifndef MSIM_SCENEMANAGER_H
#define MSIM_SCENEMANAGER_H
#include <BM_SceneManager.h>
namespace BLOCKMOD {
class BlockItem;
class Block;
}
class MSIMSceneManager : public BLOCKMOD::SceneManager {
public:
explicit MSIMSceneManager(QObject *parent = nullptr);
protected:
/*! Create a graphics item based on the data in the given block.
You can override this method and create your own graphics items, derived from
base class BlockItem (which contains all the move/selection logic).
*/
BLOCKMOD::BlockItem * createBlockItem(BLOCKMOD::Block & b) override;
};
#endif // MSIM_SCENEMANAGER_H
| 23.115385 | 79 | 0.77371 |
930651b5d879e8ce1133d3146717b6b31d997b90 | 235 | h | C | ObjectTrackDemo/UIImage+Orientation.h | WhiteTeeth/ios11-ObjectTrackDemo | cb6f676d85aab5e353de9a91a3ee93f340adb9d3 | [
"MIT"
] | 31 | 2017-07-25T07:05:36.000Z | 2021-07-28T01:39:07.000Z | ObjectTrackDemo/UIImage+Orientation.h | WhiteTeeth/ios11-ObjectTrackDemo | cb6f676d85aab5e353de9a91a3ee93f340adb9d3 | [
"MIT"
] | 4 | 2018-03-01T08:54:13.000Z | 2019-05-13T14:35:34.000Z | ObjectTrackDemo/UIImage+Orientation.h | WhiteTeeth/ios11-ObjectTrackDemo | cb6f676d85aab5e353de9a91a3ee93f340adb9d3 | [
"MIT"
] | 8 | 2017-07-28T03:08:44.000Z | 2019-11-20T01:02:19.000Z | //
// UIImage+Orientation.h
// ObjectTrackDemo
//
// Created by baiya on 2017/6/22.
// Copyright © 2017年 Maxcw. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (Orientation)
- (UIImage *)fixOrientation;
@end
| 14.6875 | 49 | 0.685106 |
930c2e15bf08079a09dd89c36911efe5dad68131 | 598 | c | C | doc/tpdb_trs/C/SV-COMP_Termination_Category/UrbanMine-ESOP2014-Fig3_true-termination.c | ComputationWithBoundedResources/ara-inference | 970fcf905d89c3a769615cd81cc77e1903469dd5 | [
"MIT"
] | 1 | 2018-09-03T09:26:13.000Z | 2018-09-03T09:26:13.000Z | doc/tpdb_trs/C/SV-COMP_Termination_Category/UrbanMine-ESOP2014-Fig3_true-termination.c | ComputationWithBoundedResources/ara-inference | 970fcf905d89c3a769615cd81cc77e1903469dd5 | [
"MIT"
] | null | null | null | doc/tpdb_trs/C/SV-COMP_Termination_Category/UrbanMine-ESOP2014-Fig3_true-termination.c | ComputationWithBoundedResources/ara-inference | 970fcf905d89c3a769615cd81cc77e1903469dd5 | [
"MIT"
] | null | null | null | /*
* Program from Fig.3 of
* 2014ESOP - Urban,Miné - An Abstract Domain to Infer Ordinal-Valued Ranking Functions
*
* Date: 2014
* Author: Caterina Urban
*/
extern int __VERIFIER_nondet_int(void);
int main() {
int x = __VERIFIER_nondet_int();
int y = __VERIFIER_nondet_int();
while (x != 0 && y > 0) {
if (x > 0) {
if (__VERIFIER_nondet_int()) {
x = x - 1;
y = __VERIFIER_nondet_int();
} else {
y = y - 1;
}
} else {
if (__VERIFIER_nondet_int()) {
x = x + 1;
} else {
y = y - 1;
x = __VERIFIER_nondet_int();
}
}
}
} | 19.290323 | 87 | 0.553512 |
931047b8dac3f1fb5d14af1b12a4277ab5703d97 | 2,186 | h | C | src/shared/game/gta3/CAEBankLoader.h | gtaisbetterthanfn/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 186 | 2015-01-18T05:46:11.000Z | 2022-03-22T10:03:44.000Z | src/shared/game/gta3/CAEBankLoader.h | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 82 | 2015-01-14T01:02:04.000Z | 2022-03-20T23:55:59.000Z | src/shared/game/gta3/CAEBankLoader.h | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 34 | 2015-01-07T11:17:00.000Z | 2022-02-28T00:16:20.000Z | #pragma once
#pragma pack(push, 1)
struct CAEBankLookupItem
{
char m_iPak;
char _pad[3];
unsigned int m_dwOffset;
unsigned int m_dwSize;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct CAEBankSlotItem
{
unsigned int m_dwOffset;
unsigned int m_dwLoopOffset;
unsigned short m_usSampleRate;
short m_usSoundHeadroom;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct CAEBankSlot
{
unsigned int m_dwOffsetOnBuffer;
unsigned int m_dwSlotBufferSize;
int _unused1; // Actually used
int _unused2; // Actually used
unsigned short m_usBankNum;
unsigned short m_nSoundsOnBank; // 0xFFFF for single sound rqs
CAEBankSlotItem m_aBankItems[400];
};
#pragma pack(pop)
#pragma pack(push, 1)
struct CAESoundRequest
{
CAEBankSlot *m_pBankSlot;
unsigned int m_dwOffset;
unsigned int m_dwSize;
void *m_pBufferData;
void *m_pBuffer;
int m_iLoadingStatus;
unsigned short m_usBank;
unsigned short m_usBankSlot;
unsigned short m_usSound;
char m_iPak;
char field_1F;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct CAEBankLoader
{
CAEBankSlot *m_pBankSlots;
CAEBankLookupItem *m_pBankLookup;
char *m_pPakFiles;
short m_usNumBankSlots;
short m_usNumBanks;
short m_iNumPakFiles;
short _unused0;
char m_bInitialized;
char gap_15[3];
unsigned int m_iSoundBuffersSize;
char *m_pSoundBuffers;
int *m_StreamHandles;
CAESoundRequest m_aSoundRequests[50];
short _unk0;
short m_nRequestsToLoad;
short m_iRequestListNext;
short m_iStreamingChannel;
unsigned short m_aBankSlotSound[45];
char _unused1[30];
};
#pragma pack(pop)
#pragma pack(push, 1)
struct BankHeader
{
unsigned short m_nSounds;
short _pad;
CAEBankSlotItem m_aSounds[400];
};
#pragma pack(pop)
static_assert(sizeof(CAEBankLoader) == 0x6E4, "Incorrect struct size: CAEBankLoader");
static_assert(sizeof(CAESoundRequest) == 0x20, "Incorrect struct size: CAESoundRequest");
static_assert(sizeof(CAEBankSlot) == 0x12D4, "Incorrect struct size: CAEBankSlot");
static_assert(sizeof(CAEBankLookupItem) == 0x0C, "Incorrect struct size: CAEBankLookupItem");
| 23.010526 | 96 | 0.727813 |
9311f7613e15bb90cfe6bae1ef633fe909d7246b | 8,358 | h | C | src/Value.h | Beidah/Iliad | 2e86bbb160b471f3b8d9981c649990149eb47b5e | [
"Apache-2.0"
] | 2 | 2018-07-23T13:50:58.000Z | 2018-08-02T18:25:33.000Z | src/Value.h | Beidah/Iliad | 2e86bbb160b471f3b8d9981c649990149eb47b5e | [
"Apache-2.0"
] | null | null | null | src/Value.h | Beidah/Iliad | 2e86bbb160b471f3b8d9981c649990149eb47b5e | [
"Apache-2.0"
] | null | null | null | //! \file Value.h
//! \brief Details the data representation used by the program.
#pragma once
#include "ValueType.h"
//! Basical value representation
/*!
Values are stored in an std::vector of unsigned chars of the binary of the value.
This class stores the bytes, size and an enum of the type of data that is represented.
Basic arithmetic operators are overloaded to make using values in the compiler code as easy
as using normal data-types. Values are stored in little endian.
*/
class Value {
private:
const ValueType m_Type; //!< The type the value represents.
size_t m_Size; //!< Size of the data in bytes.
ByteArray m_Data; //!< Bytes of data. Stored in little endian.
bool m_Initialized; //!< If it has been given a value to begin with or not.
public:
//!@{ \name Constructors
//! Initilizes values
//! Default constructor, returns an "Null" value
Value() : m_Type(ValueType::Null), m_Size(0), m_Initialized(false) {}
//! Copy constructor
Value(const Value& value);
private:
//! Main constructor
/*!
This constructor is the one called by the templated one, and initilizes a valid value.
\param bytes A vector<uint8_t> of the binary to be stored, in little endian.
\param type ValueType of value.
*/
Value(ByteArray bytes, ValueType type);
public:
//! Template constructor, takes in a value and serializes it.
/*!
Calls main constructor after passing input through both toBytes and getType
\param value value of any supported ValueType.
*/
template<typename T, typename = std::enable_if_t<!std::is_same_v<T, Value&>&& !std::is_same_v<T, Value>>>
Value(T&& value) : Value(Serialize::toBytes<T>(value), Transformer::getType(value)) {}
//! Creates an "uninitilized" value of the given type.
Value(ValueType type) : m_Type(type), m_Size(ValueTypeSize(type)), m_Initialized(false) { m_Data.reserve(m_Size); }
//!@}
//!@{ \name Getters
//! Gets const data from private members.
//! Converts byte array into type T
/*! Converts the data into a usable value type. Is able to cast to appropiate types.
May result in data lost if used to convert a float to an integral or a larger value
to a smaller one.
\return Value called for.
*/
template<typename T>
T AsValue() const;
//! Specialized AsValue for bool values. Returns bool operator
template<>
bool AsValue<bool>() const { return static_cast<bool>(*this); }
//! Specialized AsValue for float values.
template <>
float AsValue<float>() const {
// If value is not a number, it's not convertable to a float.
if (!IsNumber()) return 0;
if (m_Type == ValueType::Float) {
int32_t intermediate = 0;
for (size_t i = 0; i < m_Size; i++) {
intermediate |= (m_Data[i] << (8 * (m_Size - i - 1)));
}
return reinterpret_cast<float&>(intermediate);
} else {
switch (m_Type) {
case ValueType::Int8: return static_cast<float>(AsValue<int8_t>());
case ValueType::Int16: return static_cast<float>(AsValue<int16_t>());
case ValueType::Int32: return static_cast<float>(AsValue<int32_t>());
case ValueType::Int64: return static_cast<float>(AsValue<int64_t>());
case ValueType::Double: return static_cast<float>(AsValue<double>());
default: return 0; // Unreachable
}
}
}
//! Specialized AsValue for double Values.
template <>
double AsValue<double>() const {
// If value is not a number, it's not convertable to a float.
if (!IsNumber()) return 0;
if (m_Type == ValueType::Double) {
int64_t intermediate = 0;
for (size_t i = 0; i < m_Size; i++) {
intermediate |= (m_Data[i] << (8 * (m_Size - i - 1)));
}
return reinterpret_cast<double&>(intermediate);
} else {
switch (m_Type) {
case ValueType::Int8: return static_cast<double>(AsValue<int8_t>());
case ValueType::Int16: return static_cast<double>(AsValue<int16_t>());
case ValueType::Int32: return static_cast<double>(AsValue<int32_t>());
case ValueType::Int64: return static_cast<double>(AsValue<int64_t>());
case ValueType::Float: return static_cast<double>(AsValue<float>());
default: return 0; // Unreachable
}
}
}
//! Specialized AsValue for string values.
template<>
std::string AsValue<std::string>() const {
if (IsChar() || IsString())
return std::string(m_Data.begin(), m_Data.end());
else return ToString();
}
//! returns a byte array of the value.
const ByteArray& AsBytes() const;
//! A string representation of the value for printing.
std::string ToString() const;
//! \return Size of Value in bytes.
size_t Size() const { return m_Size; }
//! \return ValueType of Value.
const ValueType& Type() const { return m_Type; }
//!@}
//!@{ \name Operators
//!@{ Unary operator.
//! \brief Multiplies the value by -1 to get its negative
/*!
\return If Value is a number, a new Value of opposite value, otherwise, returns self.
*/
Value operator-() const;
//!@}
//!@{ Binary operator, should only be used for number values.
Value operator+(Value value) const;
Value operator-(Value value) const;
Value operator*(Value value) const;
Value operator/(Value value) const;
//!@}
//!@{ Assignment
Value& operator=(const Value& value);
template<typename T>
Value& operator=(T value) {
m_Data = Serialize::toBytes(FWD(value));
m_Initialized = true;
return *this;
}
template<>
Value& operator=<std::string>(std::string value) {
m_Size = value.size();
m_Data.assign(value.begin(), value.end());
m_Initialized = true;
return *this;
}
//!@}
//!@{ Comparison
//! \todo When available, replace with C++20 "spaceship" operator using partial_ordering for unorderable comparisons.
bool operator==(const Value& value) const;
bool operator!=(const Value& value) const { return !(*this == value); }
bool operator<(const Value& value) const;
bool operator>(const Value& value) const { return value < *this; }
bool operator<=(const Value& value) const { return (*this < value) || (*this == value); }
bool operator>=(const Value& value) const { return (*this > value) || (*this == value); }
//!@}
//!@{ Boolean value
explicit operator bool() const;
//!@}
//!@}
//!@{ \name Utilities
//! Functions to help determine the type of Value
inline bool IsNumber() const { return m_Type >= ValueType::Int8 && m_Type <= ValueType::Double; }
inline bool IsIntegral() const { return m_Type >= ValueType::Int8 && m_Type <= ValueType::Int64; }
inline bool IsDecimal() const { return m_Type >= ValueType::Float && m_Type <= ValueType::Double; }
inline bool IsBoolean() const { return m_Type == ValueType::Bool; }
inline bool IsChar() const { return m_Type == ValueType::Char; }
inline bool IsString() const { return m_Type == ValueType::String; }
inline bool IsNull() const { return m_Type == ValueType::Null; }
inline bool IsInitilized() const { return m_Initialized; }
inline bool IsValid() const { return m_Type != ValueType::Invalid; }
//!@}
};
template<typename T>
T Value::AsValue() const {
static_assert(std::is_arithmetic<T>::value, "Type mismatch.");
// If finding the boolean, use bool operator.
if (std::is_same<T, bool>()) {
return static_cast<bool>(*this);
}
// If the types matchup, just convert byte array to type.
if (m_Type == Transformer::getType(T())) {
T value = 0;
for (size_t i = 0; i < m_Size; i++) {
value |= (m_Data[i] << (8 * (m_Size - i - 1)));
}
return value;
}
if (IsDecimal()) {
if (m_Type == ValueType::Float) {
int32_t intermediate = 0;
for (size_t i = 0; i < m_Size; i++) {
intermediate |= (m_Data[i] << (8 * (m_Size - i - 1)));
}
float floatVal = reinterpret_cast<float&>(intermediate);
return static_cast<T>(floatVal);
} else if (m_Type == ValueType::Double) {
int64_t intermediate = 0;
for (size_t i = 0; i < m_Size; i++) {
intermediate |= (m_Data[i] << (8 * (m_Size - i - 1)));
}
double doubleVal = reinterpret_cast<double&>(intermediate);
return static_cast<T>(doubleVal);
}
}
// If types do not match up, get origianl type and convert.
switch (m_Type) {
case ValueType::Int8: return static_cast<T>(AsValue<int8_t>());
case ValueType::Int16: return static_cast<T>(AsValue<int16_t>());
case ValueType::Int32: return static_cast<T>(AsValue<int32_t>());
case ValueType::Int64: return static_cast<T>(AsValue<int64_t>());
default: static_assert(true, "Type not supported.");
}
return T();
}
| 30.955556 | 118 | 0.676478 |
9317b967dda5d2dcc162d00a6efcac40994f56e2 | 28,980 | h | C | src/environments/gym-uds/gym-uds.grpc.pb.h | rval735/BiSUNA | 0475db39d10b61fa929a61a66a32686961a211ca | [
"Apache-1.1"
] | 6 | 2019-05-07T01:14:59.000Z | 2021-03-25T10:34:22.000Z | src/environments/gym-uds/gym-uds.grpc.pb.h | rval735/BiSUNA | 0475db39d10b61fa929a61a66a32686961a211ca | [
"Apache-1.1"
] | null | null | null | src/environments/gym-uds/gym-uds.grpc.pb.h | rval735/BiSUNA | 0475db39d10b61fa929a61a66a32686961a211ca | [
"Apache-1.1"
] | null | null | null | // Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: gym-uds.proto
#ifndef GRPC_gym_2duds_2eproto__INCLUDED
#define GRPC_gym_2duds_2eproto__INCLUDED
#include "gym-uds.pb.h"
#include <functional>
#include <grpcpp/impl/codegen/async_generic_service.h>
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
#include <grpcpp/impl/codegen/client_callback.h>
#include <grpcpp/impl/codegen/method_handler_impl.h>
#include <grpcpp/impl/codegen/proto_utils.h>
#include <grpcpp/impl/codegen/rpc_method.h>
#include <grpcpp/impl/codegen/server_callback.h>
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/impl/codegen/stub_options.h>
#include <grpcpp/impl/codegen/sync_stream.h>
namespace grpc {
class CompletionQueue;
class Channel;
class ServerCompletionQueue;
class ServerContext;
} // namespace grpc
class Environment final {
public:
static constexpr char const* service_full_name() {
return "Environment";
}
class StubInterface {
public:
virtual ~StubInterface() {}
virtual ::grpc::Status Reset(::grpc::ClientContext* context, const ::Empty& request, ::State* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>> AsyncReset(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>>(AsyncResetRaw(context, request, cq));
}
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>> PrepareAsyncReset(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>>(PrepareAsyncResetRaw(context, request, cq));
}
virtual ::grpc::Status Step(::grpc::ClientContext* context, const ::Action& request, ::State* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>> AsyncStep(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>>(AsyncStepRaw(context, request, cq));
}
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>> PrepareAsyncStep(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::State>>(PrepareAsyncStepRaw(context, request, cq));
}
virtual ::grpc::Status Sample(::grpc::ClientContext* context, const ::Empty& request, ::Action* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::Action>> AsyncSample(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::Action>>(AsyncSampleRaw(context, request, cq));
}
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::Action>> PrepareAsyncSample(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::Action>>(PrepareAsyncSampleRaw(context, request, cq));
}
class experimental_async_interface {
public:
virtual ~experimental_async_interface() {}
virtual void Reset(::grpc::ClientContext* context, const ::Empty* request, ::State* response, std::function<void(::grpc::Status)>) = 0;
virtual void Step(::grpc::ClientContext* context, const ::Action* request, ::State* response, std::function<void(::grpc::Status)>) = 0;
virtual void Sample(::grpc::ClientContext* context, const ::Empty* request, ::Action* response, std::function<void(::grpc::Status)>) = 0;
};
virtual class experimental_async_interface* experimental_async() { return nullptr; }
private:
virtual ::grpc::ClientAsyncResponseReaderInterface< ::State>* AsyncResetRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::State>* PrepareAsyncResetRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::State>* AsyncStepRaw(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::State>* PrepareAsyncStepRaw(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::Action>* AsyncSampleRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::Action>* PrepareAsyncSampleRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) = 0;
};
class Stub final : public StubInterface {
public:
Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel);
::grpc::Status Reset(::grpc::ClientContext* context, const ::Empty& request, ::State* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>> AsyncReset(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>>(AsyncResetRaw(context, request, cq));
}
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>> PrepareAsyncReset(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>>(PrepareAsyncResetRaw(context, request, cq));
}
::grpc::Status Step(::grpc::ClientContext* context, const ::Action& request, ::State* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>> AsyncStep(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>>(AsyncStepRaw(context, request, cq));
}
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>> PrepareAsyncStep(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::State>>(PrepareAsyncStepRaw(context, request, cq));
}
::grpc::Status Sample(::grpc::ClientContext* context, const ::Empty& request, ::Action* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::Action>> AsyncSample(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::Action>>(AsyncSampleRaw(context, request, cq));
}
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::Action>> PrepareAsyncSample(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::Action>>(PrepareAsyncSampleRaw(context, request, cq));
}
class experimental_async final :
public StubInterface::experimental_async_interface {
public:
void Reset(::grpc::ClientContext* context, const ::Empty* request, ::State* response, std::function<void(::grpc::Status)>) override;
void Step(::grpc::ClientContext* context, const ::Action* request, ::State* response, std::function<void(::grpc::Status)>) override;
void Sample(::grpc::ClientContext* context, const ::Empty* request, ::Action* response, std::function<void(::grpc::Status)>) override;
private:
friend class Stub;
explicit experimental_async(Stub* stub): stub_(stub) { }
Stub* stub() { return stub_; }
Stub* stub_;
};
class experimental_async_interface* experimental_async() override { return &async_stub_; }
private:
std::shared_ptr< ::grpc::ChannelInterface> channel_;
class experimental_async async_stub_{this};
::grpc::ClientAsyncResponseReader< ::State>* AsyncResetRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::State>* PrepareAsyncResetRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::State>* AsyncStepRaw(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::State>* PrepareAsyncStepRaw(::grpc::ClientContext* context, const ::Action& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::Action>* AsyncSampleRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::Action>* PrepareAsyncSampleRaw(::grpc::ClientContext* context, const ::Empty& request, ::grpc::CompletionQueue* cq) override;
const ::grpc::internal::RpcMethod rpcmethod_Reset_;
const ::grpc::internal::RpcMethod rpcmethod_Step_;
const ::grpc::internal::RpcMethod rpcmethod_Sample_;
};
static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions());
class Service : public ::grpc::Service {
public:
Service();
virtual ~Service();
virtual ::grpc::Status Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response);
virtual ::grpc::Status Step(::grpc::ServerContext* context, const ::Action* request, ::State* response);
virtual ::grpc::Status Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response);
};
template <class BaseClass>
class WithAsyncMethod_Reset : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_Reset() {
::grpc::Service::MarkMethodAsync(0);
}
~WithAsyncMethod_Reset() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestReset(::grpc::ServerContext* context, ::Empty* request, ::grpc::ServerAsyncResponseWriter< ::State>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_Step : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_Step() {
::grpc::Service::MarkMethodAsync(1);
}
~WithAsyncMethod_Step() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Step(::grpc::ServerContext* context, const ::Action* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestStep(::grpc::ServerContext* context, ::Action* request, ::grpc::ServerAsyncResponseWriter< ::State>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_Sample : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_Sample() {
::grpc::Service::MarkMethodAsync(2);
}
~WithAsyncMethod_Sample() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestSample(::grpc::ServerContext* context, ::Empty* request, ::grpc::ServerAsyncResponseWriter< ::Action>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag);
}
};
typedef WithAsyncMethod_Reset<WithAsyncMethod_Step<WithAsyncMethod_Sample<Service > > > AsyncService;
template <class BaseClass>
class ExperimentalWithCallbackMethod_Reset : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
ExperimentalWithCallbackMethod_Reset() {
::grpc::Service::experimental().MarkMethodCallback(0,
new ::grpc::internal::CallbackUnaryHandler< ::Empty, ::State>(
[this](::grpc::ServerContext* context,
const ::Empty* request,
::State* response,
::grpc::experimental::ServerCallbackRpcController* controller) {
return this->Reset(context, request, response, controller);
}));
}
~ExperimentalWithCallbackMethod_Reset() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
virtual void Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response, ::grpc::experimental::ServerCallbackRpcController* controller) { controller->Finish(::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "")); }
};
template <class BaseClass>
class ExperimentalWithCallbackMethod_Step : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
ExperimentalWithCallbackMethod_Step() {
::grpc::Service::experimental().MarkMethodCallback(1,
new ::grpc::internal::CallbackUnaryHandler< ::Action, ::State>(
[this](::grpc::ServerContext* context,
const ::Action* request,
::State* response,
::grpc::experimental::ServerCallbackRpcController* controller) {
return this->Step(context, request, response, controller);
}));
}
~ExperimentalWithCallbackMethod_Step() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Step(::grpc::ServerContext* context, const ::Action* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
virtual void Step(::grpc::ServerContext* context, const ::Action* request, ::State* response, ::grpc::experimental::ServerCallbackRpcController* controller) { controller->Finish(::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "")); }
};
template <class BaseClass>
class ExperimentalWithCallbackMethod_Sample : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
ExperimentalWithCallbackMethod_Sample() {
::grpc::Service::experimental().MarkMethodCallback(2,
new ::grpc::internal::CallbackUnaryHandler< ::Empty, ::Action>(
[this](::grpc::ServerContext* context,
const ::Empty* request,
::Action* response,
::grpc::experimental::ServerCallbackRpcController* controller) {
return this->Sample(context, request, response, controller);
}));
}
~ExperimentalWithCallbackMethod_Sample() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
virtual void Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response, ::grpc::experimental::ServerCallbackRpcController* controller) { controller->Finish(::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "")); }
};
typedef ExperimentalWithCallbackMethod_Reset<ExperimentalWithCallbackMethod_Step<ExperimentalWithCallbackMethod_Sample<Service > > > ExperimentalCallbackService;
template <class BaseClass>
class WithGenericMethod_Reset : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_Reset() {
::grpc::Service::MarkMethodGeneric(0);
}
~WithGenericMethod_Reset() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_Step : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_Step() {
::grpc::Service::MarkMethodGeneric(1);
}
~WithGenericMethod_Step() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Step(::grpc::ServerContext* context, const ::Action* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_Sample : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_Sample() {
::grpc::Service::MarkMethodGeneric(2);
}
~WithGenericMethod_Sample() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithRawMethod_Reset : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithRawMethod_Reset() {
::grpc::Service::MarkMethodRaw(0);
}
~WithRawMethod_Reset() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestReset(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithRawMethod_Step : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithRawMethod_Step() {
::grpc::Service::MarkMethodRaw(1);
}
~WithRawMethod_Step() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Step(::grpc::ServerContext* context, const ::Action* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestStep(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithRawMethod_Sample : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithRawMethod_Sample() {
::grpc::Service::MarkMethodRaw(2);
}
~WithRawMethod_Sample() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestSample(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class ExperimentalWithRawCallbackMethod_Reset : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
ExperimentalWithRawCallbackMethod_Reset() {
::grpc::Service::experimental().MarkMethodRawCallback(0,
new ::grpc::internal::CallbackUnaryHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>(
[this](::grpc::ServerContext* context,
const ::grpc::ByteBuffer* request,
::grpc::ByteBuffer* response,
::grpc::experimental::ServerCallbackRpcController* controller) {
this->Reset(context, request, response, controller);
}));
}
~ExperimentalWithRawCallbackMethod_Reset() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
virtual void Reset(::grpc::ServerContext* context, const ::grpc::ByteBuffer* request, ::grpc::ByteBuffer* response, ::grpc::experimental::ServerCallbackRpcController* controller) { controller->Finish(::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "")); }
};
template <class BaseClass>
class ExperimentalWithRawCallbackMethod_Step : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
ExperimentalWithRawCallbackMethod_Step() {
::grpc::Service::experimental().MarkMethodRawCallback(1,
new ::grpc::internal::CallbackUnaryHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>(
[this](::grpc::ServerContext* context,
const ::grpc::ByteBuffer* request,
::grpc::ByteBuffer* response,
::grpc::experimental::ServerCallbackRpcController* controller) {
this->Step(context, request, response, controller);
}));
}
~ExperimentalWithRawCallbackMethod_Step() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Step(::grpc::ServerContext* context, const ::Action* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
virtual void Step(::grpc::ServerContext* context, const ::grpc::ByteBuffer* request, ::grpc::ByteBuffer* response, ::grpc::experimental::ServerCallbackRpcController* controller) { controller->Finish(::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "")); }
};
template <class BaseClass>
class ExperimentalWithRawCallbackMethod_Sample : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
ExperimentalWithRawCallbackMethod_Sample() {
::grpc::Service::experimental().MarkMethodRawCallback(2,
new ::grpc::internal::CallbackUnaryHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>(
[this](::grpc::ServerContext* context,
const ::grpc::ByteBuffer* request,
::grpc::ByteBuffer* response,
::grpc::experimental::ServerCallbackRpcController* controller) {
this->Sample(context, request, response, controller);
}));
}
~ExperimentalWithRawCallbackMethod_Sample() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
virtual void Sample(::grpc::ServerContext* context, const ::grpc::ByteBuffer* request, ::grpc::ByteBuffer* response, ::grpc::experimental::ServerCallbackRpcController* controller) { controller->Finish(::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "")); }
};
template <class BaseClass>
class WithStreamedUnaryMethod_Reset : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_Reset() {
::grpc::Service::MarkMethodStreamed(0,
new ::grpc::internal::StreamedUnaryHandler< ::Empty, ::State>(std::bind(&WithStreamedUnaryMethod_Reset<BaseClass>::StreamedReset, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_Reset() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status Reset(::grpc::ServerContext* context, const ::Empty* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedReset(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::Empty,::State>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_Step : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_Step() {
::grpc::Service::MarkMethodStreamed(1,
new ::grpc::internal::StreamedUnaryHandler< ::Action, ::State>(std::bind(&WithStreamedUnaryMethod_Step<BaseClass>::StreamedStep, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_Step() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status Step(::grpc::ServerContext* context, const ::Action* request, ::State* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedStep(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::Action,::State>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_Sample : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_Sample() {
::grpc::Service::MarkMethodStreamed(2,
new ::grpc::internal::StreamedUnaryHandler< ::Empty, ::Action>(std::bind(&WithStreamedUnaryMethod_Sample<BaseClass>::StreamedSample, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_Sample() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status Sample(::grpc::ServerContext* context, const ::Empty* request, ::Action* response) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedSample(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::Empty,::Action>* server_unary_streamer) = 0;
};
typedef WithStreamedUnaryMethod_Reset<WithStreamedUnaryMethod_Step<WithStreamedUnaryMethod_Sample<Service > > > StreamedUnaryService;
typedef Service SplitStreamedService;
typedef WithStreamedUnaryMethod_Reset<WithStreamedUnaryMethod_Step<WithStreamedUnaryMethod_Sample<Service > > > StreamedService;
};
#endif // GRPC_gym_2duds_2eproto__INCLUDED
| 55.095057 | 262 | 0.703899 |
9318eda6b253660e97d7223bfbfa12fd5bcff6bb | 23,082 | h | C | ns3/ns-3.26/src/network/model/net-device.h | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 7 | 2017-08-11T06:06:47.000Z | 2022-02-27T07:34:33.000Z | ns3/ns-3.26/src/network/model/net-device.h | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 3 | 2017-08-11T03:04:59.000Z | 2017-09-11T14:01:14.000Z | ns3/ns-3.26/src/network/model/net-device.h | Aedemon/clusim | 7f09cdb79b5f02cf0fed1bd44842981941f29f32 | [
"Apache-2.0"
] | 3 | 2017-08-08T13:36:30.000Z | 2018-07-04T09:49:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2005,2006 INRIA
*
* 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;
*
* 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
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
* Modified by Emmanuelle Laprise to remove dependence on LLC headers
* Modified by Stefano Avallone to add NetDeviceQueue and NetDeviceQueueInterface
*/
#ifndef NET_DEVICE_H
#define NET_DEVICE_H
#include <string>
#include <vector>
#include <stdint.h>
#include "ns3/callback.h"
#include "ns3/object.h"
#include "ns3/ptr.h"
#include "address.h"
#include "ns3/ipv4-address.h"
#include "ns3/ipv6-address.h"
namespace ns3 {
class Node;
class Channel;
class Packet;
class QueueLimits;
/**
* \ingroup network
* \defgroup netdevice Network Device
*/
/**
* \ingroup netdevice
* \brief Base class to represent items of packet Queues
*
* An item stored in an ns-3 packet Queue contains a packet and possibly other
* information. An item of the base class only contains a packet. Subclasses
* can be derived from this base class to allow items to contain additional
* information.
*/
class QueueItem : public SimpleRefCount<QueueItem>
{
public:
/**
* \brief Create a queue item containing a packet.
* \param p the packet included in the created item.
*/
QueueItem (Ptr<Packet> p);
virtual ~QueueItem ();
/**
* \return the packet included in this item.
*/
Ptr<Packet> GetPacket (void) const;
/**
* \brief Use this method (instead of GetPacket ()->GetSize ()) to get the packet size
*
* Subclasses may keep header and payload separate to allow manipulating the header,
* so using this method ensures that the correct packet size is returned.
*
* \return the size of the packet included in this item.
*/
virtual uint32_t GetPacketSize (void) const;
/**
* \enum Uint8Values
* \brief 1-byte fields of the packet whose value can be retrieved, if present
*/
enum Uint8Values
{
IP_DSFIELD
};
/**
* \brief Retrieve the value of a given field from the packet, if present
* \param field the field whose value has to be retrieved
* \param value the output parameter to store the retrieved value
*
* \return true if the requested field is present in the packet, false otherwise.
*/
virtual bool GetUint8Value (Uint8Values field, uint8_t &value) const;
/**
* \brief Print the item contents.
* \param os output stream in which the data should be printed.
*/
virtual void Print (std::ostream &os) const;
/**
* TracedCallback signature for Ptr<QueueItem>
*
* \param [in] item The queue item.
*/
typedef void (* TracedCallback) (Ptr<const QueueItem> item);
private:
/**
* \brief Default constructor
*
* Defined and unimplemented to avoid misuse
*/
QueueItem ();
/**
* \brief Copy constructor
*
* Defined and unimplemented to avoid misuse
*/
QueueItem (const QueueItem &);
/**
* \brief Assignment operator
*
* Defined and unimplemented to avoid misuse
* \returns
*/
QueueItem &operator = (const QueueItem &);
/**
* The packet contained in the queue item.
*/
Ptr<Packet> m_packet;
};
/**
* \brief Stream insertion operator.
*
* \param os the stream
* \param item the item
* \returns a reference to the stream
*/
std::ostream& operator<< (std::ostream& os, const QueueItem &item);
/**
* \ingroup netdevice
*
* \brief Network device transmission queue
*
* This class stores information about a single transmission queue
* of a network device that is exposed to queue discs. Such information
* includes the state of the transmission queue (whether it has been
* stopped or not) and data used by techniques such as Byte Queue Limits.
*
* This class roughly models the struct netdev_queue of Linux.
*/
class NetDeviceQueue : public SimpleRefCount<NetDeviceQueue>
{
public:
NetDeviceQueue ();
virtual ~NetDeviceQueue();
/**
* Called by the device to start this device transmission queue.
* This is the analogous to the netif_tx_start_queue function of the Linux kernel.
*/
virtual void Start (void);
/**
* Called by the device to stop this device transmission queue.
* This is the analogous to the netif_tx_stop_queue function of the Linux kernel.
*/
virtual void Stop (void);
/**
* Called by the device to wake the queue disc associated with this
* device transmission queue. This is done by invoking the wake callback.
* This is the analogous to the netif_tx_wake_queue function of the Linux kernel.
*/
virtual void Wake (void);
/**
* \brief Get the status of the device transmission queue.
* \return true if the device transmission queue is stopped.
*
* Called by queue discs to enquire about the status of a given transmission queue.
* This is the analogous to the netif_tx_queue_stopped function of the Linux kernel.
*/
bool IsStopped (void) const;
/// Callback invoked by netdevices to wake upper layers
typedef Callback< void > WakeCallback;
/**
* \brief Set the wake callback
* \param cb the callback to set
*
* Called by the traffic control layer to set the wake callback. The wake callback
* is invoked by the device whenever it is needed to "wake" the upper layers (i.e.,
* solicitate the queue disc associated with this transmission queue (in case of
* multi-queue aware queue discs) or to the network device (otherwise) to send
* packets down to the device).
*/
virtual void SetWakeCallback (WakeCallback cb);
/**
* \brief Called by the netdevice to report the number of bytes queued to the device queue
* \param bytes number of bytes queued to the device queue
*/
void NotifyQueuedBytes (uint32_t bytes);
/**
* \brief Called by the netdevice to report the number of bytes it is going to transmit
* \param bytes number of bytes the device is going to transmit
*/
void NotifyTransmittedBytes (uint32_t bytes);
/**
* \brief Reset queue limits state
*/
void ResetQueueLimits ();
/**
* \brief Set queue limits to this queue
* \param ql the queue limits associated to this queue
*/
void SetQueueLimits (Ptr<QueueLimits> ql);
/**
* \brief Get queue limits to this queue
* \return the queue limits associated to this queue
*/
Ptr<QueueLimits> GetQueueLimits ();
private:
bool m_stoppedByDevice; //!< True if the queue has been stopped by the device
bool m_stoppedByQueueLimits; //!< True if the queue has been stopped by a queue limits object
Ptr<QueueLimits> m_queueLimits; //!< Queue limits object
WakeCallback m_wakeCallback; //!< Wake callback
};
/**
* \ingroup netdevice
*
* \brief Network device transmission queue interface
*
* This interface is used by the traffic control layer and by the aggregated
* device to access the transmission queues of the device. Additionally, through
* this interface, traffic control aware netdevices can:
* - set the number of transmission queues
* - set the method used (by upper layers) to determine the transmission queue
* in which the netdevice would enqueue a given packet
* This interface is created and aggregated to a device by the traffic control
* layer when an Ipv{4,6}Interface is added to the device or a queue disc is
* installed on the device.
*/
class NetDeviceQueueInterface : public Object
{
public:
/**
* \brief Get the type ID.
* \return the object TypeId
*/
static TypeId GetTypeId (void);
/**
* \brief Constructor
*
* Creates one NetDeviceQueue by default
*/
NetDeviceQueueInterface ();
virtual ~NetDeviceQueueInterface ();
/**
* \brief Get the i-th transmission queue of the device.
*
* \param i the index of the requested queue.
* \return the i-th transmission queue of the device.
*
* The index of the first transmission queue is zero.
*/
Ptr<NetDeviceQueue> GetTxQueue (uint8_t i) const;
/**
* \brief Get the number of device transmission queues.
* \return the number of device transmission queues.
*/
uint8_t GetNTxQueues (void) const;
/**
* \brief Set the number of device transmission queues to create.
* \param numTxQueues number of device transmission queues to create.
*
* A multi-queue netdevice must call this method from within its
* NotifyNewAggregate method to set the number of device transmission queues
* to create.
*/
void SetTxQueuesN (uint8_t numTxQueues);
/**
* \brief Create the device transmission queues.
*
* Called by the traffic control layer just after aggregating this netdevice
* queue interface to the netdevice.
*/
void CreateTxQueues (void);
/// Callback invoked to determine the tx queue selected for a given packet
typedef Callback< uint8_t, Ptr<QueueItem> > SelectQueueCallback;
/**
* \brief Set the select queue callback.
* \param cb the callback to set.
*
* A multi-queue netdevice must call this method from within its
* NotifyNewAggregate method to set the select queue callback, i.e., the
* method used to select a device transmission queue for a given packet.
*/
void SetSelectQueueCallback (SelectQueueCallback cb);
/**
* \brief Get the select queue callback.
* \return the select queue callback.
*
* Called by the traffic control layer to get the select queue callback set
* by a multi-queue device.
*/
SelectQueueCallback GetSelectQueueCallback (void) const;
protected:
/**
* \brief Dispose of the object
*/
virtual void DoDispose (void);
private:
std::vector< Ptr<NetDeviceQueue> > m_txQueuesVector; //!< Device transmission queues
SelectQueueCallback m_selectQueueCallback; //!< Select queue callback
uint8_t m_numTxQueues; //!< Number of transmission queues to create
};
/**
* \ingroup netdevice
*
* \brief Network layer to device interface
*
* This interface defines the API which the IP and ARP
* layers need to access to manage an instance of a network device
* layer. It currently does not support MAC-level
* multicast but this should not be too hard to add by adding
* extra methods to register MAC multicast addresses to
* filter out unwanted packets before handing them to the
* higher layers.
*
* In Linux, this interface is analogous to the interface
* just above dev_queue_xmit() (i.e., IP packet is fully
* constructed with destination MAC address already selected).
*
* If you want to write a new MAC layer, you need to subclass
* this base class and implement your own version of the
* pure virtual methods in this class.
*
* This class was designed to hide as many MAC-level details as
* possible from the perspective of layer 3 to allow a single layer 3
* to work with any kind of MAC layer. Specifically, this class
* encapsulates the specific format of MAC addresses used by a
* device such that the layer 3 does not need any modification
* to handle new address formats. This means obviously that the
* NetDevice class must know about the address format of all potential
* layer 3 protocols through its GetMulticast methods: the current
* API has been optimized to make it easy to add new MAC protocols,
* not to add new layer 3 protocols.
*
* Devices aiming to be Traffic Control aware must implement a NotifyNewAggregate
* method to perform the following operations:
* - cache the pointer to the netdevice queue interface aggregated to the device
* - set the number of device transmission queues through the netdevice queue
* interface, if the device is multi-queue
* - set the select queue callback through the netdevice queue interface, if
* the device is multi-queue
* In order to support flow control, a Traffic Control aware device must:
* - stop a device queue when there is no room for another packet. This check
* is typically performed after successfully enqueuing a packet in the device
* queue. Failing to enqueue a packet because there is no room for the packet
* in the queue should be avoided. Should such a situation occur, the device
* queue should be immediately stopped
* - wake up the queue disc when the device queue is empty. This check is
* typically performed after a dequeue operation fails because the device
* queue is empty.
* - start a device queue when the queue is stopped and there is room for
* another packet. This check is typically performed after successfully
* dequeuing a packet from the device queue
* In order to support BQL, a Traffic Control aware device must:
* - call NotifyQueuedBytes after successfully enqueuing a packet in the
* device queue
* - call NotifyTransmittedBytes after successfully dequeuing a packet from
* the device queue
*/
class NetDevice : public Object
{
public:
/**
* \brief Get the type ID.
* \return the object TypeId
*/
static TypeId GetTypeId (void);
virtual ~NetDevice();
/**
* \param index ifIndex of the device
*/
virtual void SetIfIndex (const uint32_t index) = 0;
/**
* \return index ifIndex of the device
*/
virtual uint32_t GetIfIndex (void) const = 0;
/**
* \return the channel this NetDevice is connected to. The value
* returned can be zero if the NetDevice is not yet connected
* to any channel or if the underlying NetDevice has no
* concept of a channel. i.e., callers _must_ check for zero
* and be ready to handle it.
*/
virtual Ptr<Channel> GetChannel (void) const = 0;
/**
* Set the address of this interface
* \param address address to set
*/
virtual void SetAddress (Address address) = 0;
/**
* \return the current Address of this interface.
*/
virtual Address GetAddress (void) const = 0;
/**
* \param mtu MTU value, in bytes, to set for the device
* \return whether the MTU value was within legal bounds
*
* Override for default MTU defined on a per-type basis.
*/
virtual bool SetMtu (const uint16_t mtu) = 0;
/**
* \return the link-level MTU in bytes for this interface.
*
* This value is typically used by the IP layer to perform
* IP fragmentation when needed.
*/
virtual uint16_t GetMtu (void) const = 0;
/**
* \return true if link is up; false otherwise
*/
virtual bool IsLinkUp (void) const = 0;
/**
* TracedCallback signature for link changed event.
*/
typedef void (* LinkChangeTracedCallback) (void);
/**
* \param callback the callback to invoke
*
* Add a callback invoked whenever the link
* status changes to UP. This callback is typically used
* by the IP/ARP layer to flush the ARP cache and by IPv6 stack
* to flush NDISC cache whenever the link goes up.
*/
virtual void AddLinkChangeCallback (Callback<void> callback) = 0;
/**
* \return true if this interface supports a broadcast address,
* false otherwise.
*/
virtual bool IsBroadcast (void) const = 0;
/**
* \return the broadcast address supported by
* this netdevice.
*
* Calling this method is invalid if IsBroadcast returns
* not true.
*/
virtual Address GetBroadcast (void) const = 0;
/**
* \return value of m_isMulticast flag
*/
virtual bool IsMulticast (void) const = 0;
/**
* \brief Make and return a MAC multicast address using the provided
* multicast group
*
* \RFC{1112} says that an Ipv4 host group address is mapped to an Ethernet
* multicast address by placing the low-order 23-bits of the IP address into
* the low-order 23 bits of the Ethernet multicast address
* 01-00-5E-00-00-00 (hex). Similar RFCs exist for Ipv6 and Eui64 mappings.
* This method performs the multicast address creation function appropriate
* to the underlying MAC address of the device. This MAC address is
* encapsulated in an abstract Address to avoid dependencies on the exact
* MAC address format.
*
* In the case of net devices that do not support
* multicast, clients are expected to test NetDevice::IsMulticast and avoid
* attempting to map multicast packets. Subclasses of NetDevice that do
* support multicasting are expected to override this method and provide an
* implementation appropriate to the particular device.
*
* \param multicastGroup The IP address for the multicast group destination
* of the packet.
* \return The MAC multicast Address used to send packets to the provided
* multicast group.
*
* \warning Calling this method is invalid if IsMulticast returns not true.
* \see IsMulticast()
*/
virtual Address GetMulticast (Ipv4Address multicastGroup) const = 0;
/**
* \brief Get the MAC multicast address corresponding
* to the IPv6 address provided.
* \param addr IPv6 address
* \return the MAC multicast address
* \warning Calling this method is invalid if IsMulticast returns not true.
*/
virtual Address GetMulticast (Ipv6Address addr) const = 0;
/**
* \brief Return true if the net device is acting as a bridge.
*
* \return value of m_isBridge flag
*/
virtual bool IsBridge (void) const = 0;
/**
* \brief Return true if the net device is on a point-to-point link.
*
* \return value of m_isPointToPoint flag
*/
virtual bool IsPointToPoint (void) const = 0;
/**
* \param packet packet sent from above down to Network Device
* \param dest mac address of the destination (already resolved)
* \param protocolNumber identifies the type of payload contained in
* this packet. Used to call the right L3Protocol when the packet
* is received.
*
* Called from higher layer to send packet into Network Device
* to the specified destination Address
*
* \return whether the Send operation succeeded
*/
virtual bool Send (Ptr<Packet> packet, const Address& dest, uint16_t protocolNumber) = 0;
/**
* \param packet packet sent from above down to Network Device
* \param source source mac address (so called "MAC spoofing")
* \param dest mac address of the destination (already resolved)
* \param protocolNumber identifies the type of payload contained in
* this packet. Used to call the right L3Protocol when the packet
* is received.
*
* Called from higher layer to send packet into Network Device
* with the specified source and destination Addresses.
*
* \return whether the Send operation succeeded
*/
virtual bool SendFrom (Ptr<Packet> packet, const Address& source, const Address& dest, uint16_t protocolNumber) = 0;
/**
* \returns the node base class which contains this network
* interface.
*
* When a subclass needs to get access to the underlying node
* base class to print the nodeid for example, it can invoke
* this method.
*/
virtual Ptr<Node> GetNode (void) const = 0;
/**
* \param node the node associated to this netdevice.
*
* This method is called from ns3::Node::AddDevice.
*/
virtual void SetNode (Ptr<Node> node) = 0;
/**
* \returns true if ARP is needed, false otherwise.
*
* Called by higher-layers to check if this NetDevice requires
* ARP to be used.
*/
virtual bool NeedsArp (void) const = 0;
/**
* Packet types are used as they are in Linux. GCC name resolution on
* typedef enum {} PacketType is broken for the foreseeable future, so
* if you need to use ns-3 PacketType in a driver that also uses the
* Linux packet types you're hosed unless we define a shadow type,
* which we do here.
*/
enum PacketType
{
PACKET_HOST = 1, /**< Packet addressed oo us */
NS3_PACKET_HOST = PACKET_HOST,
PACKET_BROADCAST, /**< Packet addressed to all */
NS3_PACKET_BROADCAST = PACKET_BROADCAST,
PACKET_MULTICAST, /**< Packet addressed to multicast group */
NS3_PACKET_MULTICAST = PACKET_MULTICAST,
PACKET_OTHERHOST, /**< Packet addressed to someone else */
NS3_PACKET_OTHERHOST = PACKET_OTHERHOST,
};
/**
* \param device a pointer to the net device which is calling this callback
* \param packet the packet received
* \param protocol the 16 bit protocol number associated with this packet.
* This protocol number is expected to be the same protocol number
* given to the Send method by the user on the sender side.
* \param sender the address of the sender
* \returns true if the callback could handle the packet successfully, false
* otherwise.
*/
typedef Callback< bool, Ptr<NetDevice>, Ptr<const Packet>, uint16_t, const Address & > ReceiveCallback;
/**
* \param cb callback to invoke whenever a packet has been received and must
* be forwarded to the higher layers.
*
* Set the callback to be used to notify higher layers when a packet has been
* received.
*/
virtual void SetReceiveCallback (ReceiveCallback cb) = 0;
/**
* \param device a pointer to the net device which is calling this callback
* \param packet the packet received
* \param protocol the 16 bit protocol number associated with this packet.
* This protocol number is expected to be the same protocol number
* given to the Send method by the user on the sender side.
* \param sender the address of the sender
* \param receiver the address of the receiver
* \param packetType type of packet received (broadcast/multicast/unicast/otherhost)
* \returns true if the callback could handle the packet successfully, false
* otherwise.
*/
typedef Callback< bool, Ptr<NetDevice>, Ptr<const Packet>, uint16_t,
const Address &, const Address &, enum PacketType > PromiscReceiveCallback;
/**
* \param cb callback to invoke whenever a packet has been received in promiscuous mode and must
* be forwarded to the higher layers.
*
* Enables netdevice promiscuous mode and sets the callback that
* will handle promiscuous mode packets. Note, promiscuous mode
* packets means _all_ packets, including those packets that can be
* sensed by the netdevice but which are intended to be received by
* other hosts.
*/
virtual void SetPromiscReceiveCallback (PromiscReceiveCallback cb) = 0;
/**
* \return true if this interface supports a bridging mode, false otherwise.
*/
virtual bool SupportsSendFrom (void) const = 0;
};
} // namespace ns3
#endif /* NET_DEVICE_H */
| 34.094535 | 118 | 0.703145 |
9319dad50ca506daea9382461570e42570455ecb | 421 | h | C | src/Sensors/LowLevel/SensorDHT11.h | mmakaay/arduino-doughboy | e48e44f287a56c3716527f86946c16a8db1d8d52 | [
"MIT"
] | 1 | 2020-07-06T19:45:49.000Z | 2020-07-06T19:45:49.000Z | src/Sensors/LowLevel/SensorDHT11.h | mmakaay/arduino-doughboy | e48e44f287a56c3716527f86946c16a8db1d8d52 | [
"MIT"
] | null | null | null | src/Sensors/LowLevel/SensorDHT11.h | mmakaay/arduino-doughboy | e48e44f287a56c3716527f86946c16a8db1d8d52 | [
"MIT"
] | null | null | null | #ifndef DOUGH_SENSOR_DHT11_H
#define DOUGH_SENSOR_DHT11_H
#include <DHT.h>
#include "config.h"
namespace Dough
{
// This class provides access to the DHT11 sensor in the device.
class SensorDHT11
{
public:
static SensorDHT11 *Instance();
void begin();
float readTemperature();
float readHumidity();
private:
SensorDHT11();
DHT *_dht;
};
}
#endif | 17.541667 | 68 | 0.627078 |
931c2582d046e7b3d2867230f9e130a45980c123 | 303 | h | C | DBBuilder-Demo-Mac/DBBuilder Demo-Mac/AppDelegate.h | dennisbirch/DBBuilder | f4b8e0963b502abf4bfaee4515b4dc1aa7fa617f | [
"MIT"
] | null | null | null | DBBuilder-Demo-Mac/DBBuilder Demo-Mac/AppDelegate.h | dennisbirch/DBBuilder | f4b8e0963b502abf4bfaee4515b4dc1aa7fa617f | [
"MIT"
] | null | null | null | DBBuilder-Demo-Mac/DBBuilder Demo-Mac/AppDelegate.h | dennisbirch/DBBuilder | f4b8e0963b502abf4bfaee4515b4dc1aa7fa617f | [
"MIT"
] | null | null | null | //
// AppDelegate.h
// DBBuilder Demo-Mac
//
// Created by Dennis Birch on 11/21/14.
// Copyright (c) 2014 Dennis Birch. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (nonatomic, copy, readonly) NSString *databasePath;
@end
| 17.823529 | 61 | 0.712871 |
931c76fc0dc346745af7e66fff7b4c32f8bdfdf0 | 311 | c | C | 14/review_6.c | codelegant/c-primer-plus | a23d2716d26c22d797e3eae1855be08b13a80c46 | [
"MIT"
] | 2 | 2020-10-23T08:45:47.000Z | 2020-10-23T09:14:24.000Z | 14/review_6.c | codelegant/c-primer-plus | a23d2716d26c22d797e3eae1855be08b13a80c46 | [
"MIT"
] | null | null | null | 14/review_6.c | codelegant/c-primer-plus | a23d2716d26c22d797e3eae1855be08b13a80c46 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
typedef struct lens{
float foclen;
float fstop;
char brand[30];
} LENS;
int main(void) {
LENS lens[10] = { [2]={ 500, 2.0, "Remarkatar" } };
lens[1]=(LENS){400, 1.8, "Canon"};
strcpy(lens[0].brand , "Nikon");
printf("%.2f\n", lens[1].foclen);
return 0;
}
| 19.4375 | 53 | 0.59164 |
93200dfa59e728793f02b44b0ab36f79103bb560 | 878 | h | C | platform/mcu/moc108/mx108/mx378/app/app.h | ghsecuritylab/Alios_SDK | edd416e7d2961db42c2100ac2d6237ee527d1aee | [
"Apache-2.0"
] | 2 | 2021-05-28T08:25:33.000Z | 2021-11-17T02:58:50.000Z | platform/mcu/moc108/mx108/mx378/app/app.h | ghsecuritylab/Alios_SDK | edd416e7d2961db42c2100ac2d6237ee527d1aee | [
"Apache-2.0"
] | null | null | null | platform/mcu/moc108/mx108/mx378/app/app.h | ghsecuritylab/Alios_SDK | edd416e7d2961db42c2100ac2d6237ee527d1aee | [
"Apache-2.0"
] | 5 | 2018-05-23T02:56:10.000Z | 2021-01-02T16:44:09.000Z | #ifndef _APP_H_
#define _APP_H_
#pragma once
#include "rtos_pub.h"
//#define APP_DEBUG
#ifdef APP_DEBUG
#define APP_PRT os_printf
#define APP_WPRT warning_prf
#else
#define APP_PRT os_null_printf
#define APP_WPRT warning_prf
#endif
enum
{
BMSG_NULL_TYPE = 0,
BMSG_RX_TYPE = 1,
BMSG_TX_TYPE = 2,
BMSG_IOCTL_TYPE = 3,
BMSG_SKT_TX_TYPE = 4,
BMSG_TX_RAW_TYPE = 5,
BMSG_RX_LSIG = 6, /* phy receive 802.11 LSIG*/
};
typedef struct bus_message
{
uint32_t type;
uint32_t arg;
uint32_t len;
mico_semaphore_t sema;
}BUS_MSG_T;
#define CORE_QITEM_COUNT (64)
#define CORE_STACK_SIZE (4 * 1024)
typedef struct _wifi_core_
{
uint32_t queue_item_count;
mico_queue_t io_queue;
mico_thread_t handle;
uint32_t stack_size;
}WIFI_CORE_T;
void app_start(void);
void core_thread_uninit(void);
#endif // _APP_H_
// eof
| 15.963636 | 50 | 0.714123 |
93210bd45140dd7c9224b7e4c5a3265321dce621 | 331 | c | C | acsl/libraries/libc/test/wchar/io/test_getwchar.c | davidcok/annotationsforall | 16024a9ffecdb72b638e1f942c567f8815183e89 | [
"Apache-2.0"
] | 4 | 2016-06-16T21:03:57.000Z | 2021-02-06T10:20:14.000Z | acsl/libraries/libc/test/wchar/io/test_getwchar.c | davidcok/annotationsforall | 16024a9ffecdb72b638e1f942c567f8815183e89 | [
"Apache-2.0"
] | null | null | null | acsl/libraries/libc/test/wchar/io/test_getwchar.c | davidcok/annotationsforall | 16024a9ffecdb72b638e1f942c567f8815183e89 | [
"Apache-2.0"
] | 1 | 2021-06-09T07:00:34.000Z | 2021-06-09T07:00:34.000Z | #include "../../../stdio_common.h"
#include <wchar.h>
void runSuccess() {
getwchar();
}
void runFailure() {
}
int f;
void testValues() {
f = 2;
wint_t result;
result = getwchar();
//@ assert result == WEOF || (wchar_t)result == result;
//@ assert f == 2;
//@ assert vacuous: \false;
}
| 14.391304 | 59 | 0.531722 |
9321841bb4fb24981f24c564de2b72fb84e5f68c | 15,865 | h | C | src/game/variables.h | def-/zcatchPlus | 143a2982ca9af8fc76cf11b709b5b46c0d854779 | [
"Zlib"
] | 3 | 2018-12-23T17:11:45.000Z | 2019-08-01T07:29:51.000Z | src/game/variables.h | def-/zcatchPlus | 143a2982ca9af8fc76cf11b709b5b46c0d854779 | [
"Zlib"
] | 13 | 2018-12-23T00:53:17.000Z | 2020-04-08T21:51:23.000Z | src/game/variables.h | def-/zcatchPlus | 143a2982ca9af8fc76cf11b709b5b46c0d854779 | [
"Zlib"
] | 4 | 2019-04-29T11:26:33.000Z | 2021-11-18T16:33:08.000Z | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#ifndef GAME_VARIABLES_H
#define GAME_VARIABLES_H
#undef GAME_VARIABLES_H // this file will be included several times
// client
MACRO_CONFIG_INT(ClPredict, cl_predict, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict client movements")
MACRO_CONFIG_INT(ClNameplates, cl_nameplates, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show name plates")
MACRO_CONFIG_INT(ClNameplatesAlways, cl_nameplates_always, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Always show name plates disregarding of distance")
MACRO_CONFIG_INT(ClNameplatesTeamcolors, cl_nameplates_teamcolors, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use team colors for name plates")
MACRO_CONFIG_INT(ClNameplatesSize, cl_nameplates_size, 50, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the name plates from 0 to 100%")
MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon on pickup")
MACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD")
MACRO_CONFIG_INT(ClShowChatFriends, cl_show_chat_friends, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show only chat messages from friends")
MACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame FPS counter")
MACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
MACRO_CONFIG_INT(ClThreadsoundloading, cl_threadsoundloading, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Load sound files threaded")
MACRO_CONFIG_INT(ClWarningTeambalance, cl_warning_teambalance, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Warn about team balance")
MACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 300, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
MACRO_CONFIG_INT(ClMouseFollowfactor, cl_mouse_followfactor, 60, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
MACRO_CONFIG_INT(ClMouseMaxDistance, cl_mouse_max_distance, 800, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
MACRO_CONFIG_INT(EdShowkeys, ed_showkeys, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
//MACRO_CONFIG_INT(ClFlow, cl_flow, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
MACRO_CONFIG_INT(ClShowWelcome, cl_show_welcome, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
MACRO_CONFIG_INT(ClMotdTime, cl_motd_time, 10, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "How long to show the server message of the day")
MACRO_CONFIG_STR(ClVersionServer, cl_version_server, 100, "version.teeworlds.com", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Server to use to check for new versions")
MACRO_CONFIG_STR(ClLanguagefile, cl_languagefile, 255, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "What language file to use")
MACRO_CONFIG_INT(PlayerUseCustomColor, player_use_custom_color, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors")
MACRO_CONFIG_INT(PlayerColorBody, player_color_body, 65408, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player body color")
MACRO_CONFIG_INT(PlayerColorFeet, player_color_feet, 65408, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player feet color")
MACRO_CONFIG_STR(PlayerSkin, player_skin, 24, "default", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin")
MACRO_CONFIG_INT(UiPage, ui_page, 6, 0, 10, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface page")
MACRO_CONFIG_INT(UiToolboxPage, ui_toolbox_page, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toolbox page")
MACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, "localhost:8303", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface server address")
MACRO_CONFIG_INT(UiScale, ui_scale, 100, 50, 150, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface scale")
MACRO_CONFIG_INT(UiMousesens, ui_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity for menus/editor")
MACRO_CONFIG_INT(UiColorHue, ui_color_hue, 160, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface color hue")
MACRO_CONFIG_INT(UiColorSat, ui_color_sat, 70, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface color saturation")
MACRO_CONFIG_INT(UiColorLht, ui_color_lht, 175, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface color lightness")
MACRO_CONFIG_INT(UiColorAlpha, ui_color_alpha, 228, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface alpha")
MACRO_CONFIG_INT(GfxNoclip, gfx_noclip, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Disable clipping")
// server
MACRO_CONFIG_INT(SvWarmup, sv_warmup, 0, 0, 0, CFGFLAG_SERVER, "Number of seconds to do warmup before round starts")
MACRO_CONFIG_INT(SvUnpauseTimer, sv_unpause_timer, 0, 0, 0, CFGFLAG_SERVER, "Number of seconds till the game continues")
MACRO_CONFIG_STR(SvMotd, sv_motd, 900, "", CFGFLAG_SERVER, "Message of the day to display for the clients")
MACRO_CONFIG_INT(SvTeamdamage, sv_teamdamage, 0, 0, 1, CFGFLAG_SERVER, "Team damage")
MACRO_CONFIG_STR(SvMaprotation, sv_maprotation, 768, "", CFGFLAG_SERVER, "Maps to rotate between")
MACRO_CONFIG_INT(SvRoundsPerMap, sv_rounds_per_map, 1, 1, 100, CFGFLAG_SERVER, "Number of rounds on each map before rotating")
MACRO_CONFIG_INT(SvRoundSwap, sv_round_swap, 1, 0, 1, CFGFLAG_SERVER, "Swap teams between rounds")
MACRO_CONFIG_INT(SvPowerups, sv_powerups, 1, 0, 1, CFGFLAG_SERVER, "Allow powerups like ninja")
MACRO_CONFIG_INT(SvScorelimit, sv_scorelimit, 0, 0, 1000, CFGFLAG_SERVER, "Score limit (0 disables)")
MACRO_CONFIG_INT(SvTimelimit, sv_timelimit, 0, 0, 1000, CFGFLAG_SERVER, "Time limit in minutes (0 disables)")
MACRO_CONFIG_STR(SvGametype, sv_gametype, 32, "dm", CFGFLAG_SERVER, "Game type (dm, tdm, ctf)")
MACRO_CONFIG_INT(SvTournamentMode, sv_tournament_mode, 0, 0, 1, CFGFLAG_SERVER, "Tournament mode. When enabled, players joins the server as spectator")
MACRO_CONFIG_INT(SvSpamprotection, sv_spamprotection, 1, 0, 1, CFGFLAG_SERVER, "Spam protection")
MACRO_CONFIG_INT(SvRespawnDelayTDM, sv_respawn_delay_tdm, 3, 0, 10, CFGFLAG_SERVER, "Time needed to respawn after death in tdm gametype")
MACRO_CONFIG_INT(SvSpectatorSlots, sv_spectator_slots, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Number of slots to reserve for spectators")
MACRO_CONFIG_INT(SvTeambalanceTime, sv_teambalance_time, 1, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before autobalancing teams")
MACRO_CONFIG_INT(SvInactiveKickTime, sv_inactivekick_time, 3, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before taking care of inactive players")
MACRO_CONFIG_INT(SvInactiveKick, sv_inactivekick, 1, 0, 2, CFGFLAG_SERVER, "How to deal with inactive players (0=move to spectator, 1=move to free spectator slot/kick, 2=kick)")
MACRO_CONFIG_INT(SvStrictSpectateMode, sv_strict_spectate_mode, 0, 0, 1, CFGFLAG_SERVER, "Restricts information in spectator mode")
MACRO_CONFIG_INT(SvVoteSpectate, sv_vote_spectate, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to move players to spectators")
MACRO_CONFIG_INT(SvVoteSpectateRejoindelay, sv_vote_spectate_rejoindelay, 3, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before a player can rejoin after being moved to spectators by vote")
MACRO_CONFIG_INT(SvVoteKick, sv_vote_kick, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to kick players")
MACRO_CONFIG_INT(SvVoteKickMin, sv_vote_kick_min, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Minimum number of players required to start a kick vote")
MACRO_CONFIG_INT(SvVoteKickBantime, sv_vote_kick_bantime, 5, 0, 1440, CFGFLAG_SERVER, "The time to ban a player if kicked by vote. 0 makes it just use kick")
// debug
#ifdef CONF_DEBUG // this one can crash the server if not used correctly
MACRO_CONFIG_INT(DbgDummies, dbg_dummies, 0, 0, 15, CFGFLAG_SERVER, "")
#endif
MACRO_CONFIG_INT(DbgFocus, dbg_focus, 0, 0, 1, CFGFLAG_CLIENT, "")
MACRO_CONFIG_INT(DbgTuning, dbg_tuning, 0, 0, 1, CFGFLAG_CLIENT, "")
//zCatch:
MACRO_CONFIG_INT(SvMode, sv_mode, 1, 1, 5, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "1 - Instagib; 2 - Everything; 3 - Hammerparty; 4 - Grenade; 5 - Ninja")
MACRO_CONFIG_INT(SvAllowJoin, sv_allow_join, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Allow new Players to join without waiting for the next round")
//1 = Allowed to join; 2 = Will join when person with the most kills die
MACRO_CONFIG_INT(SvColorIndicator, sv_color_indicator, 1, 0, 1, CFGFLAG_SERVER, "Color tees apropriate to the number of currently caught players")
MACRO_CONFIG_INT(SvBonus, sv_bonus, 0, 0, 100, CFGFLAG_SERVER, "Give the last player extra points")
MACRO_CONFIG_INT(SvLaserjumps, sv_laserjumps, 0, 0, 1, CFGFLAG_SERVER, "Use laserjumps - on a laser bounce a explosion will occur which takes no damage")
MACRO_CONFIG_INT(SvChatValue, sv_chat_value, 250, 100, 1000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "A value which is added on each message and decreased on each tick")
MACRO_CONFIG_INT(SvChatThreshold, sv_chat_threshold, 1000, 250, 10000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "If this threshold will exceed by too many messages the player will be muted")
MACRO_CONFIG_INT(SvMuteDuration, sv_mute_duration, 60, 0, 3600, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "How long the player will be muted (in seconds)")
MACRO_CONFIG_INT(SvAnticamper, sv_anticamper, 2, 0, 2, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "0 disables, 1 enables anticamper in all modes and 2 only in Instagib")
MACRO_CONFIG_INT(SvAnticamperFreeze, sv_anticamper_freeze, 7, 0, 15, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "If a player should freeze on camping (and how long) or die")
MACRO_CONFIG_INT(SvAnticamperTime, sv_anticamper_time, 10, 5, 120, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "How long to wait till the player dies/freezes")
MACRO_CONFIG_INT(SvAnticamperRange, sv_anticamper_range, 200, 0, 1000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Distance how far away the player must move to escape anticamper")
MACRO_CONFIG_INT(SvGrenadeMinDamage, sv_grenade_min_damage, 4, 1, 6, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "How much damage the grenade must do to kill the player (depends how far away it explodes)")
MACRO_CONFIG_INT(SvGrenadeEndlessAmmo, sv_grenade_endless_ammo, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Endless ammo for grenade (only mode 4). If not zero, set sv_grenade_bullets for the number of bullets")
MACRO_CONFIG_INT(SvWeaponsAmmo, sv_weapons_ammo, 4, 1, 10, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Default amount of ammo for all weapons in mode 2 or grenade in mode 4. Your ammo will regenerate after some while")
MACRO_CONFIG_INT(SvVoteForceReason, sv_vote_forcereason, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Allow only votes with a reason (except settings)")
MACRO_CONFIG_INT(SvSuicideTime, sv_suicide_time, 15, 0, 60, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Minimum time between suicides. 0 to forbid suicides completely")
MACRO_CONFIG_INT(SvKillPenalty, sv_kill_penalty, 5, 0, 50, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "The amount of points which the score will be decreased on each suicide")
// zCatch/TeeVi
MACRO_CONFIG_INT(SvLastStandingPlayers, sv_last_standing_players, 7, 2, 16, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "How many players are needed to have last standing rounds")
// MACRO_CONFIG_INT(SvBotDetection, sv_bot_detection, 0, 0, 3, CFGFLAG_SERVER, "Bot detection (0=off, 1=fast aim, 2=follow, 3=all)")
MACRO_CONFIG_INT(SvRanking, sv_ranking, 1, 0, 1, CFGFLAG_SERVER, "Ranking system (0=off, 1=sqlite)")
MACRO_CONFIG_STR(SvRankingFile, sv_ranking_file, 255, "ranking.db", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "File in which the ranking and scores are saved.")
MACRO_CONFIG_INT(SvAllowHardMode, sv_allow_hard_mode, 0, 0, 2, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Allow players to go into hard mode")
MACRO_CONFIG_INT(SvAllowRainbow, sv_allow_rainbow, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Allow players to get the rainbow when playing the release game.")
// zCatch jxsl13 added.
MACRO_CONFIG_INT(SvAllowDefaultDynamicCam, sv_allow_default_dynamic_cam, 1, 0, 2, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Allow the use and sending of player information in dynamic cam range(allow dynamic cam = 1, else alternative dyn cam implementation = 0)")
MACRO_CONFIG_INT(SvStaticCamAbsolutexDistanceX, sv_static_cam_x, 840, 0, 10000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "If the dynamic camera is disabled, this is the rendered horizontal distance from a player's current position.")
MACRO_CONFIG_INT(SvStaticCamAbsolutexDistanceY, sv_static_cam_y, 680, 0, 10000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "If the dynamic camera is disabled, this is the rendered vertical distance from a player's current position.")
MACRO_CONFIG_INT(SvLastStandingDeathmatch, sv_last_standing_deathmatch, 0, 0, 2, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "If the last standing players treshold is not reached, caught people will be released automatically and new people are allowed to join the game directly.")
// Adjustable default regeneration time.
MACRO_CONFIG_INT(SvGunRegenerationTime, sv_gun_regeneration_time, 625, 0, 10000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Default: 625 - Time after which the gun's projectiles regenerate.")
MACRO_CONFIG_INT(SvGrenadeRegenerationTime, sv_grenade_regeneration_time, 1000, 0, 10000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Default: 1000 - Time after which the grenade's projectiles regenerate.")
MACRO_CONFIG_INT(SvRifleRegenerationTime, sv_rifle_regeneration_time, 1200, 0, 10000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Default: 1200 - Time after which the laser rifle's projectiles regenerate.")
MACRO_CONFIG_INT(SvShotgunRegenerationTime, sv_shotgun_regeneration_time, 1000, 0, 10000, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Default: 1000 - Time after which the shotgun's projectiles regenerate.")
MACRO_CONFIG_INT(SvSqliteHistorian, sv_sqlite_historian, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Enable SQLite logging: Needs sv_tee_historian 1 (enabled) in order to work. May cause lag if the sqlite file gets too big. Change sv_sqlite_historian_file to \"\" and execute save_tee_historian to create an new file.")
MACRO_CONFIG_STR(SvSqliteHistorianFileName, sv_sqlite_historian_file, 64, "", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Sqlite Historian file name. Change to have an own file format or leave as is to have the default format.")
MACRO_CONFIG_INT(SvBotDetection, sv_bot_detection, 1, 0, 1, CFGFLAG_SERVER, "Enable(1) or disables(0) bot detection.")
MACRO_CONFIG_STR(SvBotDetectionFile, sv_bot_detection_file, 64, "botdetection", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Bot detection file name.")
MACRO_CONFIG_INT(SvAutomaticBanMinUrgencyLevel, sv_auto_ban_min_level, 3, 0, 6, CFGFLAG_SERVER, "Bans every player of >= sv_auto_ban_min_level, 0 - off, 1 - weird client, 2 - known cheat client, 3 - zoom, 4 - bot, 5 - zoom & bot, 6 - instant ban candidates.")
MACRO_CONFIG_INT(SvCheatClientMentionInterval, sv_cheat_mention_interval, 120, 0, 3600, CFGFLAG_SERVER, "After how many seconds to repeat that a player is using a weird client that is categorized >= (sv_auto_ban_min_level: 2), 0 - off")
MACRO_CONFIG_INT(SvAutomaticBanTime, sv_auto_ban_time, 30, 1, 1440, CFGFLAG_SERVER, "For how many minutes to ban the player that was automatically detected?")
MACRO_CONFIG_INT(SvFastAimFirstAndThirdPositionDistanceTolerance, sv_faim_tollerance_1_and_3_dist, 24, 0, 1000, CFGFLAG_SERVER, "How much the distance between the first and third position of a player's mouse may differ for a fast aiming bot to be detected.")
MACRO_CONFIG_INT(SvFastAimDistanceTravelledTolerance, sv_faim_tollerance_dist_travel, 100, 0, 2000, CFGFLAG_SERVER, "How much the mouse has to travel within three inputs before the fast aim is checked.")
MACRO_CONFIG_INT(SvZoomIndicationResetInterval, sv_zindication_reset_interval, 120, 0, 7200, CFGFLAG_SERVER, "How many seconds need to pass, in order for the zoom indication counter/list to be emptied.")
MACRO_CONFIG_STR(SvNickBanFile, sv_nick_ban_file, 128, "banned_nicks.txt", CFGFLAG_SERVER|CFGFLAG_NONTEEHISTORIC, "Name of the file, where banned nicks are stored. Default: banned_nicks.txt")
#endif
| 103.69281 | 324 | 0.811283 |
9321fd1d9e8c0a27e9998d32eca6c6b7be6f29ff | 482 | h | C | XXBTraceroute/XXBTraceroute/XXBTraceroute/XXBTraceRouteQueue.h | sixTiger/XXBTraceroute | 7e47db86674e43c39ea7297f882ee9c305b6afd0 | [
"MIT"
] | 3 | 2019-05-08T06:31:12.000Z | 2022-03-24T10:57:46.000Z | XXBTraceroute/XXBTraceroute/XXBTraceroute/XXBTraceRouteQueue.h | sixTiger/XXBTraceroute | 7e47db86674e43c39ea7297f882ee9c305b6afd0 | [
"MIT"
] | null | null | null | XXBTraceroute/XXBTraceroute/XXBTraceroute/XXBTraceRouteQueue.h | sixTiger/XXBTraceroute | 7e47db86674e43c39ea7297f882ee9c305b6afd0 | [
"MIT"
] | null | null | null | //
// XXBTraceRouteQueue.h
// XXBTraceroute
//
// Created by xiaobing5 on 2019/4/17.
// Copyright © 2019 xiaobing5. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "XXBTracerouteUtil.h"
@interface XXBTraceRouteQueue : NSObject{
dispatch_queue_t _queue;
XXBTracerouteUtil *_tracerouteUtil;
}
+ (instancetype)traceRouteQueue;
/**
开始网络诊断
@param block 网络诊断的回调
*/
- (void)inTraceRoute:(void (^)(XXBTracerouteUtil *tracerouteUtil))block;
@end
| 17.214286 | 72 | 0.719917 |
9325df7bae1a39fbfe262bf61fdce9cbbf2c144d | 247 | h | C | Classes/FDSyncedAnimation.h | shenkevin/FlameDragon | 02f86da70f1429410160ce55ebbeb3e9c59631d3 | [
"MIT"
] | 1 | 2022-02-26T04:56:40.000Z | 2022-02-26T04:56:40.000Z | Classes/FDSyncedAnimation.h | shenkevin/FlameDragon | 02f86da70f1429410160ce55ebbeb3e9c59631d3 | [
"MIT"
] | null | null | null | Classes/FDSyncedAnimation.h | shenkevin/FlameDragon | 02f86da70f1429410160ce55ebbeb3e9c59631d3 | [
"MIT"
] | null | null | null | //
// FDSyncedAnimation.h
// FlameDragon
//
// Created by sui toney on 11-11-13.
// Copyright 2011 ms. All rights reserved.
//
#import "cocos2d.h"
#import "FDAnimation.h"
@interface FDSyncedAnimation : FDAnimation {
int totalTick;
}
@end
| 13.722222 | 44 | 0.688259 |
9327911ecf93548328271a2f51a0f6740e93dba5 | 1,311 | h | C | OpenTissue/core/geometry/geometry_is_triangle_obtuse.h | ricortiz/OpenTissue | f8c8ebc5137325b77ba90bed897f6be2795bd6fb | [
"Zlib"
] | 76 | 2018-02-20T11:30:52.000Z | 2022-03-31T12:45:06.000Z | OpenTissue/core/geometry/geometry_is_triangle_obtuse.h | ricortiz/OpenTissue | f8c8ebc5137325b77ba90bed897f6be2795bd6fb | [
"Zlib"
] | 27 | 2018-11-20T14:32:49.000Z | 2021-11-24T15:26:45.000Z | OpenTissue/core/geometry/geometry_is_triangle_obtuse.h | ricortiz/OpenTissue | f8c8ebc5137325b77ba90bed897f6be2795bd6fb | [
"Zlib"
] | 24 | 2018-02-21T01:45:26.000Z | 2022-03-07T07:06:49.000Z | #ifndef OPENTISSUE_CORE_GEOMETRY_GEOMETRY_IS_TRIANGLE_OBTUSE_H
#define OPENTISSUE_CORE_GEOMETRY_GEOMETRY_IS_TRIANGLE_OBTUSE_H
//
// OpenTissue Template Library
// - A generic toolbox for physics-based modeling and simulation.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.
//
// OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php
//
#include <OpenTissue/configuration.h>
#include <OpenTissue/core/geometry/geometry_is_angle_obtuse.h>
namespace OpenTissue
{
namespace geometry
{
/**
* Obtuse Triangle Testing.
* If any corner of an triangle is obtuse then the triangle is considered to be obtuse.
*
* @param p First vertex of triangle.
* @param pi Second vertex of triangle.
* @param pj Third vertex of triangle.
*
* @return If triangle is obtuse then the return value is true otherwise it is false.
*/
template<typename vector_type>
bool is_triangle_obtuse(vector_type const & p,vector_type const & pi,vector_type const & pj)
{
return( is_angle_obtuse(p,pi,pj)
|| is_angle_obtuse(pi,pj,p)
|| is_angle_obtuse(pj,p,pi)
);
}
} // namespace geometry
} // namespace OpenTissue
//OPENTISSUE_CORE_GEOMETRY_GEOMETRY_IS_TRIANGLE_OBTUSE_H
#endif
| 31.214286 | 96 | 0.720061 |
9327f294e33c752f881d2057cd761d3bc4e2adcd | 810 | h | C | cases/comparison_trackers/param/post/objects/surfer__us_15o58__surftimeconst_2o5__reorientationtime_0o5/pos/group/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/comparison_trackers/param/post/objects/surfer__us_15o58__surftimeconst_2o5__reorientationtime_0o5/pos/group/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/comparison_trackers/param/post/objects/surfer__us_15o58__surftimeconst_2o5__reorientationtime_0o5/pos/group/choice.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | #ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_15O58__SURFTIMECONST_2O5__REORIENTATIONTIME_0O5_POS_GROUP_CHOICE_H
#define C0P_PARAM_POST_OBJECTS_SURFER__US_15O58__SURFTIMECONST_2O5__REORIENTATIONTIME_0O5_POS_GROUP_CHOICE_H
#pragma once
// THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS.
// THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE
// CHOOSE COMMAND IS USED
// choose your post
#include "core/post/objects/object/post/group/all/core.h"
#include "param/post/objects/surfer__us_15o58__surftimeconst_2o5__reorientationtime_0o5/pos/group/all/parameters.h"
namespace c0p {
template<typename TypeObjectStep>
using PostSurferUs15O58Surftimeconst2O5Reorientationtime0O5PosGroup = PostPostGroupAll<PostSurferUs15O58Surftimeconst2O5Reorientationtime0O5PosGroupAllParameters, TypeObjectStep>;
}
#endif
| 42.631579 | 183 | 0.867901 |
932b342f8e251492fca9fbb2972791e820a40776 | 760 | h | C | Classes/Util/App/ARUserManager.h | artsy/energy | e3543ff0a87029dbd171af7b0e09c9fa13b5536a | [
"MIT"
] | 231 | 2015-08-06T18:40:19.000Z | 2022-03-27T20:40:03.000Z | Classes/Util/App/ARUserManager.h | artsy/energy | e3543ff0a87029dbd171af7b0e09c9fa13b5536a | [
"MIT"
] | 313 | 2015-08-06T19:04:17.000Z | 2022-01-14T15:42:36.000Z | Classes/Util/App/ARUserManager.h | artsy/energy | e3543ff0a87029dbd171af7b0e09c9fa13b5536a | [
"MIT"
] | 54 | 2015-08-06T19:01:14.000Z | 2022-02-10T12:19:50.000Z | #import <Foundation/Foundation.h>
/// Handles interacting with user state
/// and logging in.
@interface ARUserManager : NSObject
/// User is logged in and token is still valid
- (BOOL)userIsLoggedIn;
/// User has credentials in the defaults
/// but we don't know if they're logged in
- (BOOL)userCredentialsExist;
/// Uses the stored credentials to log in transparently
- (BOOL)requestLoginWithStoredCredentials;
/// Same as above but with a callback
- (BOOL)requestLoginWithStoredCredentialsCompletion:(void (^)(BOOL success, NSError *error))completion;
/// Logs in with the username / password
- (void)requestLoginWithUsername:(NSString *)username andPassword:(NSString *)password completion:(void (^)(BOOL success, NSError *error))completion;
@end
| 30.4 | 149 | 0.760526 |
932bf01d302812c763ee776e30ecca904fb9d3a9 | 8,397 | c | C | openjdk11/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/multienv/MA08/ma08t001/ma08t001a.c | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | openjdk11/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/multienv/MA08/ma08t001/ma08t001a.c | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | openjdk11/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/multienv/MA08/ma08t001/ma08t001a.c | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include <stdlib.h>
#include <string.h>
#include "jni_tools.h"
#include "agent_common.h"
#include "jvmti_tools.h"
#define PASSED 0
#define STATUS_FAILED 2
#ifdef __cplusplus
extern "C" {
#endif
/* ========================================================================== */
/* scaffold objects */
static jlong timeout = 0;
/* test objects */
static jthread threadForStop = NULL;
static jthread threadForInterrupt = NULL;
static int ThreadDeathFlag = 0;
static int InterruptedExceptionFlag = 0;
/* ========================================================================== */
/** callback functions **/
const char* THREAD_DEATH_CLASS_SIG = "Ljava/lang/ThreadDeath;";
const char* INTERRUPTED_EXCEPTION_CLASS_SIG = "Ljava/lang/InterruptedException;";
static void JNICALL
Exception(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread,
jmethodID method, jlocation location, jobject exception,
jmethodID catch_method, jlocation catch_location) {
jclass klass = NULL;
char *signature = NULL;
if (!NSK_JNI_VERIFY(jni_env, (klass =
NSK_CPP_STUB2(GetObjectClass, jni_env, exception)) != NULL)) {
nsk_jvmti_setFailStatus();
return;
}
if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB4(GetClassSignature, jvmti_env,
klass, &signature, NULL))) {
nsk_jvmti_setFailStatus();
return;
}
if (!NSK_VERIFY(signature != NULL)) {
nsk_jvmti_setFailStatus();
return;
}
NSK_DISPLAY1("Exception event: %s\n", signature);
if (NSK_CPP_STUB3(IsSameObject, jni_env, threadForInterrupt, thread)) {
if (strcmp(signature, INTERRUPTED_EXCEPTION_CLASS_SIG) == 0) {
InterruptedExceptionFlag++;
} else {
NSK_COMPLAIN1("Unexpected exception in DebuggeeThreadForInterrupt: %s\n",
signature);
nsk_jvmti_setFailStatus();
}
} else if (NSK_CPP_STUB3(IsSameObject, jni_env, threadForStop, thread)) {
if (strcmp(signature, THREAD_DEATH_CLASS_SIG) == 0) {
ThreadDeathFlag++;
} else {
NSK_COMPLAIN1("Unexpected exception in DebuggeeThreadForStop: %s\n",
signature);
nsk_jvmti_setFailStatus();
}
}
NSK_CPP_STUB2(Deallocate, jvmti_env, (unsigned char*)signature);
}
/* ========================================================================== */
static int prepare(jvmtiEnv* jvmti, JNIEnv* jni) {
const char* STOP_THREAD_NAME = "DebuggeeThreadForStop";
const char* INTERRUPT_THREAD_NAME = "DebuggeeThreadForInterrupt";
jvmtiThreadInfo info;
jthread *threads = NULL;
jint threads_count = 0;
int i;
NSK_DISPLAY0("Prepare: find tested thread\n");
/* get all live threads */
if (!NSK_JVMTI_VERIFY(
NSK_CPP_STUB3(GetAllThreads, jvmti, &threads_count, &threads)))
return NSK_FALSE;
if (!NSK_VERIFY(threads_count > 0 && threads != NULL))
return NSK_FALSE;
/* find tested thread */
for (i = 0; i < threads_count; i++) {
if (!NSK_VERIFY(threads[i] != NULL))
return NSK_FALSE;
/* get thread information */
if (!NSK_JVMTI_VERIFY(
NSK_CPP_STUB3(GetThreadInfo, jvmti, threads[i], &info)))
return NSK_FALSE;
NSK_DISPLAY3(" thread #%d (%s): %p\n", i, info.name, threads[i]);
/* find by name */
if (info.name != NULL) {
if (strcmp(info.name, STOP_THREAD_NAME) == 0) {
threadForStop = threads[i];
} else if (strcmp(info.name, INTERRUPT_THREAD_NAME) == 0) {
threadForInterrupt = threads[i];
}
}
}
/* deallocate threads list */
if (!NSK_JVMTI_VERIFY(
NSK_CPP_STUB2(Deallocate, jvmti, (unsigned char*)threads)))
return NSK_FALSE;
if (threadForStop == NULL) {
NSK_COMPLAIN0("DebuggeeThreadForStop not found");
return NSK_FALSE;
}
if (threadForInterrupt == NULL) {
NSK_COMPLAIN0("DebuggeeThreadForInterrupt not found");
return NSK_FALSE;
}
if (!NSK_JNI_VERIFY(jni, (threadForStop =
NSK_CPP_STUB2(NewGlobalRef, jni, threadForStop)) != NULL))
return NSK_FALSE;
if (!NSK_JNI_VERIFY(jni, (threadForInterrupt =
NSK_CPP_STUB2(NewGlobalRef, jni, threadForInterrupt)) != NULL))
return NSK_FALSE;
/* enable event */
if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB4(SetEventNotificationMode,
jvmti, JVMTI_ENABLE, JVMTI_EVENT_EXCEPTION, NULL)))
return NSK_FALSE;
return NSK_TRUE;
}
/* ========================================================================== */
/** Agent algorithm. */
static void JNICALL
agentProc(jvmtiEnv* jvmti, JNIEnv* jni, void* arg) {
if (!nsk_jvmti_waitForSync(timeout))
return;
if (!prepare(jvmti, jni)) {
nsk_jvmti_setFailStatus();
return;
}
/* resume debugee and wait for sync */
if (!nsk_jvmti_resumeSync())
return;
if (!nsk_jvmti_waitForSync(timeout))
return;
NSK_DISPLAY1("ThreadDeath received: %d\n", ThreadDeathFlag);
if (!NSK_VERIFY(ThreadDeathFlag))
nsk_jvmti_setFailStatus();
NSK_DISPLAY1("InterruptedException received: %d\n",
InterruptedExceptionFlag);
if (!NSK_VERIFY(InterruptedExceptionFlag))
nsk_jvmti_setFailStatus();
/* disable event */
if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB4(SetEventNotificationMode,
jvmti, JVMTI_DISABLE, JVMTI_EVENT_EXCEPTION, NULL)))
nsk_jvmti_setFailStatus();
NSK_TRACE(NSK_CPP_STUB2(DeleteGlobalRef, jni, threadForStop));
NSK_TRACE(NSK_CPP_STUB2(DeleteGlobalRef, jni, threadForInterrupt));
if (!nsk_jvmti_resumeSync())
return;
}
/* ========================================================================== */
/** Agent library initialization. */
#ifdef STATIC_BUILD
JNIEXPORT jint JNICALL Agent_OnLoad_ma08t001a(JavaVM *jvm, char *options, void *reserved) {
return Agent_Initialize(jvm, options, reserved);
}
JNIEXPORT jint JNICALL Agent_OnAttach_ma08t001a(JavaVM *jvm, char *options, void *reserved) {
return Agent_Initialize(jvm, options, reserved);
}
JNIEXPORT jint JNI_OnLoad_ma08t001a(JavaVM *jvm, char *options, void *reserved) {
return JNI_VERSION_1_8;
}
#endif
jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
jvmtiEnv* jvmti = NULL;
jvmtiCapabilities caps;
jvmtiEventCallbacks callbacks;
NSK_DISPLAY0("Agent_OnLoad\n");
if (!NSK_VERIFY(nsk_jvmti_parseOptions(options)))
return JNI_ERR;
timeout = nsk_jvmti_getWaitTime() * 60 * 1000;
if (!NSK_VERIFY((jvmti =
nsk_jvmti_createJVMTIEnv(jvm, reserved)) != NULL))
return JNI_ERR;
if (!NSK_VERIFY(nsk_jvmti_setAgentProc(agentProc, NULL)))
return JNI_ERR;
memset(&caps, 0, sizeof(caps));
caps.can_generate_exception_events = 1;
if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(AddCapabilities, jvmti, &caps))) {
return JNI_ERR;
}
memset(&callbacks, 0, sizeof(callbacks));
callbacks.Exception = &Exception;
if (!NSK_VERIFY(nsk_jvmti_init_MA(&callbacks)))
return JNI_ERR;
return JNI_OK;
}
/* ========================================================================== */
#ifdef __cplusplus
}
#endif
| 31.449438 | 93 | 0.629391 |
932e18ad1effc8e97dc38485cfecd48d073da706 | 1,469 | h | C | PrivateFrameworks/StoreKitUI.framework/SKUIGallerySwooshPageSection.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | PrivateFrameworks/StoreKitUI.framework/SKUIGallerySwooshPageSection.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | PrivateFrameworks/StoreKitUI.framework/SKUIGallerySwooshPageSection.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/StoreKitUI.framework/StoreKitUI
*/
@interface SKUIGallerySwooshPageSection : SKUIStorePageSection <SKUIArtworkRequestDelegate, SKUIGallerySwooshViewControllerDelegate> {
NSMapTable * _componentArtworkRequests;
SKUIGallerySwooshViewController * _swooshViewController;
}
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (nonatomic, readonly) SKUISwooshPageComponent *pageComponent;
@property (readonly) Class superclass;
- (void).cxx_destruct;
- (void)_addImpressionForIndex:(long long)arg1 toSession:(id)arg2;
- (id)_newArtworkRequestWithArtwork:(id)arg1;
- (id)_swooshViewController;
- (void)addImpressionsForIndexPath:(id)arg1 toSession:(id)arg2;
- (void)artworkRequest:(id)arg1 didLoadImage:(id)arg2;
- (id)cellForIndexPath:(id)arg1;
- (struct CGSize { double x1; double x2; })cellSizeForIndexPath:(id)arg1;
- (void)dealloc;
- (id)initWithPageComponent:(id)arg1;
- (long long)numberOfCells;
- (void)prefetchResourcesWithReason:(long long)arg1;
- (void)swoosh:(id)arg1 didChangePlaybackState:(long long)arg2 forItemAtIndex:(long long)arg3;
- (void)swoosh:(id)arg1 didSelectCellAtIndex:(long long)arg2;
- (id)swoosh:(id)arg1 imageForCellAtIndex:(long long)arg2;
- (void)swoosh:(id)arg1 willDisplayCellAtIndex:(long long)arg2;
- (void)willAppearInContext:(id)arg1;
@end
| 41.971429 | 134 | 0.792376 |
932e9f5a5cad3594a3f3fa21509655924e6ebe8f | 8,277 | h | C | include/param.h | sytelus/firmware | 52f31c61c3bb90d17daacebaf908b2850a23a71e | [
"BSD-3-Clause"
] | 1 | 2019-04-12T12:30:16.000Z | 2019-04-12T12:30:16.000Z | include/param.h | sytelus/firmware | 52f31c61c3bb90d17daacebaf908b2850a23a71e | [
"BSD-3-Clause"
] | null | null | null | include/param.h | sytelus/firmware | 52f31c61c3bb90d17daacebaf908b2850a23a71e | [
"BSD-3-Clause"
] | 1 | 2019-10-22T15:30:56.000Z | 2019-10-22T15:30:56.000Z | /*
* Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
#include "mavlink.h"
#define PARAMS_NAME_LENGTH MAVLINK_MSG_PARAM_SET_FIELD_PARAM_ID_LEN
typedef enum
{
/******************************/
/*** HARDWARE CONFIGURATION ***/
/******************************/
PARAM_BAUD_RATE,
/*****************************/
/*** MAVLINK CONFIGURATION ***/
/*****************************/
PARAM_SYSTEM_ID,
PARAM_STREAM_HEARTBEAT_RATE,
PARAM_STREAM_STATUS_RATE,
PARAM_STREAM_ATTITUDE_RATE,
PARAM_STREAM_IMU_RATE,
PARAM_STREAM_MAG_RATE,
PARAM_STREAM_BARO_RATE,
PARAM_STREAM_AIRSPEED_RATE,
PARAM_STREAM_SONAR_RATE,
PARAM_STREAM_OUTPUT_RAW_RATE,
PARAM_STREAM_RC_RAW_RATE,
/********************************/
/*** CONTROLLER CONFIGURATION ***/
/********************************/
PARAM_MAX_COMMAND,
PARAM_PID_ROLL_RATE_P,
PARAM_PID_ROLL_RATE_I,
PARAM_PID_ROLL_RATE_D,
PARAM_ROLL_RATE_TRIM,
PARAM_PID_PITCH_RATE_P,
PARAM_PID_PITCH_RATE_I,
PARAM_PID_PITCH_RATE_D,
PARAM_PITCH_RATE_TRIM,
PARAM_PID_YAW_RATE_P,
PARAM_PID_YAW_RATE_I,
PARAM_PID_YAW_RATE_D,
PARAM_YAW_RATE_TRIM,
PARAM_PID_ROLL_ANGLE_P,
PARAM_PID_ROLL_ANGLE_I,
PARAM_PID_ROLL_ANGLE_D,
PARAM_ROLL_ANGLE_TRIM,
PARAM_PID_PITCH_ANGLE_P,
PARAM_PID_PITCH_ANGLE_I,
PARAM_PID_PITCH_ANGLE_D,
PARAM_PITCH_ANGLE_TRIM,
PARAM_X_EQ_TORQUE,
PARAM_Y_EQ_TORQUE,
PARAM_Z_EQ_TORQUE,
PARAM_PID_TAU,
/*************************/
/*** PWM CONFIGURATION ***/
/*************************/
PARAM_MOTOR_PWM_SEND_RATE,
PARAM_MOTOR_IDLE_THROTTLE,
PARAM_FAILSAFE_THROTTLE,
PARAM_MOTOR_MAX_PWM,
PARAM_MOTOR_MIN_PWM,
PARAM_SPIN_MOTORS_WHEN_ARMED,
/*******************************/
/*** ESTIMATOR CONFIGURATION ***/
/*******************************/
PARAM_INIT_TIME,
PARAM_FILTER_KP,
PARAM_FILTER_KI,
PARAM_FILTER_USE_QUAD_INT,
PARAM_FILTER_USE_MAT_EXP,
PARAM_FILTER_USE_ACC,
PARAM_CALIBRATE_GYRO_ON_ARM,
PARAM_GYRO_ALPHA,
PARAM_ACC_ALPHA,
PARAM_ACCEL_SCALE,
PARAM_GYRO_X_BIAS,
PARAM_GYRO_Y_BIAS,
PARAM_GYRO_Z_BIAS,
PARAM_ACC_X_BIAS,
PARAM_ACC_Y_BIAS,
PARAM_ACC_Z_BIAS,
PARAM_ACC_X_TEMP_COMP,
PARAM_ACC_Y_TEMP_COMP,
PARAM_ACC_Z_TEMP_COMP,
PARAM_MAG_A11_COMP,
PARAM_MAG_A12_COMP,
PARAM_MAG_A13_COMP,
PARAM_MAG_A21_COMP,
PARAM_MAG_A22_COMP,
PARAM_MAG_A23_COMP,
PARAM_MAG_A31_COMP,
PARAM_MAG_A32_COMP,
PARAM_MAG_A33_COMP,
PARAM_MAG_X_BIAS,
PARAM_MAG_Y_BIAS,
PARAM_MAG_Z_BIAS,
/************************/
/*** RC CONFIGURATION ***/
/************************/
PARAM_RC_TYPE,
PARAM_RC_X_CHANNEL,
PARAM_RC_Y_CHANNEL,
PARAM_RC_Z_CHANNEL,
PARAM_RC_F_CHANNEL,
PARAM_RC_ATTITUDE_OVERRIDE_CHANNEL,
PARAM_RC_THROTTLE_OVERRIDE_CHANNEL,
PARAM_RC_ATT_CONTROL_TYPE_CHANNEL,
PARAM_RC_ARM_CHANNEL,
PARAM_RC_NUM_CHANNELS,
PARAM_RC_SWITCH_5_DIRECTION,
PARAM_RC_SWITCH_6_DIRECTION,
PARAM_RC_SWITCH_7_DIRECTION,
PARAM_RC_SWITCH_8_DIRECTION,
PARAM_RC_OVERRIDE_DEVIATION,
PARAM_OVERRIDE_LAG_TIME,
PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE,
PARAM_RC_ATTITUDE_MODE,
PARAM_RC_MAX_ROLL,
PARAM_RC_MAX_PITCH,
PARAM_RC_MAX_ROLLRATE,
PARAM_RC_MAX_PITCHRATE,
PARAM_RC_MAX_YAWRATE,
/***************************/
/*** FRAME CONFIGURATION ***/
/***************************/
PARAM_MIXER,
PARAM_FIXED_WING,
PARAM_ELEVATOR_REVERSE,
PARAM_AILERON_REVERSE,
PARAM_RUDDER_REVERSE,
/********************/
/*** ARMING SETUP ***/
/********************/
PARAM_ARM_THRESHOLD,
// keep track of size of params array
PARAMS_COUNT
} param_id_t;
typedef enum uint8_t
{
PARAM_TYPE_INT32,
PARAM_TYPE_FLOAT,
PARAM_TYPE_INVALID
} param_type_t;
// function declarations
/**
* @brief Initialize parameter values
*/
void init_params(void);
/**
* @brief Set all parameters to default values
*/
void set_param_defaults(void);
/**
* @brief Read parameter values from non-volatile memory
* @return True if successful, false otherwise
*/
bool read_params(void);
/**
* @brief Write current parameter values to non-volatile memory
* @return True if successful, false otherwise
*/
bool write_params(void);
/**
* @brief Callback for executing actions that need to be taken when a parameter value changes
* @param id The ID of the parameter that was changed
*/
void param_change_callback(param_id_t id);
/**
* @brief Gets the id of a parameter from its name
* @param name The name of the parameter
* @return The ID of the parameter if the name is valid, PARAMS_COUNT otherwise (invalid ID)
*/
param_id_t lookup_param_id(const char name[PARAMS_NAME_LENGTH]);
/**
* @brief Get the value of an integer parameter by id
* @param id The ID of the parameter
* @return The value of the parameter
*/
int get_param_int(param_id_t id);
/**
* @brief Get the value of a floating point parameter by id
* @param id The ID of the parameter
* @return The value of the parameter
*/
float get_param_float(param_id_t id);
/**
* @brief Get the name of a parameter
* @param id The ID of the parameter
* @return The name of the parameter
*/
char *get_param_name(param_id_t id);
/**
* @brief Get the type of a parameter
* @param id The ID of the parameter
* @return The type of the parameter
* This returns one of three possible types
* PARAM_TYPE_INT32, PARAM_TYPE_FLOAT, or PARAM_TYPE_INVALID
* See line 165
*/
param_type_t get_param_type(param_id_t id);
/**
* @brief Sets the value of a parameter by ID and calls the parameter change callback
* @param id The ID of the parameter
* @param value The new value
* @return True if a parameter value was changed, false otherwise
*/
bool set_param_int(param_id_t id, int32_t value);
/**
* @brief Sets the value of a floating point parameter by ID and calls the parameter callback
* @param id The ID of the parameter
* @param value The new value
* @return True if a parameter was changed, false otherwise
*/
bool set_param_float(param_id_t id, float value);
/**
* @brief Sets the value of a parameter by name and calls the parameter change callback
* @param name The name of the parameter
* @param value The new value
* @return True if a parameter value was changed, false otherwise
*/
bool set_param_by_name_int(const char name[PARAMS_NAME_LENGTH], int32_t value);
/**
* @brief Sets the value of a floating point parameter by name and calls the parameter change callback
* @param name The name of the parameter
* @param value The new value
* @return True if a parameter value was changed, false otherwise
*/
bool set_param_by_name_float(const char name[PARAMS_NAME_LENGTH], float value);
#ifdef __cplusplus
}
#endif
| 26.359873 | 102 | 0.722967 |
932eb60315e2aa874db56ad1c069acb02d7ef419 | 154 | h | C | include/pocas/core/string.h | Zirias/pocas | 987e79acde3779654a8502ac9c1bebd81a823d6a | [
"BSD-2-Clause"
] | null | null | null | include/pocas/core/string.h | Zirias/pocas | 987e79acde3779654a8502ac9c1bebd81a823d6a | [
"BSD-2-Clause"
] | null | null | null | include/pocas/core/string.h | Zirias/pocas | 987e79acde3779654a8502ac9c1bebd81a823d6a | [
"BSD-2-Clause"
] | null | null | null | #ifndef POCAS_CORE_STRING_H
#define POCAS_CORE_STRING_H
#include <pocas/core/decl.h>
DECLEXPORT char *PC_String_copy(const char *self);
#endif
| 17.111111 | 51 | 0.75974 |
932fe44875180ed6b78a1bf4e67c2df92617f826 | 733 | c | C | polynomialSum/main.c | zhongchen43/data-structure-algorithms | 96e1c99c2f052e25d140f90fcb1331b37ed6ee84 | [
"MIT"
] | null | null | null | polynomialSum/main.c | zhongchen43/data-structure-algorithms | 96e1c99c2f052e25d140f90fcb1331b37ed6ee84 | [
"MIT"
] | null | null | null | polynomialSum/main.c | zhongchen43/data-structure-algorithms | 96e1c99c2f052e25d140f90fcb1331b37ed6ee84 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
#include <time.h>
#define MAXN 10
//compute f = a0 + a1*x + ...an * (x^n)
// normal impletation
double f(int n, double a[], double x)
{
double p = a[0];
for(int i=1;i<=n;i++)
p += (a[i] * pow(x, i));
return p;
}
// opt
double fOpt(int n, double a[], double x)
{
double p = a[n];
for(int i=n;i>0;i--)
p = a[i-1] + x*p;
return p;
}
int main()
{
double a[MAXN];
for(int i=0; i<MAXN; i++)
a[i] = (double)i;
clock_t start, stop;
double duration;
start = clock();
f(MAXN-1, a, 1.1);
// fOpt(MAXN-1, a, 1.1);
stop = clock();
duration = ((double)(stop-start));
printf("ticks = %f\n", duration);
return 0;
}
| 17.046512 | 40 | 0.503411 |
93310d34e54a7742f5a5135b1be5d42665dfc3a8 | 7,769 | c | C | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/vlcom_c.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 6 | 2022-01-21T19:58:08.000Z | 2022-03-28T12:32:24.000Z | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/vlcom_c.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | null | null | null | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/vlcom_c.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 4 | 2022-02-12T10:01:40.000Z | 2022-03-28T14:28:52.000Z | /*
-Procedure vlcom_c ( Vector linear combination, 3 dimensions )
-Abstract
Compute a vector linear combination of two double precision,
3-dimensional vectors.
-Disclaimer
THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
-Required_Reading
None.
-Keywords
VECTOR
*/
#include "SpiceUsr.h"
#undef vlcom_c
void vlcom_c ( SpiceDouble a,
ConstSpiceDouble v1[3],
SpiceDouble b,
ConstSpiceDouble v2[3],
SpiceDouble sum[3] )
/*
-Brief_I/O
VARIABLE I/O DESCRIPTION
-------- --- --------------------------------------------------
a I Coefficient of `v1'.
v1 I Vector in 3-space.
b I Coefficient of `v2'.
v2 I Vector in 3-space.
sum O Linear vector combination a*v1 + b*v2.
-Detailed_Input
a is the double precision scalar variable that multiplies
`v1'.
v1 is an arbitrary, double precision 3-dimensional vector.
b is the double precision scalar variable that multiplies
`v2'.
v2 is an arbitrary, double precision 3-dimensional vector.
-Detailed_Output
sum is the double precision 3-dimensional vector which
contains the linear combination
a * v1 + b * v2
-Parameters
None.
-Exceptions
Error free.
-Files
None.
-Particulars
The code reflects precisely the following mathematical expression
For each value of the index `i', from 0 to 2:
sum[i] = a*v1[i] + b*v2[i]
No error checking is performed to guard against numeric overflow.
-Examples
The numerical results shown for these examples may differ across
platforms. The results depend on the SPICE kernels used as
input, the compiler and supporting libraries, and the machine
specific arithmetic implementation.
1) Suppose you want to generate a sequence of points representing
an elliptical footprint, from the known semi-major
and semi-minor axes.
Example code begins here.
/.
Program vlcom_ex1
./
#include <math.h>
#include <stdio.h>
#include "SpiceUsr.h"
int main( )
{
/.
Local variables.
./
SpiceDouble step;
SpiceDouble theta;
SpiceDouble vector [3];
SpiceInt i;
/.
Let `smajor' and `sminor' be the two known semi-major and
semi-minor axes of our elliptical footprint.
./
SpiceDouble smajor [3] = { 0.070115, 0.0, 0.0 };
SpiceDouble sminor [3] = { 0.0, 0.035014, 0.0 };
/.
Compute the vectors of interest and display them
./
theta = 0.0;
step = twopi_c() / 16;
for ( i = 0; i < 16; i++ )
{
vlcom_c ( cos(theta), smajor, sin(theta), sminor, vector );
printf( "%2d: %9.6f %9.6f %9.6f\n",
i, vector[0], vector[1], vector[2] );
theta = theta + step;
}
return ( 0 );
}
When this program was executed on a Mac/Intel/cc/64-bit
platform, the output was:
0: 0.070115 0.000000 0.000000
1: 0.064778 0.013399 0.000000
2: 0.049579 0.024759 0.000000
3: 0.026832 0.032349 0.000000
4: 0.000000 0.035014 0.000000
5: -0.026832 0.032349 0.000000
6: -0.049579 0.024759 0.000000
7: -0.064778 0.013399 0.000000
8: -0.070115 0.000000 0.000000
9: -0.064778 -0.013399 -0.000000
10: -0.049579 -0.024759 -0.000000
11: -0.026832 -0.032349 -0.000000
12: -0.000000 -0.035014 -0.000000
13: 0.026832 -0.032349 0.000000
14: 0.049579 -0.024759 0.000000
15: 0.064778 -0.013399 0.000000
2) As a second example, suppose that U and V are orthonormal
vectors that form a basis of a plane. Moreover suppose that we
wish to project a vector X onto this plane.
Example code begins here.
/.
Program vlcom_ex2
./
#include <math.h>
#include <stdio.h>
#include "SpiceUsr.h"
int main( )
{
/.
Local variables.
./
SpiceDouble puv [3];
SpiceDouble v [3];
/.
Let `x' be an arbitrary 3-vector
./
SpiceDouble x [3] = { 4.0, 35.0, -5.0 };
/.
Let `u' and `v' be orthonormal 3-vectors spanning the
plane of interest.
./
SpiceDouble u [3] = { 0.0, 0.0, 1.0 };
v[0] = sqrt(2.0)/2.0;
v[1] = -sqrt(2.0)/2.0;
v[2] = 0.0;
/.
Compute the projection of `x' onto this 2-dimensional
plane in 3-space.
./
vlcom_c ( vdot_c ( x, u ), u, vdot_c ( x, v ), v, puv );
/.
Display the results.
./
printf( "Input vector : %5.1f %5.1f %5.1f\n",
x[0], x[1], x[2] );
printf( "Projection into 2-d plane: %5.1f %5.1f %5.1f\n",
puv[0], puv[1], puv[2] );
return ( 0 );
}
When this program was executed on a Mac/Intel/cc/64-bit
platform, the output was:
Input vector : 4.0 35.0 -5.0
Projection into 2-d plane: -15.5 15.5 -5.0
-Restrictions
1) No error checking is performed to guard against numeric
overflow or underflow. The user is responsible for insuring
that the input values are reasonable.
-Literature_References
None.
-Author_and_Institution
N.J. Bachman (JPL)
J. Diaz del Rio (ODC Space)
W.L. Taber (JPL)
E.D. Wright (JPL)
-Version
-CSPICE Version 1.1.1, 13-AUG-2021 (JDR)
Edited the header to comply with NAIF standard. Added complete
code example.
-CSPICE Version 1.1.0, 22-OCT-1998 (NJB)
Made input vectors const.
-CSPICE Version 1.0.0, 08-FEB-1998 (EDW) (WLT)
-Index_Entries
linear combination of two 3-dimensional vectors
-&
*/
{ /* Begin vlcom_c */
/* This really doesn't require a degree in rocket science */
sum[0] = a*v1[0] + b*v2[0];
sum[1] = a*v1[1] + b*v2[1];
sum[2] = a*v1[2] + b*v2[2];
} /* End vlcom_c */
| 25.388889 | 73 | 0.564809 |
93326a3e1bf8c744de86a4089b6a4c3c15f81107 | 1,584 | h | C | sdk/include/feos/types.h | fincs/FeOS-v2 | 369bed95e8f472f05a1e6995d30673e158bf812e | [
"MIT"
] | 1 | 2019-01-22T18:52:00.000Z | 2019-01-22T18:52:00.000Z | sdk/include/feos/types.h | fincs/FeOS-v2 | 369bed95e8f472f05a1e6995d30673e158bf812e | [
"MIT"
] | null | null | null | sdk/include/feos/types.h | fincs/FeOS-v2 | 369bed95e8f472f05a1e6995d30673e158bf812e | [
"MIT"
] | null | null | null | #pragma once
// These are supplied by the compiler
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <limits.h>
typedef uint8_t byte_t;
typedef uint16_t hword_t;
typedef uint32_t word_t;
typedef uint64_t dword_t;
typedef int8_t char_t;
typedef int16_t short_t;
typedef int32_t long_t;
typedef int64_t dlong_t;
typedef byte_t u8;
typedef hword_t u16;
typedef word_t u32;
typedef dword_t u64;
typedef char_t s8;
typedef short_t s16;
typedef long_t s32;
typedef dlong_t s64;
typedef float f32;
typedef double f64;
typedef volatile u8 vu8;
typedef volatile u16 vu16;
typedef volatile u32 vu32;
typedef volatile u64 vu64;
typedef volatile s8 vs8;
typedef volatile s16 vs16;
typedef volatile s32 vs32;
typedef volatile s64 vs64;
typedef volatile f32 vf32;
typedef volatile f64 vf64;
typedef void (* fp_t)(void);
#ifndef __cplusplus
#define nullptr NULL
#endif
#define BIT(n) (1 << (n))
#ifdef FEOS_KERNEL
#ifdef FEOS_KMODULE
#define _STATIC
#else
#define _STATIC static
#endif
#endif
#define FEOS_EXPORT __attribute__((__visibility__("default"))) //!< Exported symbol attribute.
#define FEOS_WEAK __attribute__((weak)) //!< Weak symbol attribute.
#define FEOS_DEPRECATED __attribute__((deprecated)) //!< Deprecated symbol attribute.
#define FEOS_INIT __attribute__((constructor)) //!< Initialization function attribute. Makes a function be automatically called when a module is loaded.
#define FEOS_FINI __attribute__((destructor)) //!< Deinitialization function attribute. Makes a function be automatically called when a module is unloaded.
| 25.967213 | 155 | 0.787247 |
9333e3d0da94e01ad3522e5ff9b83258475eb135 | 680 | c | C | io/src/sput/fox_sputnbr.c | fox-tek/libfox | da842455e90e1152d4fd1dd8701c459fb8702657 | [
"MIT"
] | 2 | 2021-06-30T22:37:42.000Z | 2021-11-08T09:35:52.000Z | io/src/sput/fox_sputnbr.c | fox-tek/libfox | da842455e90e1152d4fd1dd8701c459fb8702657 | [
"MIT"
] | null | null | null | io/src/sput/fox_sputnbr.c | fox-tek/libfox | da842455e90e1152d4fd1dd8701c459fb8702657 | [
"MIT"
] | null | null | null | /*
** (not) EPITECH PROJECT, 2021
** Libfox
** File description:
** Write a number to an already allocated string
*/
#include <stdbool.h>
#include <sys/types.h>
#include "fox_define.h"
#include "fox_math.h"
#include "fox_string.h"
__Anonnull ssize_t fox_sputnbr(str_t s, llong_t n)
{
bool isneg = (n < 0);
size_t sz = fox_numsize(n);
*s = '-' * isneg;
s += isneg;
for (hindex_t i = 0; i < sz; i += 1) {
s[i] = N_TO_CHAR(N_ABS(n % 10));
n /= 10;
}
for (hindex_t i = 0; i < sz / 2; i += 1) {
s[i] ^= s[sz - i - 1];
s[sz - i - 1] ^= s[i];
s[i] ^= s[sz - i - 1];
}
s[sz] = '\0';
return sz + isneg;
}
| 20 | 50 | 0.507353 |
93342c02223d3cd3ee3ee69f7c3ce81439dbba91 | 155 | h | C | ios/RCTTICBridgeView.h | kzyman/react-native-tx-education | 2f95c81ecde7a7752c9faf91fcde4815b97f6e2b | [
"MIT"
] | null | null | null | ios/RCTTICBridgeView.h | kzyman/react-native-tx-education | 2f95c81ecde7a7752c9faf91fcde4815b97f6e2b | [
"MIT"
] | null | null | null | ios/RCTTICBridgeView.h | kzyman/react-native-tx-education | 2f95c81ecde7a7752c9faf91fcde4815b97f6e2b | [
"MIT"
] | null | null | null | #import <Foundation/Foundation.h>
#import <TEduBoard/TEduBoard.h>
#import <React/RCTViewManager.h>
@interface TICBridgeViewManager : RCTViewManager
@end
| 19.375 | 48 | 0.8 |
9334e0f38e9331f669dc8e065bc03296ab3197d3 | 977 | c | C | ft_strclr.c | Maljean/libft | a5e83fd6e869202da44ff6d5f581ae4e11f830ad | [
"MIT"
] | null | null | null | ft_strclr.c | Maljean/libft | a5e83fd6e869202da44ff6d5f581ae4e11f830ad | [
"MIT"
] | null | null | null | ft_strclr.c | Maljean/libft | a5e83fd6e869202da44ff6d5f581ae4e11f830ad | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strclr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: maljean <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/22 14:02:12 by maljean #+# #+# */
/* Updated: 2018/02/22 14:03:39 by maljean ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_strclr(char *s)
{
if (s)
ft_bzero(s, ft_strlen(s));
}
| 48.85 | 80 | 0.14739 |
9338c23bfdcf65db0540e15d6186649b76e1403d | 15,636 | c | C | src/main.c | ArneDJ/terragen | 6f7bd66526f8e84919273fa9d1ee9879a47379e1 | [
"MIT"
] | null | null | null | src/main.c | ArneDJ/terragen | 6f7bd66526f8e84919273fa9d1ee9879a47379e1 | [
"MIT"
] | null | null | null | src/main.c | ArneDJ/terragen | 6f7bd66526f8e84919273fa9d1ee9879a47379e1 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <time.h>
#include <SDL2/SDL.h>
#include <GL/glew.h>
#include <GL/gl.h>
#include "gmath.h"
#include "camera.h"
#include "mesh.h"
#include "shader.h"
#include "texture.h"
#include "imp.h"
#include "voronoi.h"
#define IIR_GAUSS_BLUR_IMPLEMENTATION
#include "gauss.h"
#define WINDOW_WIDTH 1920
#define WINDOW_HEIGHT 1080
enum celltype {
COASTAL,
INLAND,
MOUNTAIN,
};
struct vorcell {
vec2 center;
enum celltype type;
jcv_site site;
};
struct object {
struct mesh m;
GLuint texture;
GLuint shader;
vec3 translation;
vec3 rotation;
vec3 scale;
struct AABB bbox;
};
struct terrain {
struct mesh m;
GLuint shader;
GLuint heightmap;
GLuint texture[5];
};
struct water {
struct mesh m;
GLuint shader;
GLuint diffuse;
GLuint normal;
GLuint depthmap;
GLuint depthtexture;
GLuint depth_fbo;
};
static GLuint make_terrain_heightmap(unsigned int res);
static struct object make_skybox(void)
{
struct object skybox = {0};
struct shader pipeline[] = {
{GL_VERTEX_SHADER, "data/shader/skyboxv.glsl"},
{GL_FRAGMENT_SHADER, "data/shader/skyboxf.glsl"},
{GL_NONE, NULL}
};
skybox.shader = load_shaders(pipeline);
mat4 model = IDENTITY_MATRIX;
mat4 project = make_project_matrix(90, (float)WINDOW_WIDTH/(float)WINDOW_HEIGHT, 0.1, 200.0);
glUseProgram(skybox.shader);
glUniformMatrix4fv(glGetUniformLocation(skybox.shader, "project"), 1, GL_FALSE, project.f);
skybox.m = make_cube_mesh();
return skybox;
}
static void display_skybox(struct object *sky)
{
glUseProgram(sky->shader);
glDisable(GL_CULL_FACE);
glDepthFunc(GL_LEQUAL);
glBindVertexArray(sky->m.VAO);
glDrawArrays(GL_TRIANGLES, 0, sky->m.vcount);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
}
static struct water make_water(GLuint depthmap)
{
struct water wat;
struct shader pipeline[] = {
{GL_VERTEX_SHADER, "data/shader/waterv.glsl"},
{GL_TESS_CONTROL_SHADER, "data/shader/watertc.glsl"},
{GL_TESS_EVALUATION_SHADER, "data/shader/waterte.glsl"},
{GL_FRAGMENT_SHADER, "data/shader/waterf.glsl"},
{GL_NONE, NULL}
};
wat.shader = load_shaders(pipeline);
wat.m = make_grid_mesh(64, 64, 1.0);
wat.depthmap = depthmap;
wat.normal = load_dds_texture("media/texture/water_normal.dds");
mat4 project = make_project_matrix(90, (float)WINDOW_WIDTH/(float)WINDOW_HEIGHT, 0.1, 200.0);
glUseProgram(wat.shader);
glUniformMatrix4fv(glGetUniformLocation(wat.shader, "project"), 1, GL_FALSE, project.f);
return wat;
}
static void display_water(struct water *wat)
{
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glUseProgram(wat->shader);
glUniform1i(glGetUniformLocation(wat->shader, "heightmap_terrain"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, wat->depthmap);
glUniform1i(glGetUniformLocation(wat->shader, "water_normal"), 1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, wat->normal);
glUniform1i(glGetUniformLocation(wat->shader, "water_depth_buffer"), 2);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, wat->depthtexture);
glBindVertexArray(wat->m.VAO);
glPatchParameteri(GL_PATCH_VERTICES, 3);
glDrawArrays(GL_PATCHES, 0, wat->m.vcount);
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
static struct terrain make_terrain(int resolution)
{
struct terrain ter = {0};
struct shader pipeline[] = {
{GL_VERTEX_SHADER, "data/shader/terrainv.glsl"},
{GL_TESS_CONTROL_SHADER, "data/shader/terraintc.glsl"},
{GL_TESS_EVALUATION_SHADER, "data/shader/terrainte.glsl"},
{GL_FRAGMENT_SHADER, "data/shader/terrainf.glsl"},
{GL_NONE, NULL}
};
ter.shader = load_shaders(pipeline);
ter.m = make_patch_mesh(64,64, 1.0);
ter.heightmap = make_terrain_heightmap(resolution);
ter.texture[0] = load_dds_texture("media/texture/grass.dds");
ter.texture[1] = load_dds_texture("media/texture/rock.dds");
ter.texture[2] = load_dds_texture("media/texture/graydirt.dds");
ter.texture[3] = load_dds_texture("media/texture/snowrocks.dds");
mat4 project = make_project_matrix(90, (float)WINDOW_WIDTH/(float)WINDOW_HEIGHT, 0.1, 200.0);
glUseProgram(ter.shader);
glUniformMatrix4fv(glGetUniformLocation(ter.shader, "project"), 1, GL_FALSE, project.f);
return ter;
}
static void display_terrain(struct terrain *ter)
{
glUseProgram(ter->shader);
glUniform1i(glGetUniformLocation(ter->shader, "grass"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, ter->texture[0]);
glUniform1i(glGetUniformLocation(ter->shader, "stone"), 1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, ter->texture[1]);
glUniform1i(glGetUniformLocation(ter->shader, "gravel"), 2);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, ter->texture[2]);
glUniform1i(glGetUniformLocation(ter->shader, "snow"), 3);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, ter->texture[3]);
glUniform1i(glGetUniformLocation(ter->shader, "heightmap"), 4);
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, ter->heightmap);
glBindVertexArray(ter->m.VAO);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glPatchParameteri(GL_PATCH_VERTICES, 4);
glDrawArrays(GL_PATCHES, 0, ter->m.vcount);
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
// Remaps the point from the input space to image space
static inline jcv_point remap(const jcv_point* pt, const jcv_point* min, const jcv_point* max, int width, int height)
{
jcv_point p;
p.x = (pt->x - min->x)/(max->x - min->x) * (jcv_real)width;
p.y = (pt->y - min->y)/(max->y - min->y) * (jcv_real)height;
return p;
}
static GLuint make_terrain_heightmap(unsigned int res)
{
const size_t size = res * res;
unsigned char *perlin = calloc(size, sizeof(unsigned char));
unsigned char *mountainr = calloc(size, sizeof(unsigned char));
unsigned char *image = calloc(size, sizeof(unsigned char));
unsigned char *cpy = calloc(size, sizeof(unsigned char));
unsigned char red = 255.0;
unsigned char black = 0.0;
unsigned char water = 0.0;
unsigned char land = 100.0;
unsigned char coastclr = 200.0;
int nbuf = 0;
for(int x = 0; x < res; x++) {
for(int y = 0; y < res; y++) {
float z = fbm_noise(0.5*x, 0.5*y, 0.005, 2.5, 2.0);
perlin[nbuf] = z * 255.0;
if (z > 0.55) {
z = land;
} else {
z = water;
}
image[nbuf++] = z;
}
}
const int MIN_LAKE_SIZE = res * 2;
const int MIN_ISLAND_SIZE = res;
/* remove small lakes */
memcpy(cpy, image, size);
for (int x = 0; x < res; x++) {
for (int y = 0; y < res; y++) {
int index = y * res + x ;
int size = floodfill(x, y, cpy, res, res, water, land);
if (size < MIN_LAKE_SIZE && size > 1) {
floodfill(x, y, image, res, res, water, land);
}
}
}
/* remove small islands */
memcpy(cpy, image, size);
for (int x = 0; x < res; x++) {
for (int y = 0; y < res; y++) {
int index = y * res + x ;
int size = floodfill(x, y, cpy, res, res, land, water);
if (size < MIN_ISLAND_SIZE && size > 1) {
floodfill(x, y, image, res, res, land, water);
}
}
}
/* generate site points */
const int MAX_SITES = 500;
jcv_point site[MAX_SITES];
int nsite = 0;
while (nsite < MAX_SITES) {
float x = frand(res);
float y = frand(res);
int index = (int)y * res + (int)x;
if (image[index] == land) {
site[nsite].x = x;
site[nsite].y = y;
nsite++;
}
}
jcv_diagram diagram;
memset(&diagram, 0, sizeof(jcv_diagram));
jcv_diagram_generate(MAX_SITES, site, 0, 0, &diagram);
/* plot the sites */
unsigned char sitecolor = 155.0;
const jcv_site *sites = jcv_diagram_get_sites(&diagram);
/*
for (int i = 0; i < diagram.numsites; i++) {
const jcv_site *site = &sites[i];
jcv_point p = site->p;
plot((int)p.x, (int)p.y, image, res, res, 1, &sitecolor);
}
*/
/* find the coastal cells */
/* points don't account for image space! convert them! */
struct vorcell vcell[MAX_SITES];
for (int i = 0; i < MAX_SITES; i++) {
vcell[i].site = sites[i];
vcell[i].center.x = sites[i].p.x;
vcell[i].center.y = sites[i].p.y;
const jcv_graphedge *e = vcell[i].site.edges;
while (e) {
jcv_point p1 = remap(&e->pos[0], &diagram.min, &diagram.max, res, res);
jcv_point p2 = remap(&e->pos[1], &diagram.min, &diagram.max, res, res);
const int index1 = (int)p1.y * res + (int)p1.x;
const int index2 = (int)p2.y * res + (int)p2.x;
if (image[index1] == water || image[index2] == water) {
vcell[i].type = COASTAL;
break;
} else {
vcell[i].type = INLAND;
}
e = e->next;
}
}
iir_gauss_blur(res, res, 1, image, 5.0);
/* ADD MOUNTAINS */
const float MIN_MOUNTAIN_HEIGHT = 0.7;
for (int i = 0; i < MAX_SITES; i++) {
const int index = (int)vcell[i].center.y * res + (int)vcell[i].center.x;
const float hsample = perlin[index]/255.f;
if (hsample > MIN_MOUNTAIN_HEIGHT && vcell[i].type == INLAND) {
vcell[i].type = MOUNTAIN;
const jcv_graphedge *e = vcell[i].site.edges;
while (e) {
draw_triangle(vcell[i].center.x, vcell[i].center.y, e->pos[0].x, e->pos[0].y, e->pos[1].x, e->pos[1].y, mountainr, res, res, 1, &red);
e = e->next;
}
}
}
iir_gauss_blur(res, res, 1, mountainr, 10.0);
for (int x = 0; x < res; x++) {
for (int y = 0; y < res; y++) {
int index = y * res + x;
float mountains = 1.0 - (sqrt(worley_noise(0.02*x, 0.030*y)));
float ridge = worley_noise(x * 0.03, y * 0.02);
float range = mountainr[index]/255.f;
mountains *= range * 0.6;
ridge *= range * 0.6;
image[index] = 255.0 * (image[index]/255.f + ((mountains + ridge) / 2.0));
}
}
/* ADD RIVERS */
/* maker river candidate network */
srand(time(NULL));
const float RIVER_WIDTH = 8.0;
unsigned char color_line = 0.0;
unsigned char *riverr = calloc(size, sizeof(unsigned char));
for (int i = 0; i < size; i++) {
riverr[i] = 255.0;
}
//memcpy(riverr, image, size);
for (int i = 0; i < 20; i++) {
int startindex = rand() % MAX_SITES;
const jcv_site *rsite = &vcell[startindex].site;
if (vcell[startindex].type == MOUNTAIN) {
for (int i = 0; i < 500; i++) {
jcv_point c1 = remap(&rsite->p, &diagram.min, &diagram.max, res, res);
const jcv_graphedge *e = rsite->edges;
rsite = e->neighbor;
jcv_point c2 = remap(&rsite->p, &diagram.min, &diagram.max, res, res);
draw_thick_line(c1.x, c1.y, c2.x, c2.y, riverr, res, res, 1, &color_line, RIVER_WIDTH);
int out = 0;
while (e) {
jcv_point p1 = remap(&e->pos[0], &diagram.min, &diagram.max, res, res);
jcv_point p2 = remap(&e->pos[1], &diagram.min, &diagram.max, res, res);
const int index1 = (int)p1.y * res + (int)p1.x;
const int index2 = (int)p2.y * res + (int)p2.x;
if (image[index1] == water) {
draw_thick_line(c2.x, c2.y, p1.x, p1.y, riverr, res, res, 1, &color_line, RIVER_WIDTH);
out = 1;
break;
} else if (image[index2] == water) {
draw_thick_line(c2.x, c2.y, p2.x, p2.y, riverr, res, res, 1, &color_line, RIVER_WIDTH);
out = 1;
break;
}
e = e->next;
}
if (out) {
break;
}
}
}
}
iir_gauss_blur(res, res, 1, riverr, 5.0);
for (int i = 0; i < size; i++) {
image[i] = 255.0 * (image[i]/255.f) * (riverr[i]/255.f);
}
/*
const jcv_edge *edge = jcv_diagram_get_edges(&diagram);
while (edge) {
draw_line((int)edge->pos[0].x, (int)edge->pos[0].y, (int)edge->pos[1].x, (int)edge->pos[1].y, image, res, res, 1, &sitecolor);
edge = jcv_diagram_get_next_edge(edge);
}
*/
GLuint texnum = make_r_texture(image, res, res);
jcv_diagram_free(&diagram);
free(image);
free(mountainr);
free(cpy);
free(perlin);
free(riverr);
return texnum;
}
static void run_loop(SDL_Window *window)
{
float start, end = 0.0;
SDL_SetRelativeMouseMode(SDL_TRUE);
struct camera cam = init_camera(1.0, 1.0, 1.0, 90.0, 0.2);
struct terrain terra = make_terrain(2048);
struct object sky = make_skybox();
struct mesh cube = make_grid_mesh(1, 1, 10.0);
GLuint texture = terra.heightmap;
// INITIALIZE DEPTH FRAME BUFFER //
struct water wat = make_water(terra.heightmap);
wat.depth_fbo = init_depth_framebuffer(&wat.depthtexture, 1024, 1024);
struct shader pipeline[] = {
{GL_VERTEX_SHADER, "data/shader/cubev.glsl"},
{GL_FRAGMENT_SHADER, "data/shader/cubef.glsl"},
{GL_NONE, NULL}
};
GLuint program = load_shaders(pipeline);
mat4 model = IDENTITY_MATRIX;
mat4 project = make_project_matrix(90, (float)WINDOW_WIDTH/(float)WINDOW_HEIGHT, 0.1, 200.0);
glUseProgram(program);
glUniformMatrix4fv(glGetUniformLocation(program, "project"), 1, GL_FALSE, project.f);
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_FALSE, model.f);
/* MASTER LOOP */
SDL_Event event;
while (event.type != SDL_QUIT) {
const float gtime = (float)SDL_GetTicks();
start = gtime;
float delta = start - end;
while(SDL_PollEvent(&event));
/* update camera */
update_free_camera(&cam, 0.001 * delta);
mat4 view = make_view_matrix(cam.eye, cam.center, cam.up);
mat4 skybox_view = view;
skybox_view.f[12] = 0.0;
skybox_view.f[13] = 0.0;
skybox_view.f[14] = 0.0;
/* update scene */
glUseProgram(program);
glUniformMatrix4fv(glGetUniformLocation(program, "view"), 1, GL_FALSE, view.f);
glUseProgram(terra.shader);
glUniformMatrix4fv(glGetUniformLocation(terra.shader, "view"), 1, GL_FALSE, view.f);
glUniformMatrix4fv(glGetUniformLocation(terra.shader, "view"), 1, GL_FALSE, view.f);
glUniform3fv(glGetUniformLocation(terra.shader, "view_center"), 1, cam.center.f);
glUniform3fv(glGetUniformLocation(terra.shader, "view_eye"), 1, cam.eye.f);
glUseProgram(wat.shader);
glUniformMatrix4fv(glGetUniformLocation(wat.shader, "view"), 1, GL_FALSE, view.f);
glUniform3fv(glGetUniformLocation(wat.shader, "view_dir"), 1, cam.center.f);
glUniform3fv(glGetUniformLocation(wat.shader, "view_eye"), 1, cam.eye.f);
glUniform1f(glGetUniformLocation(wat.shader, "time"), gtime);
glUseProgram(sky.shader);
glUniformMatrix4fv(glGetUniformLocation(sky.shader, "view"), 1, GL_FALSE, skybox_view.f);
glViewport(0, 0, 1024, 1024);
glBindFramebuffer(GL_FRAMEBUFFER, wat.depth_fbo);
glClear(GL_DEPTH_BUFFER_BIT);
display_terrain(&terra);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
/* render */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(cube.VAO);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawArrays(GL_TRIANGLES, 0, cube.vcount);
display_terrain(&terra);
display_water(&wat);
display_skybox(&sky);
/* swap buffer */
SDL_GL_SwapWindow(window);
end = start;
}
}
static SDL_Window *init_window(int width, int height)
{
SDL_Window *window;
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Terragen", 0, 0,
WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL);
if (window == NULL) {
printf("error: could not create window: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
return window;
}
static SDL_GLContext init_glcontext(SDL_Window *window)
{
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
if (glewInit()) {
fprintf(stderr, "unable to init glew\n");
exit(EXIT_FAILURE);
}
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return glcontext;
}
int main(int argc, char *argv[])
{
SDL_Window *window = init_window(WINDOW_WIDTH, WINDOW_HEIGHT);
SDL_GLContext glcontext = init_glcontext(window);
run_loop(window);
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
exit(EXIT_SUCCESS);
}
| 27.57672 | 138 | 0.682911 |
933b6562065e26ec6b54bff324ee38b250f516a9 | 4,295 | c | C | src/util.c | Sigurdurhelga/blabbr | e050cfc4de10f3aadd3b5a48c1fb8bed365aa0b4 | [
"MIT"
] | 1 | 2018-08-17T05:43:20.000Z | 2018-08-17T05:43:20.000Z | src/util.c | jamesrobb/blabbr | e050cfc4de10f3aadd3b5a48c1fb8bed365aa0b4 | [
"MIT"
] | null | null | null | src/util.c | jamesrobb/blabbr | e050cfc4de10f3aadd3b5a48c1fb8bed365aa0b4 | [
"MIT"
] | null | null | null | // open ssl headers
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <locale.h>
#include "util.h"
void gdateweekday_to_gstring(GDateWeekday day, GString *name) {
switch(day) {
case G_DATE_BAD_WEEKDAY:
g_string_append(name, "Non");
return;
case G_DATE_MONDAY:
g_string_append(name, "Mon");
return;
case G_DATE_TUESDAY:
g_string_append(name, "Tue");
return;
case G_DATE_WEDNESDAY:
g_string_append(name, "Wed");
return;
case G_DATE_THURSDAY:
g_string_append(name, "Thu");
return;
case G_DATE_FRIDAY:
g_string_append(name, "Fri");
return;
case G_DATE_SATURDAY:
g_string_append(name, "Sat");
return;
case G_DATE_SUNDAY:
g_string_append(name, "Sun");
return;
default:
g_string_append(name, "Non");
return;
}
}
void gdatemonth_to_gstring(GDateMonth mon, GString *name) {
switch(mon) {
case G_DATE_BAD_MONTH:
g_string_append(name, "Non");
return;
case G_DATE_JANUARY:
g_string_append(name, "Jan");
return;
case G_DATE_FEBRUARY:
g_string_append(name, "Feb");
return;
case G_DATE_MARCH:
g_string_append(name, "Mar");
return;
case G_DATE_APRIL:
g_string_append(name, "Apr");
return;
case G_DATE_MAY:
g_string_append(name, "May");
return;
case G_DATE_JUNE:
g_string_append(name, "Jun");
return;
case G_DATE_JULY:
g_string_append(name, "Jul");
return;
case G_DATE_AUGUST:
g_string_append(name, "Aug");
return;
case G_DATE_SEPTEMBER:
g_string_append(name, "Sep");
return;
case G_DATE_OCTOBER:
g_string_append(name, "Oct");
return;
case G_DATE_NOVEMBER:
g_string_append(name, "Nov");
return;
case G_DATE_DECEMBER:
g_string_append(name, "Dec");
return;
}
}
int gchar_array_len(gchar *arr) {
// this function assumes arr is null terminated
int len = 0;
while(arr[len] != '\0') {
len++;
if(len >= LONG_STRING_WARNING) {
g_warning("string passed to gchar_array_len is very long");
}
}
return len+1;
}
int gchar_array_array_len(gchar **arr) {
// returns the length of an array of gchar arrays
int len = 0;
while(arr[len]) {
len++;
}
return len;
}
void ghash_table_strstr_iterator(gpointer key, gpointer value, G_GNUC_UNUSED gpointer user_data) {
g_print("field: %s, value: %s\n", (gchar*) key, (gchar*) value);
return;
}
void ghash_table_gchar_destroy(gpointer value) {
g_free((gchar *) value);
}
// strips strip_char from the source and saves the stripped array to the destination.
void gchar_char_strip(gchar *destination, gchar* source, gchar strip_char) {
int length = gchar_array_len(source);
int destpos = 0;
for(int i = 0; i < length; i++) {
if(source[i] != strip_char) {
destination[destpos] = source[i];
destpos++;
}
}
}
void ssl_print_error(int ssl_error) {
switch(ssl_error) {
case SSL_ERROR_NONE:
g_info("SSL_ERROR_NONE");
break;
case SSL_ERROR_ZERO_RETURN:
g_info("SSL_ERROR_ZERO_RETURN");
break;
case SSL_ERROR_WANT_READ:
g_info("SSL_ERROR_WANT_READ");
break;
case SSL_ERROR_WANT_WRITE:
g_info("SSL_ERROR_WANT_WRITE");
break;
case SSL_ERROR_WANT_CONNECT:
g_info("SSL_ERROR_WANT_CONNECT");
break;
case SSL_ERROR_WANT_ACCEPT:
g_info("SSL_ERROR_WANT_ACCEPT");
break;
case SSL_ERROR_WANT_X509_LOOKUP:
g_info("SSL_ERROR_WANT_X509_LOOKUP");
break;
case SSL_ERROR_SYSCALL:
g_info("SSL_ERROR_SYSCALL");
break;
case SSL_ERROR_SSL:
g_info("SSL_ERROR_SSL");
break;
default:
ERR_print_errors_fp(stdout);
g_info("SOME OTHER SSL PROBLEM %d", ssl_error);
break;
}
}
gchar* wchars_to_gchars(wchar_t *source) {
// for unicode purposes
setlocale(LC_ALL, "en_US.utf8");
int dest_len = (wcslen(source) * sizeof(wchar_t)) + 1;
gchar *dest_pointer = g_malloc(dest_len);
wcstombs(dest_pointer, source, dest_len);
return dest_pointer;
}
int wint_chars_len(wint_t *arr, int max) {
int length = 0;
while(length < max) {
if(arr[length] == 0) {
break;
}
length++;
}
return length;
} | 22.025641 | 98 | 0.650524 |
933ba6eee60f4df7ebb7bf5e304f46c7fb31c791 | 2,337 | c | C | csc501-lab3/mon/monboot.c | zyczyh/OS-Course-Project-3 | d929b87fc678762cdcda7e4aaf328c8e4ad2ba04 | [
"MIT"
] | 1 | 2019-01-24T02:34:02.000Z | 2019-01-24T02:34:02.000Z | csc501-lab3/mon/monboot.c | zyczyh/OS-Course-Project-3 | d929b87fc678762cdcda7e4aaf328c8e4ad2ba04 | [
"MIT"
] | null | null | null | csc501-lab3/mon/monboot.c | zyczyh/OS-Course-Project-3 | d929b87fc678762cdcda7e4aaf328c8e4ad2ba04 | [
"MIT"
] | 1 | 2021-02-16T22:28:50.000Z | 2021-02-16T22:28:50.000Z | /*
* boot_xinu.c - Bootstrap Xinu from network
*
* Author: John c. Lin
* Dept. of Computer Science
* Purdue University
* Date: Fri Jun 16 15:42:26 1995
*/
#include <./mon/monnetwork.h>
#include <./mon/monitor.h>
#include <stdio.h>
int mon_boot_state;
struct netif *mon_eth_pni = &mon_nif[0]; /* network interface */
int mon_boot_try = 0;
int mon_clktime = 0; /* tick once per sec. for retx purpose */
int mon_timeout = 0; /* when to send a retx; 0: stop retx */
int mon_first_req = 0;
#define VERBOSE
#define PRINTERR
/*-------------------------------------------------------------------------
* boot_xinu() -
*-------------------------------------------------------------------------
*/
int boot_xinu()
{
STATWORD ps;
mon_boot_try = mon_timeout = 0;
mon_boot_state = BEGIN_BOOTP;
while (1) {
switch (mon_boot_state) {
case BOOTP_RETX:
if (++mon_boot_try > MON_MAX_TRY) {
#ifdef PRINTERR
kprintf("Error: No reply to BOOTP request.\n");
#endif
return (SYSERR);
}
/* fall through */
case BEGIN_BOOTP:
mon_boot_state = BOOTP_REQ_SENT;
#ifdef VERBOSE
kprintf("Send BOOTP request....\n");
#endif
if (mon_first_req == 0)
mon_first_req = mon_clktime;
mon_bootp_request(mon_clktime - mon_first_req);
mon_timeout = mon_clktime + mon_boot_try + 2; /* start timer */
break;
case BOOTP_REQ_SENT:
/*
* wait for reply
*/
break;
case TFTP_RETX:
if (++mon_boot_try > MON_MAX_TRY) {
#ifdef PRINTERR
kprintf("Error: No reply to TFTP request.\n");
#endif
return(SYSERR);
}
/* fall through */
case BEGIN_TFTP:
#ifdef VERBOSE
kprintf("Send TFTP request....\n");
#endif
mon_tftp_req();
mon_boot_state = TFTP_REQ_SENT;
mon_timeout = mon_clktime + mon_boot_try + 2; /* start timer */
mon_tftp_block = 1;
mon_tftp_bytes = 0;
mon_tftp_retx = 0;
break;
case TFTP_REQ_SENT:
/*
* wait for transfer to complete
*/
break;
case BOOT_DONE:
/*
* Jump to loaded image
*/
disable(ps);
jumptobootcode();
break;
case BOOT_ERROR:
return(SYSERR);
default:
#ifdef PRINTERR
kprintf("xinuboot: illegal state = %d\n", mon_boot_state);
#endif
break;
}
}
}
| 21.638889 | 75 | 0.572101 |
933c4a701e33451785fccc84f275d276184c3445 | 26,793 | c | C | common/m6502/m6502.c | liberodark/potator | 2873c42f28012992c1132fd083787f5b76b99418 | [
"Unlicense"
] | 2 | 2019-10-01T22:35:53.000Z | 2019-11-05T01:08:25.000Z | common/m6502/m6502.c | liberodark/potator | 2873c42f28012992c1132fd083787f5b76b99418 | [
"Unlicense"
] | 2 | 2021-03-12T22:14:20.000Z | 2021-07-09T08:56:50.000Z | common/m6502/m6502.c | liberodark/potator | 2873c42f28012992c1132fd083787f5b76b99418 | [
"Unlicense"
] | 6 | 2021-03-10T16:49:10.000Z | 2021-10-12T00:21:29.000Z | /** M65C02: portable 65C02 emulator **************************/
/** **/
/** M65C02.c **/
/** **/
/** This file contains implementation for 65C02 CPU. Don't **/
/** forget to provide Rd6502(), Wr6502(), Loop6502(), and **/
/** possibly Op6502() functions to accomodate the emulated **/
/** machine's architecture. **/
/** **/
/** Copyright (C) Marat Fayzullin 1996-2002 **/
/** Alex Krasivsky 1996 **/
/** Steve Nickolas 2002 **/
/** Portions by Holger Picker 2002 **/
/** ADC and SBC instructions provided by Scott Hemphill **/
/** You are not allowed to distribute this software **/
/** commercially. Please, notify me, if you make any **/
/** changes to this file. **/
/*************************************************************/
/* This is M65C02 Version 1.4 of 2002.1220 -uso. */
#include "m6502.h"
#include "tables.h"
#include <stdio.h>
/** INLINE ***************************************************/
/** Different compilers inline C functions differently. **/
/*************************************************************/
/* #define INLINE inline */
/** System-Dependent Stuff ***********************************/
/** This is system-dependent code put here to speed things **/
/** up. It has to stay inlined to be fast. **/
/*************************************************************/
#ifdef INES
#define FAST_RDOP
extern byte *Page[];
INLINE byte Op6502(register word A) { return(Page[A >> 13][A & 0x1FFF]); }
#endif
/** FAST_RDOP ************************************************/
/** With this #define not present, Rd6502() should perform **/
/** the functions of Rd6502(). **/
/*************************************************************/
#ifndef FAST_RDOP
#define Op6502(A) Rd6502(A)
#endif
/* "Izp" added by uso. */
/** Addressing Methods ***************************************/
/** These macros calculate and return effective addresses. **/
/*************************************************************/
#define MC_Ab(Rg) M_LDWORD(Rg)
#define MC_Zp(Rg) Rg.W=Op6502(R->PC.W++)
#define MC_Zx(Rg) Rg.W=(byte)(Op6502(R->PC.W++)+R->X)
#define MC_Zy(Rg) Rg.W=(byte)(Op6502(R->PC.W++)+R->Y)
#define MC_Ax(Rg) M_LDWORD(Rg);Rg.W+=R->X
#define MC_Ay(Rg) M_LDWORD(Rg);Rg.W+=R->Y
#define MC_Ix(Rg) K.W=(byte)(Op6502(R->PC.W++)+R->X); \
Rg.B.l=Op6502(K.W++);Rg.B.h=Op6502(K.W)
#define MC_Iy(Rg) K.W=Op6502(R->PC.W++); \
Rg.B.l=Op6502(K.W++);Rg.B.h=Op6502(K.W); \
Rg.W+=R->Y
#define MC_Izp(Rg) K.W=Op6502(R->PC.W++); \
Rg.B.l=Op6502(K.W++);Rg.B.h=Op6502(K.W);
/** Reading From Memory **************************************/
/** These macros calculate address and read from it. **/
/*************************************************************/
#define MR_Ab(Rg) MC_Ab(J);Rg=Rd6502(J.W)
#define MR_Im(Rg) Rg=Op6502(R->PC.W++)
#define MR_Zp(Rg) MC_Zp(J);Rg=Rd6502(J.W)
#define MR_Zx(Rg) MC_Zx(J);Rg=Rd6502(J.W)
#define MR_Zy(Rg) MC_Zy(J);Rg=Rd6502(J.W)
#define MR_Ax(Rg) MC_Ax(J);Rg=Rd6502(J.W)
#define MR_Ay(Rg) MC_Ay(J);Rg=Rd6502(J.W)
#define MR_Ix(Rg) MC_Ix(J);Rg=Rd6502(J.W)
#define MR_Iy(Rg) MC_Iy(J);Rg=Rd6502(J.W)
#define MR_Izp(Rg) MC_Izp(J);Rg=Rd6502(J.W)
/** Writing To Memory ****************************************/
/** These macros calculate address and write to it. **/
/*************************************************************/
#define MW_Ab(Rg) MC_Ab(J);Wr6502(J.W,Rg)
#define MW_Zp(Rg) MC_Zp(J);Wr6502(J.W,Rg)
#define MW_Zx(Rg) MC_Zx(J);Wr6502(J.W,Rg)
#define MW_Zy(Rg) MC_Zy(J);Wr6502(J.W,Rg)
#define MW_Ax(Rg) MC_Ax(J);Wr6502(J.W,Rg)
#define MW_Ay(Rg) MC_Ay(J);Wr6502(J.W,Rg)
#define MW_Ix(Rg) MC_Ix(J);Wr6502(J.W,Rg)
#define MW_Iy(Rg) MC_Iy(J);Wr6502(J.W,Rg)
#define MW_Izp(Rg) MC_Izp(J);Wr6502(J.W,Rg)
/** Modifying Memory *****************************************/
/** These macros calculate address and modify it. **/
/*************************************************************/
#define MM_Ab(Cmd) MC_Ab(J);I=Rd6502(J.W);Cmd(I);Wr6502(J.W,I)
#define MM_Zp(Cmd) MC_Zp(J);I=Rd6502(J.W);Cmd(I);Wr6502(J.W,I)
#define MM_Zx(Cmd) MC_Zx(J);I=Rd6502(J.W);Cmd(I);Wr6502(J.W,I)
#define MM_Ax(Cmd) MC_Ax(J);I=Rd6502(J.W);Cmd(I);Wr6502(J.W,I)
/** Other Macros *********************************************/
/** Calculating flags, stack, jumps, arithmetics, etc. **/
/*************************************************************/
#define M_FL(Rg) R->P=(R->P&~(Z_FLAG|N_FLAG))|ZNTable[Rg]
#define M_LDWORD(Rg) Rg.B.l=Op6502(R->PC.W++);Rg.B.h=Op6502(R->PC.W++)
#define M_PUSH(Rg) Wr6502(0x0100|R->S,Rg);R->S--
#define M_POP(Rg) R->S++;Rg=Op6502(0x0100|R->S)
#define M_JR R->PC.W+=(offset)Op6502(R->PC.W)+1;R->ICount--
/* Added by uso, fixed by h.p. */
#define M_TSB(Data) R->P = (R->P & ~Z_FLAG) | ((Data & R->A) == 0 ? Z_FLAG : 0); \
Data |= R->A;
#define M_TRB(Data) R->P = (R->P & ~Z_FLAG) | ((Data & R->A) == 0 ? Z_FLAG : 0); \
Data &= ~R->A;
/* The following code was provided by Mr. Scott Hemphill. Thanks a lot! */
#define M_ADC(Rg) \
{ \
register unsigned int w; \
if ((R->A ^ Rg) & 0x80) { \
R->P &= ~V_FLAG; } \
else { \
R->P |= V_FLAG; } \
if (R->P&D_FLAG) { \
w = (R->A & 0xf) + (Rg & 0xf) + (R->P & C_FLAG); \
if (w >= 10) w = 0x10 | ((w+6)&0xf); \
w += (R->A & 0xf0) + (Rg & 0xf0); \
if (w >= 160) { \
R->P |= C_FLAG; \
if ((R->P&V_FLAG) && w >= 0x180) R->P &= ~ V_FLAG; \
w += 0x60; \
} else { \
R->P &= ~C_FLAG; \
if ((R->P&V_FLAG) && w < 0x80) R->P &= ~V_FLAG; \
} \
} else { \
w = R->A + Rg + (R->P&C_FLAG); \
if (w >= 0x100) { \
R->P |= C_FLAG; \
if ((R->P & V_FLAG) && w >= 0x180) R->P &= ~V_FLAG; \
} else { \
R->P &= ~C_FLAG; \
if ((R->P&V_FLAG) && w < 0x80) R->P &= ~V_FLAG; \
} \
} \
R->A = (unsigned char)w; \
R->P = (R->P & ~(Z_FLAG | N_FLAG)) | (R->A >= 0x80 ? N_FLAG : 0) | (R->A == 0 ? Z_FLAG : 0); \
}
#define M_SBC(Rg) SBCInstruction(R, Rg)
#define M_CMP(Rg1,Rg2) \
K.W=Rg1-Rg2; \
R->P&=~(N_FLAG|Z_FLAG|C_FLAG); \
R->P|=ZNTable[K.B.l]|(K.B.h? 0:C_FLAG)
#define M_BIT(Rg) \
R->P&=~(N_FLAG|V_FLAG|Z_FLAG); \
R->P|=(Rg&(N_FLAG|V_FLAG))|(Rg&R->A? 0:Z_FLAG)
#define M_AND(Rg) R->A&=Rg;M_FL(R->A)
#define M_ORA(Rg) R->A|=Rg;M_FL(R->A)
#define M_EOR(Rg) R->A^=Rg;M_FL(R->A)
#define M_INC(Rg) Rg++;M_FL(Rg)
#define M_DEC(Rg) Rg--;M_FL(Rg)
#define M_ASL(Rg) R->P&=~C_FLAG;R->P|=Rg>>7;Rg<<=1;M_FL(Rg)
#define M_LSR(Rg) R->P&=~C_FLAG;R->P|=Rg&C_FLAG;Rg>>=1;M_FL(Rg)
#define M_ROL(Rg) K.B.l=(Rg<<1)|(R->P&C_FLAG); \
R->P&=~C_FLAG;R->P|=Rg>>7;Rg=K.B.l; \
M_FL(Rg)
#define M_ROR(Rg) K.B.l=(Rg>>1)|(R->P<<7); \
R->P&=~C_FLAG;R->P|=Rg&C_FLAG;Rg=K.B.l; \
M_FL(Rg)
/* The following code was provided by Mr. Scott Hemphill. Thanks a lot again! */
static void SBCInstruction(M6502 *R, register unsigned char val) {
register unsigned int w;
register unsigned int temp;
if ((R->A ^ val) & 0x80) {
R->P |= V_FLAG;
}
else {
R->P &= ~V_FLAG;
}
if (R->P&D_FLAG) { /* decimal subtraction */
temp = 0xf + (R->A & 0xf) - (val & 0xf) + (R->P & C_FLAG);
if (temp < 0x10) {
w = 0;
temp -= 6;
}
else {
w = 0x10;
temp -= 0x10;
}
w += 0xf0 + (R->A & 0xf0) - (val & 0xf0);
if (w < 0x100) {
R->P &= ~C_FLAG;
if ((R->P&V_FLAG) && w < 0x80) R->P &= ~V_FLAG;
w -= 0x60;
}
else {
R->P |= C_FLAG;
if ((R->P&V_FLAG) && w >= 0x180) R->P &= ~V_FLAG;
}
w += temp;
}
else { /* standard binary subtraction */
w = 0xff + R->A - val + (R->P&C_FLAG);
if (w < 0x100) {
R->P &= ~C_FLAG;
if ((R->P & V_FLAG) && w < 0x80) R->P &= ~V_FLAG;
}
else {
R->P |= C_FLAG;
if ((R->P&V_FLAG) && w >= 0x180) R->P &= ~V_FLAG;
}
}
R->A = (unsigned char)w;
R->P = (R->P & ~(Z_FLAG | N_FLAG)) | (R->A >= 0x80 ? N_FLAG : 0) | (R->A == 0 ? Z_FLAG : 0);
} /* SBCinstruction */
/** Reset6502() **********************************************/
/** This function can be used to reset the registers before **/
/** starting execution with Run6502(). It sets registers to **/
/** their initial values. **/
/*************************************************************/
void Reset6502(M6502 *R)
{
R->A = R->X = R->Y = 0x00;
R->P = Z_FLAG | R_FLAG;
R->S = 0xFF;
R->PC.B.l = Rd6502(0xFFFC);
R->PC.B.h = Rd6502(0xFFFD);
R->ICount = R->IPeriod;
R->IRequest = INT_NONE;
R->AfterCLI = 0;
}
/** Int6502() ************************************************/
/** This function will generate interrupt of a given type. **/
/** INT_NMI will cause a non-maskable interrupt. INT_IRQ **/
/** will cause a normal interrupt, unless I_FLAG set in R. **/
/*************************************************************/
void Int6502(M6502 *R, byte Type)
{
register pair J;
if ((Type == INT_NMI) || ((Type == INT_IRQ) && !(R->P&I_FLAG)))
{
R->ICount -= 7;
M_PUSH(R->PC.B.h);
M_PUSH(R->PC.B.l);
M_PUSH(R->P&~B_FLAG);
R->P &= ~D_FLAG;
/* if (R->IAutoReset && (Type == R->IRequest)) R->IRequest = INT_NONE; */
if (Type == INT_NMI) J.W = 0xFFFA; else { R->P |= I_FLAG; J.W = 0xFFFE; }
R->PC.B.l = Rd6502(J.W++);
R->PC.B.h = Rd6502(J.W);
}
}
/** Run6502() ************************************************/
/** This function will run 6502 code until Loop6502() call **/
/** returns INT_QUIT. It will return the PC at which **/
/** emulation stopped, and current register values in R. **/
/*************************************************************/
word Run6502(M6502 *R)
{
register pair J, K;
register byte I;
for (;;)
{
I = Op6502(R->PC.W++);
R->ICount -= Cycles[I];
switch (I)
{
/* This is M65C02 Version 1.4 of 2002.1220 -uso. */
case 0x00: /* BRK */
R->PC.W++;
M_PUSH(R->PC.B.h); M_PUSH(R->PC.B.l);
M_PUSH(R->P | B_FLAG);
R->P = (R->P | I_FLAG)&~D_FLAG;
R->PC.B.l = Rd6502(0xFFFE);
R->PC.B.h = Rd6502(0xFFFF); break;
case 0x01: MR_Ix(I); M_ORA(I); break; /* ORA ($ss,x) INDEXINDIR */
case 0x04: MM_Zp(M_TSB); break; /* uso */
case 0x05: MR_Zp(I); M_ORA(I); break; /* ORA $ss ZP */
case 0x06: MM_Zp(M_ASL); break; /* ASL $ss ZP */
case 0x08: M_PUSH(R->P); break; /* PHP */
case 0x09: MR_Im(I); M_ORA(I); break; /* ORA #$ss IMM */
case 0x0A: M_ASL(R->A); break; /* ASL a ACC */
case 0x0C: MM_Ab(M_TSB); break; /* uso */
case 0x0D: MR_Ab(I); M_ORA(I); break; /* ORA $ssss ABS */
case 0x0E: MM_Ab(M_ASL); break; /* ASL $ssss ABS */
case 0x10:
if (R->P&N_FLAG) R->PC.W++;
else { M_JR; } break; /* BPL * REL */
case 0x11: MR_Iy(I); M_ORA(I); break; /* ORA ($ss),y INDIRINDEX */
case 0x12: MR_Izp(I); M_ORA(I); break; /* uso */
case 0x14: MM_Zp(M_TRB); break; /* uso, FixByME */
case 0x15: MR_Zx(I); M_ORA(I); break; /* ORA $ss,x ZP,x */
case 0x16: MM_Zx(M_ASL); break; /* ASL $ss,x ZP,x */
case 0x18: R->P &= ~C_FLAG; break; /* CLC */
case 0x19: MR_Ay(I); M_ORA(I); break; /* ORA $ssss,y ABS,y */
case 0x1A: M_INC(R->A); break; /* uso */
case 0x1C: MM_Ab(M_TRB); break; /* uso, FixByME */
case 0x1D: MR_Ax(I); M_ORA(I); break; /* ORA $ssss,x ABS,x */
case 0x1E: MM_Ax(M_ASL); break; /* ASL $ssss,x ABS,x */
case 0x20:
K.B.l = Op6502(R->PC.W++);
K.B.h = Op6502(R->PC.W);
M_PUSH(R->PC.B.h);
M_PUSH(R->PC.B.l);
R->PC = K; break;
case 0x21: MR_Ix(I); M_AND(I); break; /* AND ($ss,x) INDEXINDIR */
case 0x24: MR_Zp(I); M_BIT(I); break; /* BIT $ss ZP */
case 0x25: MR_Zp(I); M_AND(I); break; /* AND $ss ZP */
case 0x26: MM_Zp(M_ROL); break; /* ROL $ss ZP */
case 0x28:
M_POP(I);
if ((R->IRequest != INT_NONE) && ((I^R->P)&~I&I_FLAG))
{
R->AfterCLI = 1;
R->IBackup = R->ICount;
R->ICount = 1;
}
R->P = I | R_FLAG | B_FLAG; break; /* B_FLAG added from new M6502 */
case 0x29: MR_Im(I); M_AND(I); break; /* AND #$ss IMM */
case 0x2A: M_ROL(R->A); break; /* ROL a ACC */
case 0x2C: MR_Ab(I); M_BIT(I); break; /* BIT $ssss ABS */
case 0x2D: MR_Ab(I); M_AND(I); break; /* AND $ssss ABS */
case 0x2E: MM_Ab(M_ROL); break; /* ROL $ssss ABS */
case 0x30:
if (R->P&N_FLAG) { M_JR; }
else R->PC.W++; break; /* BMI * REL */
case 0x31: MR_Iy(I); M_AND(I); break; /* AND ($ss),y INDIRINDEX */
case 0x32: MR_Izp(I); M_AND(I); break; /* uso */
case 0x34: MR_Zx(I); M_BIT(I); break; /* uso */
case 0x35: MR_Zx(I); M_AND(I); break; /* AND $ss,x ZP,x */
case 0x36: MM_Zx(M_ROL); break; /* ROL $ss,x ZP,x */
case 0x38: R->P |= C_FLAG; break; /* SEC */
case 0x39: MR_Ay(I); M_AND(I); break; /* AND $ssss,y ABS,y */
case 0x3A: M_DEC(R->A); break; /* uso */
case 0x3C: MR_Ax(I); M_BIT(I); break; /* uso */
case 0x3D: MR_Ax(I); M_AND(I); break; /* AND $ssss,x ABS,x */
case 0x3E: MM_Ax(M_ROL); break; /* ROL $ssss,x ABS,x */
case 0x40:
M_POP(R->P); R->P |= R_FLAG; M_POP(R->PC.B.l); M_POP(R->PC.B.h); break;
case 0x41: MR_Ix(I); M_EOR(I); break; /* EOR ($ss,x) INDEXINDIR */
case 0x45: MR_Zp(I); M_EOR(I); break; /* EOR $ss ZP */
case 0x46: MM_Zp(M_LSR); break; /* LSR $ss ZP */
case 0x48: M_PUSH(R->A); break; /* PHA */
case 0x49: MR_Im(I); M_EOR(I); break; /* EOR #$ss IMM */
case 0x4A: M_LSR(R->A); break; /* LSR a ACC */
case 0x4C: M_LDWORD(K); R->PC = K; break;
case 0x4D: MR_Ab(I); M_EOR(I); break; /* EOR $ssss ABS */
case 0x4E: MM_Ab(M_LSR); break; /* LSR $ssss ABS */
case 0x50: if (R->P&V_FLAG) R->PC.W++; else { M_JR; } break; /* BVC * REL */
case 0x51: MR_Iy(I); M_EOR(I); break; /* EOR ($ss),y INDIRINDEX */
case 0x52: MR_Izp(I); M_EOR(I); break; /* uso */
case 0x55: MR_Zx(I); M_EOR(I); break; /* EOR $ss,x ZP,x */
case 0x56: MM_Zx(M_LSR); break; /* LSR $ss,x ZP,x */
case 0x58: if ((R->IRequest != INT_NONE) && (R->P&I_FLAG))
{
R->AfterCLI = 1; R->IBackup = R->ICount; R->ICount = 1;
}
R->P &= ~I_FLAG; break;
case 0x59: MR_Ay(I); M_EOR(I); break; /* EOR $ssss,y ABS,y */
case 0x5A: M_PUSH(R->Y); break; /* uso */
case 0x5D: MR_Ax(I); M_EOR(I); break; /* EOR $ssss,x ABS,x */
case 0x5E: MM_Ax(M_LSR); break; /* LSR $ssss,x ABS,x */
case 0x60: M_POP(R->PC.B.l); M_POP(R->PC.B.h); R->PC.W++; break;
case 0x61: MR_Ix(I); M_ADC(I); break; /* ADC ($ss,x) INDEXINDIR */
case 0x64: MW_Zp(0); break; /* uso */
case 0x65: MR_Zp(I); M_ADC(I); break; /* ADC $ss ZP */
case 0x66: MM_Zp(M_ROR); break; /* ROR $ss ZP */
case 0x68: M_POP(R->A); M_FL(R->A); break; /* PLA */
case 0x69: MR_Im(I); M_ADC(I); break; /* ADC #$ss IMM */
case 0x6A: M_ROR(R->A); break; /* ROR a ACC */
case 0x6C: /* from newer M6502 */
M_LDWORD(K);
R->PC.B.l = Rd6502(K.W);
K.B.l++;
R->PC.B.h = Rd6502(K.W); break;
case 0x6D: MR_Ab(I); M_ADC(I); break; /* ADC $ssss ABS */
case 0x6E: MM_Ab(M_ROR); break; /* ROR $ssss ABS */
case 0x70: if (R->P&V_FLAG) { M_JR; }
else R->PC.W++; break; /* BVS * REL */
case 0x71: MR_Iy(I); M_ADC(I); break; /* ADC ($ss),y INDIRINDEX */
case 0x72: MR_Izp(I); M_ADC(I); break; /* uso */
case 0x74: MW_Zx(0); break; /* uso */
case 0x75: MR_Zx(I); M_ADC(I); break; /* ADC $ss,x ZP,x */
case 0x76: MM_Zx(M_ROR); break; /* ROR $ss,x ZP,x */
case 0x78: R->P |= I_FLAG; break; /* SEI */
case 0x79: MR_Ay(I); M_ADC(I); break; /* ADC $ssss,y ABS,y */
case 0x7A: M_POP(R->Y); M_FL(R->Y); break; /* uso */
case 0x7C: M_LDWORD(K); R->PC.B.l = Rd6502(K.W++); R->PC.B.h = Rd6502(K.W); R->PC.W += R->X; break; /* uso */
case 0x7D: MR_Ax(I); M_ADC(I); break; /* ADC $ssss,x ABS,x */
case 0x7E: MM_Ax(M_ROR); break; /* ROR $ssss,x ABS,x */
case 0x80: M_JR; break; /* uso */
case 0x81: MW_Ix(R->A); break; /* STA ($ss,x) INDEXINDIR */
case 0x84: MW_Zp(R->Y); break; /* STY $ss ZP */
case 0x85: MW_Zp(R->A); break; /* STA $ss ZP */
case 0x86: MW_Zp(R->X); break; /* STX $ss ZP */
case 0x88: R->Y--; M_FL(R->Y); break; /* DEY */
case 0x89: MR_Im(I); M_BIT(I); break; /* uso */
case 0x8A: R->A = R->X; M_FL(R->A); break; /* TXA */
case 0x8C: MW_Ab(R->Y); break; /* STY $ssss ABS */
case 0x8D: MW_Ab(R->A); break; /* STA $ssss ABS */
case 0x8E: MW_Ab(R->X); break; /* STX $ssss ABS */
case 0x90: if (R->P&C_FLAG) R->PC.W++; else { M_JR; } break; /* BCC * REL */
case 0x91: MW_Iy(R->A); break; /* STA ($ss),y INDIRINDEX */
case 0x92: MW_Izp(R->A); break; /* uso */
case 0x94: MW_Zx(R->Y); break; /* STY $ss,x ZP,x */
case 0x95: MW_Zx(R->A); break; /* STA $ss,x ZP,x */
case 0x96: MW_Zy(R->X); break; /* STX $ss,y ZP,y */
case 0x98: R->A = R->Y; M_FL(R->A); break; /* TYA */
case 0x99: MW_Ay(R->A); break; /* STA $ssss,y ABS,y */
case 0x9A: R->S = R->X; break; /* TXS */
case 0x9C: MW_Ab(0); break; /* uso */
case 0x9D: MW_Ax(R->A); break; /* STA $ssss,x ABS,x */
case 0x9E: MW_Ax(0); break; /* uso */
case 0xA0: MR_Im(R->Y); M_FL(R->Y); break; /* LDY #$ss IMM */
case 0xA1: MR_Ix(R->A); M_FL(R->A); break; /* LDA ($ss,x) INDEXINDIR */
case 0xA2: MR_Im(R->X); M_FL(R->X); break; /* LDX #$ss IMM */
case 0xA4: MR_Zp(R->Y); M_FL(R->Y); break; /* LDY $ss ZP */
case 0xA5: MR_Zp(R->A); M_FL(R->A); break; /* LDA $ss ZP */
case 0xA6: MR_Zp(R->X); M_FL(R->X); break; /* LDX $ss ZP */
case 0xA8: R->Y = R->A; M_FL(R->Y); break; /* TAY */
case 0xA9: MR_Im(R->A); M_FL(R->A); break; /* LDA #$ss IMM */
case 0xAA: R->X = R->A; M_FL(R->X); break; /* TAX */
case 0xAC: MR_Ab(R->Y); M_FL(R->Y); break; /* LDY $ssss ABS */
case 0xAD: MR_Ab(R->A); M_FL(R->A); break; /* LDA $ssss ABS */
case 0xAE: MR_Ab(R->X); M_FL(R->X); break; /* LDX $ssss ABS */
case 0xB0: if (R->P&C_FLAG) { M_JR; }
else R->PC.W++; break; /* BCS * REL */
case 0xB1: MR_Iy(R->A); M_FL(R->A); break; /* LDA ($ss),y INDIRINDEX */
case 0xB2: MR_Izp(R->A); M_FL(R->A); break; /* uso */
case 0xB4: MR_Zx(R->Y); M_FL(R->Y); break; /* LDY $ss,x ZP,x */
case 0xB5: MR_Zx(R->A); M_FL(R->A); break; /* LDA $ss,x ZP,x */
case 0xB6: MR_Zy(R->X); M_FL(R->X); break; /* LDX $ss,y ZP,y */
case 0xB8: R->P &= ~V_FLAG; break; /* CLV */
case 0xB9: MR_Ay(R->A); M_FL(R->A); break; /* LDA $ssss,y ABS,y */
case 0xBA: R->X = R->S; M_FL(R->X); break; /* TSX */
case 0xBC: MR_Ax(R->Y); M_FL(R->Y); break; /* LDY $ssss,x ABS,x */
case 0xBD: MR_Ax(R->A); M_FL(R->A); break; /* LDA $ssss,x ABS,x */
case 0xBE: MR_Ay(R->X); M_FL(R->X); break; /* LDX $ssss,y ABS,y */
case 0xC0: MR_Im(I); M_CMP(R->Y, I); break; /* CPY #$ss IMM */
case 0xC1: MR_Ix(I); M_CMP(R->A, I); break; /* CMP ($ss,x) INDEXINDIR */
case 0xC4: MR_Zp(I); M_CMP(R->Y, I); break; /* CPY $ss ZP */
case 0xC5: MR_Zp(I); M_CMP(R->A, I); break; /* CMP $ss ZP */
case 0xC6: MM_Zp(M_DEC); break; /* DEC $ss ZP */
case 0xC8: R->Y++; M_FL(R->Y); break; /* INY */
case 0xC9: MR_Im(I); M_CMP(R->A, I); break; /* CMP #$ss IMM */
case 0xCA: R->X--; M_FL(R->X); break; /* DEX */
case 0xCC: MR_Ab(I); M_CMP(R->Y, I); break; /* CPY $ssss ABS */
case 0xCD: MR_Ab(I); M_CMP(R->A, I); break; /* CMP $ssss ABS */
case 0xCE: MM_Ab(M_DEC); break; /* DEC $ssss ABS */
case 0xD0: if (R->P&Z_FLAG) R->PC.W++; else { M_JR; } break; /* BNE * REL */
case 0xD1: MR_Iy(I); M_CMP(R->A, I); break; /* CMP ($ss),y INDIRINDEX */
case 0xD2: MR_Izp(I); M_CMP(R->A, I); break; /* uso */
case 0xD5: MR_Zx(I); M_CMP(R->A, I); break; /* CMP $ss,x ZP,x */
case 0xD6: MM_Zx(M_DEC); break; /* DEC $ss,x ZP,x */
case 0xD8: R->P &= ~D_FLAG; break; /* CLD */
case 0xD9: MR_Ay(I); M_CMP(R->A, I); break; /* CMP $ssss,y ABS,y */
case 0xDA: M_PUSH(R->X); break; /* uso */
case 0xDD: MR_Ax(I); M_CMP(R->A, I); break; /* CMP $ssss,x ABS,x */
case 0xDE: MM_Ax(M_DEC); break; /* DEC $ssss,x ABS,x */
case 0xE0: MR_Im(I); M_CMP(R->X, I); break; /* CPX #$ss IMM */
case 0xE1: MR_Ix(I); M_SBC(I); break; /* SBC ($ss,x) INDEXINDIR */
case 0xE4: MR_Zp(I); M_CMP(R->X, I); break; /* CPX $ss ZP */
case 0xE5: MR_Zp(I); M_SBC(I); break; /* SBC $ss ZP */
case 0xE6: MM_Zp(M_INC); break; /* INC $ss ZP */
case 0xE8: R->X++; M_FL(R->X); break; /* INX */
case 0xE9: MR_Im(I); M_SBC(I); break; /* SBC #$ss IMM */
case 0xEA: break; /* NOP */
case 0xEC: MR_Ab(I); M_CMP(R->X, I); break; /* CPX $ssss ABS */
case 0xED: MR_Ab(I); M_SBC(I); break; /* SBC $ssss ABS */
case 0xEE: MM_Ab(M_INC); break; /* INC $ssss ABS */
case 0xF0: if (R->P&Z_FLAG) { M_JR; }
else R->PC.W++; break; /* BEQ * REL */
case 0xF1: MR_Iy(I); M_SBC(I); break; /* SBC ($ss),y INDIRINDEX */
case 0xF2: MR_Izp(I); M_SBC(I); break; /* uso */
case 0xF5: MR_Zx(I); M_SBC(I); break; /* SBC $ss,x ZP,x */
case 0xF6: MM_Zx(M_INC); break; /* INC $ss,x ZP,x */
case 0xF8: R->P |= D_FLAG; break; /* SED */
case 0xF9: MR_Ay(I); M_SBC(I); break; /* SBC $ssss,y ABS,y */
case 0xFA: M_POP(R->X); M_FL(R->X); break; /* uso */
case 0xFD: MR_Ax(I); M_SBC(I); break; /* SBC $ssss,x ABS,x */
case 0xFE: MM_Ax(M_INC); break; /* INC $ssss,x ABS,x */
default:
#ifdef DEBUG
printf("[M65C02] Unrecognized instruction: $%02X at PC=$%04X\n",
Op6502(R->PC.W - 1), (word)(R->PC.W - 1));
#endif
break;
}
/* If cycle counter expired... */
if (R->ICount <= 0)
{
/* If we have come after CLI, get INT_? from IRequest */
/* Otherwise, get it from the loop handler */
if (R->AfterCLI)
{
I = R->IRequest; /* Get pending interrupt */
R->ICount += R->IBackup - 1; /* Restore the ICount */
R->AfterCLI = 0; /* Done with AfterCLI state */
}
else
{
I = Loop6502(R); /* Call the periodic handler */
R->ICount = R->IPeriod; /* Reset the cycle counter */
/* if (!I) I = R->IRequest; */ /* Realize pending interrupt */
}
if (I == INT_QUIT) return(R->PC.W); /* Exit if INT_QUIT */
if (I) Int6502(R, I); /* Interrupt if needed */
}
}
/* Execution stopped */
return(R->PC.W);
}
| 48.892336 | 117 | 0.42261 |
933c6e3f91c0e365ac6edde7138ab3836b04abb7 | 637 | h | C | Map.h | Cyclohexanol/QSurvival | 80a47acec618f73c6d1147cc5f8e148193806a3e | [
"MIT"
] | null | null | null | Map.h | Cyclohexanol/QSurvival | 80a47acec618f73c6d1147cc5f8e148193806a3e | [
"MIT"
] | null | null | null | Map.h | Cyclohexanol/QSurvival | 80a47acec618f73c6d1147cc5f8e148193806a3e | [
"MIT"
] | null | null | null | #ifndef __MAP_H__
#define __MAP_H__
#include <vector> // Using vector to be able to resize the array according to the input.
enum Areas // Using enum to pre define the data type.
{
Land=1,
Water=2,
Food=3,
OutOfArea=-1
};
// Creating the class for the Grid/Map.
class Map
{
private:
std::vector<Areas> grid; // Applying the vector
int row;
int col;
void addArea(int x, int y, Areas v, int offset_x=0, int offset_y=0); // Using offsets to limit the premacies
void setCell(int x, int y, Areas a);
public:
Map();
void print();
Areas getCell(int x, int y);
int getCol();
int getRow();
};
#endif
| 15.925 | 110 | 0.659341 |
9340bfb05759b0acac6c90942e02418ca98c0293 | 1,688 | h | C | BreaksPPU/PPUSim/hv_decoder.h | ogamespec/breaknes | b053afb6924ca661f71a129766e8945f64f6ec7b | [
"CC0-1.0"
] | 2 | 2022-03-10T16:56:33.000Z | 2022-03-20T13:28:20.000Z | BreaksPPU/PPUSim/hv_decoder.h | ogamespec/breaknes | b053afb6924ca661f71a129766e8945f64f6ec7b | [
"CC0-1.0"
] | null | null | null | BreaksPPU/PPUSim/hv_decoder.h | ogamespec/breaknes | b053afb6924ca661f71a129766e8945f64f6ec7b | [
"CC0-1.0"
] | 1 | 2022-03-10T12:06:25.000Z | 2022-03-10T12:06:25.000Z | // H/V Decoder
#pragma once
namespace PPUSim
{
union HDecoderInput
{
struct
{
unsigned H8 : 1; // input 0
unsigned n_H8 : 1;
unsigned H7 : 1;
unsigned n_H7 : 1;
unsigned H6 : 1;
unsigned n_H6 : 1;
unsigned H5 : 1;
unsigned n_H5 : 1;
unsigned H4 : 1;
unsigned n_H4 : 1;
unsigned H3 : 1;
unsigned n_H3 : 1;
unsigned H2 : 1;
unsigned n_H2 : 1;
unsigned H1 : 1;
unsigned n_H1 : 1;
unsigned H0 : 1;
unsigned n_H0 : 1;
unsigned VB : 1;
unsigned BLNK : 1; // input Max
};
size_t packed_bits;
};
union VDecoderInput
{
struct
{
unsigned V8 : 1; // input 0
unsigned n_V8 : 1;
unsigned V7 : 1;
unsigned n_V7 : 1;
unsigned V6 : 1;
unsigned n_V6 : 1;
unsigned V5 : 1;
unsigned n_V5 : 1;
unsigned V4 : 1;
unsigned n_V4 : 1;
unsigned V3 : 1;
unsigned n_V3 : 1;
unsigned V2 : 1;
unsigned n_V2 : 1;
unsigned V1 : 1;
unsigned n_V1 : 1;
unsigned V0 : 1;
unsigned n_V0 : 1; // input Max
};
size_t packed_bits;
};
class HVDecoder
{
PPU* ppu = nullptr;
// The number of inputs is fixed in all known PPU revisions studied.
const size_t hpla_inputs = 20;
const size_t vpla_inputs = 18;
// The number of HPLA outputs is fixed, and the VPLA outputs differ slightly between NTSC-like and PAL-like PPU revisions.
const size_t hpla_outputs = 24;
size_t vpla_outputs = 0;
BaseLogic::PLA* hpla = nullptr;
BaseLogic::PLA* vpla = nullptr;
public:
HVDecoder(PPU* parent);
~HVDecoder();
void sim_HDecoder(BaseLogic::TriState VB, BaseLogic::TriState BLNK, BaseLogic::TriState** outputs);
void sim_VDecoder(BaseLogic::TriState** outputs);
};
}
| 19.627907 | 124 | 0.632701 |
9341e55d18611f8adf6c3980f1ab53ca18331b62 | 3,475 | h | C | Classes/data/Building.h | thales-vogso/deer | f3492538881f632b55be657bb9529027897b0e63 | [
"Apache-2.0"
] | null | null | null | Classes/data/Building.h | thales-vogso/deer | f3492538881f632b55be657bb9529027897b0e63 | [
"Apache-2.0"
] | null | null | null | Classes/data/Building.h | thales-vogso/deer | f3492538881f632b55be657bb9529027897b0e63 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* @desc 建筑物数据
* @date 2015-1-7
* @author 110101
* @file data/Item.h
******************************************************************************/
#ifndef __DATA_BUILDING_H__
#define __DATA_BUILDING_H__
#include "cocos2d.h"
#include "data/Item.h"
namespace data {
class Building : public custom::Event,custom::Memories {
public:
enum WORKER_ID
{
PLANT_WORKERID = 110101,
FOOD_WORKERID = 110102
};
/**
* 初始化
*/
Building();
/**
* 析构函数,要清除有指针的内容
*/
virtual ~Building();
/**
* 获取实体
*/
static Building* getInstance();
static void destroyInstance();
/**
* 初始化
*/
void init();
/**
* 根据建筑物bid获取建筑物
* @return 建筑物信息
*/
cocos2d::Value getBuildingByBID(int bid);
/**
* 根据建筑物bid获取建造
* @return 建造信息
*/
cocos2d::Value getBuildByBID(int bid);
/**
* 获取用户建造列表
* @return 用户建造列表
*/
cocos2d::Value getUserBuildList();
/**
* 添加用户制造
* @param bid 建造的建筑物
*/
void addUserBuild(int bid);
/**
* 解锁工人
* @param wid 工人id
*/
void addUserWorker(int wid);
/**
* 建造
* @param bid 建造的建筑物
*/
cocos2d::Value build(int bid);
/**
* 通过bid获取用户建筑物
* @param bid 建造的建筑物
* @return 用户建筑物
*/
cocos2d::Value getUserBuildByBID(int bid);
/**
* 通过bid获取用户建筑物数量
* @param bid 建筑物id
* @return 建筑物数量
*/
int getUserBuildAmountByBID(int bid);
/**
* 通过wid获取用户工人数量
* @param wid 工人id
* @return 工人数量
*/
int getUserWorkerAmountByWID(int wid);
/**
* 通过bid获取工人
*/
cocos2d::Value getWorkersByBID(int bid);
/**
* 获取工人总数
*/
int getWorkTotal();
/**
* 获取空闲工人数
*/
int getWorkFree();
/**
* 增加工人
* @param wid 工人id
* @amount amount 数量
* @return 结果,比如没有足够的工人
*/
bool workerPlus(int wid, int amount = 1);
/**
* 减少工人
* @param wid 工人id
* @amount amount 数量
* @return 结果,比如工人为0
*/
bool workerReduce(int wid, int amount = 1);
/**
* 获取收获列表
*/
cocos2d::Value getUserGainList();
/**
* 根据wid获取工人生产
*/
cocos2d::Value getWorkerGainByWID(int wid);
/**
* 获取用户收益
*/
cocos2d::Value getUserGain();
/**
* 采集
*/
cocos2d::Value gather();
/**
* 收获
*/
cocos2d::Value gain();
/**
* 获取收益间隔
*/
int getGainInterval();
/**
* 收获回调
* 回调的字符串
*/
void gainCallback(std::string str);
/**
* 工人人数建筑物
*/
enum BuildingID
{
SUPPORT_MIN = 110101,
SUPPORT_MAX = 110138,
ASSEMBLY = 111501
};
const int SUPPORT_TOTAL = 38;
/**
* 建造
*/
static const std::string BUILD;
/**
* 工人改变
*/
static const std::string WORKER_CHANGE;
/**
* 收集事件
*/
static const std::string EVENT_GATHER;
/**
* 自动收获
*/
static const std::string GAIN;
private:
/**
* 自身
*/
static Building* _instance;
/**
* 数据库
*/
DBSqlite* _db;
/**
* 用户uid
*/
int _uid;
/**
* 定时器
*/
cocos2d::Scheduler _scheduler;
/**
* 用户建筑物
* @param bid 建造的建筑物
*/
void userBuildPlus(int bid);
/**
* 一个工人建筑物可以承载的工人数
*/
int WORKER_BUILDING_UNIT = 5;
/**
* 建筑物
*/
std::string TABLE_BUILDING = "building";
/**
* 建造
*/
std::string TABLE_BUILD = "build";
/**
* 工人
*/
std::string TABLE_WORKER = "worker";
/**
* 工人收益
*/
std::string TABLE_WORKER_GAIN = "worker_gain";
/**
* 用户建造
*/
std::string TABLE_USER_BUILD = "user_build";
/**
* 用户工人
*/
std::string TABLE_USER_WORKER = "user_worker";
/**
* 用户收益
*/
std::string TABLE_USER_GAIN = "user_gain";
};
}
#endif // __DATA_BUILDING_H__ | 15.04329 | 79 | 0.557986 |
93423f0016c68cef2eaa04d6fcd60c2a25b93aad | 770 | h | C | include/shan/thread/spinlock.h | shanpark/Shan.Lib | a57de39a026788ddf67e5c2dbb4cae2f3ec62396 | [
"BSD-2-Clause"
] | 1 | 2017-05-05T03:05:18.000Z | 2017-05-05T03:05:18.000Z | include/shan/thread/spinlock.h | shanpark/Shan.Lib | a57de39a026788ddf67e5c2dbb4cae2f3ec62396 | [
"BSD-2-Clause"
] | null | null | null | include/shan/thread/spinlock.h | shanpark/Shan.Lib | a57de39a026788ddf67e5c2dbb4cae2f3ec62396 | [
"BSD-2-Clause"
] | null | null | null | //
// spinlock.h
// Shan.Thread
//
// Created by Sung Han Park on 2017. 5. 13..
// Copyright © 2017 Sung Han Park. All rights reserved.
//
#ifndef shan_thread_spinlock_h
#define shan_thread_spinlock_h
#include <shan/object.h>
namespace shan {
namespace thread {
/**
기대되는 평균 waiting 시간이 thread context switching 시간보다 짧을 때만 이용한다.
무한 대기 상태가 있을 수 있는데 spinlock을 이용하면 대기하는 thread는 대기하는 동안 CPU core를
full로 사용하게 된다.
*/
class spinlock : public object {
public:
spinlock() : _l(false) {}
void lock() noexcept {
while (_l.test_and_set(std::memory_order_acquire))
; // spin
}
void unlock() noexcept {
_l.clear(std::memory_order_release);
}
private:
std::atomic_flag _l;
};
} // namespace thread
} // namespace shan
#endif /* shan_thread_spinlock_h */
| 17.906977 | 66 | 0.697403 |
9343aa935332e9495517af6b096a449f79fc0730 | 2,728 | h | C | cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 58 | 2015-01-05T04:40:48.000Z | 2021-12-17T06:01:28.000Z | cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | null | null | null | cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h | centrallydecentralized/ufo | 29e8f9ce4ce92635ed22f8a051c917cfe6e0313d | [
"BSD-3-Clause"
] | 46 | 2015-01-03T06:20:54.000Z | 2020-04-18T13:32:52.000Z | /*
*
*/
#ifndef __PERFORMANCE_ALLOC_TEST_H__
#define __PERFORMANCE_ALLOC_TEST_H__
#include <string>
#include "PerformanceTest.h"
#include "support/CCProfiling.h"
class AllocBasicLayer : public PerformBasicLayer
{
public:
AllocBasicLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0);
virtual void showCurrentTest();
};
class PerformceAllocScene : public CCScene
{
public:
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual std::string title();
virtual std::string subtitle();
virtual void updateQuantityOfNodes() = 0;
const char* profilerName();
void updateProfilerName();
void onDecrease(CCObject* pSender);
void onIncrease(CCObject* pSender);
// for the profiler
virtual const char* testName() = 0;
void updateQuantityLabel();
int getQuantityOfNodes() { return quantityOfNodes; }
void dumpProfilerInfo(float dt);
// overrides
virtual void onExitTransitionDidStart();
virtual void onEnterTransitionDidFinish();
protected:
char _profilerName[256];
int lastRenderedCount;
int quantityOfNodes;
int currentQuantityOfNodes;
};
class NodeCreateTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class NodeDeallocTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class SpriteCreateEmptyTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class SpriteCreateTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
class SpriteDeallocTest : public PerformceAllocScene
{
public:
virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(float dt);
virtual const char* testName();
std::string title();
std::string subtitle();
};
void runAllocPerformanceTest();
#endif // __PERFORMANCE_ALLOC_TEST_H__
| 22.92437 | 83 | 0.725073 |
9344f96dfa523af0d29261503c822dd556aa257e | 448 | h | C | SemoCore/com.innerfunction.semo/IFConfigurable.h | innerfunction/semo-core-ios | f392fc8fde3e93db1bd69e80e93e7ed93df9278b | [
"Apache-2.0"
] | null | null | null | SemoCore/com.innerfunction.semo/IFConfigurable.h | innerfunction/semo-core-ios | f392fc8fde3e93db1bd69e80e93e7ed93df9278b | [
"Apache-2.0"
] | null | null | null | SemoCore/com.innerfunction.semo/IFConfigurable.h | innerfunction/semo-core-ios | f392fc8fde3e93db1bd69e80e93e7ed93df9278b | [
"Apache-2.0"
] | null | null | null | //
// IFConfigurable.h
// SemoCore
//
// Created by Julian Goacher on 22/04/2015.
// Copyright (c) 2015 InnerFunction. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "IFConfiguration.h"
/**
* Protocol for objects which wish to control their own configuration.
*/
@protocol IFConfigurable <NSObject>
/** Configure the object using the specified configuration. */
- (void)configure:(IFConfiguration *)configuration;
@end
| 21.333333 | 70 | 0.729911 |
93459237130a2fec577be40ecd1301e5f047fae8 | 2,774 | h | C | PrivateFrameworks/VectorKit.framework/VKSceneConfiguration.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | PrivateFrameworks/VectorKit.framework/VKSceneConfiguration.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | PrivateFrameworks/VectorKit.framework/VKSceneConfiguration.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/VectorKit.framework/VectorKit
*/
@interface VKSceneConfiguration : NSObject {
unsigned char _cameraMode;
unsigned long long _currentGroupedManeuverCount;
unsigned char _currentIncidentType;
unsigned char _currentManeuverComplexity;
unsigned char _currentManueverType;
unsigned char _currentStepLength;
struct ManeveuverDistancesRange {
double _immediate;
double _extremlyNear;
double _veryNear;
double _near;
double _medium;
double _far;
double _veryFar;
} _distanceRanges;
unsigned char _distanceToCurrentManeuver;
unsigned int _lineType;
unsigned char _navState;
int _nextManeuverRampType;
unsigned char _nextStepLength;
struct vector<GEOLocationCoordinate2D, std::__1::allocator<GEOLocationCoordinate2D> > {
struct { /* ? */ } *__begin_;
struct { /* ? */ } *__end_;
struct __compressed_pair<GEOLocationCoordinate2D *, std::__1::allocator<GEOLocationCoordinate2D> > {
struct { /* ? */ } *__first_;
} __end_cap_;
} _pointsOfInterest;
int _rampType;
unsigned char _roadSpeed;
struct shared_ptr<gss::StylesheetManager<gss::ScenePropertyID> > {
struct StylesheetManager<gss::ScenePropertyID> {} *__ptr_;
struct __shared_weak_count {} *__cntrl_;
} _sceneManager;
unsigned char _searchAlongTheRoute;
unsigned char _transportType;
unsigned char _vehicleSpeed;
}
- (id).cxx_construct;
- (void).cxx_destruct;
- (id)init;
- (unsigned char)navigationState;
- (void)setCurrentGroupedManeuverCount:(unsigned long long)arg1;
- (void)setCurrentIncidentType:(unsigned long long)arg1;
- (void)setCurrentManeuverJunctionsCount:(unsigned long long)arg1;
- (void)setCurrentManeuverType:(int)arg1;
- (void)setCurrentStepLength:(double)arg1;
- (void)setCurrentTransportationType:(int)arg1;
- (void)setDistanceToCurrentManeuver:(double)arg1;
- (void)setLineType:(unsigned int)arg1;
- (void)setNavCameraMode:(unsigned long long)arg1;
- (void)setNavigationState:(int)arg1;
- (void)setNextManeuverRampType:(int)arg1;
- (void)setNextStepLength:(double)arg1;
- (void)setRampType:(int)arg1;
- (void)setRoadSpeed:(double)arg1;
- (void)setSceneManager:(struct shared_ptr<gss::StylesheetManager<gss::ScenePropertyID> > { struct StylesheetManager<gss::ScenePropertyID> {} *x1; struct __shared_weak_count {} *x2; })arg1;
- (void)setSearchAlongTheRoute:(bool)arg1;
- (void)setStyleManager:(struct shared_ptr<gss::StylesheetManager<gss::PropertyID> > { struct StylesheetManager<gss::PropertyID> {} *x1; struct __shared_weak_count {} *x2; })arg1;
- (void)setVehicleSpeed:(double)arg1;
@end
| 40.794118 | 189 | 0.726027 |
9345f9380e1ce25b9754eb703608bbe2d12fd542 | 8,196 | h | C | examples/ios-material-ui/app/iOSStoryBookDemo/Pods/MotionAnimator/src/MDMAnimatableKeyPaths.h | hborawski/native | bef9d410d39aa945b328b588a8f624b94780009c | [
"MIT"
] | 102 | 2020-09-03T09:57:51.000Z | 2022-03-31T10:15:07.000Z | examples/ios-material-ui/app/iOSStoryBookDemo/Pods/MotionAnimator/src/MDMAnimatableKeyPaths.h | hborawski/native | bef9d410d39aa945b328b588a8f624b94780009c | [
"MIT"
] | 68 | 2020-10-30T22:39:36.000Z | 2022-03-25T22:53:45.000Z | iosApp/Pods/MotionAnimator/src/MDMAnimatableKeyPaths.h | archiegq21/DroidconKotlin | 8c3ec05448d586037c924f245f77fcd0150f0476 | [
"Apache-2.0"
] | 47 | 2017-09-17T11:16:49.000Z | 2021-08-09T06:15:40.000Z | /*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Availability.h>
#import <Foundation/Foundation.h>
// This macro is introduced in Xcode 9.
#ifndef CF_TYPED_ENUM // What follows is backwards compat for Xcode 8 and below.
#if __has_attribute(swift_wrapper)
#define CF_TYPED_ENUM __attribute__((swift_wrapper(enum)))
#else
#define CF_TYPED_ENUM
#endif
#endif
/**
A representation of an animatable key path.
This is NOT an exhaustive list of animatable properties; it only documents properties that are
officially supported by the animator. If you animate unsupported properties then the resulting
behavior is undefined.
Each property documents whether or not it supports being animated additively. This affects the
behavior of animations when a MDMMotionAnimator's additive property is enabled. Properties that
support additive animations can change direction mid-way through the animation while appearing
to preserve momentum. Properties that do not support additive animation will instantly start
animating towards the new toValue.
*/
NS_SWIFT_NAME(AnimatableKeyPath)
typedef NSString * const MDMAnimatableKeyPath CF_TYPED_ENUM;
/**
Anchor point.
Equivalent UIView property: N/A
Equivalent CALayer property: anchorPoint
Expected value type: CGPoint or NSValue (containing a CGPoint).
Additive animation supported: No.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathAnchorPoint NS_SWIFT_NAME(anchorPoint);
/**
Background color.
Equivalent UIView property: backgroundColor
Equivalent CALayer property: backgroundColor
Expected value type: UIColor or CGColor.
Additive animation supported: No.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathBackgroundColor NS_SWIFT_NAME(backgroundColor);
/**
Bounds.
Equivalent UIView property: bounds
Equivalent CALayer property: bounds
Expected value type: CGRect or NSValue (containing a CGRect).
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathBounds NS_SWIFT_NAME(bounds);
/**
Border width.
Equivalent UIView property: N/A
Equivalent CALayer property: borderWidth
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathBorderWidth NS_SWIFT_NAME(borderWidth);
/**
Border color.
Equivalent UIView property: N/A
Equivalent CALayer property: borderColor
Expected value type: UIColor or CGColor.
Additive animation supported: No.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathBorderColor NS_SWIFT_NAME(borderColor);
/**
Corner radius.
Equivalent UIView property: N/A
Equivalent CALayer property: cornerRadius
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathCornerRadius NS_SWIFT_NAME(cornerRadius);
/**
Height.
Equivalent UIView property: bounds.size.height
Equivalent CALayer property: bounds.size.height
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathHeight NS_SWIFT_NAME(height);
/**
Opacity.
Equivalent UIView property: alpha
Equivalent CALayer property: opacity
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
TODO( https://github.com/material-motion/motion-animator-objc/issues/61 ):
Disable additive animations for opacity.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathOpacity NS_SWIFT_NAME(opacity);
/**
Position.
Equivalent UIView property: center if the layer's anchorPoint is 0.5, 0.5. N/A otherwise.
Equivalent CALayer property: position
Expected value type: CGPoint or NSValue (containing a CGPoint).
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathPosition NS_SWIFT_NAME(position);
/**
Rotation.
Equivalent UIView property: transform.rotation.z
Equivalent CALayer property: transform.rotation.z
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathRotation NS_SWIFT_NAME(rotation);
/**
Scale.
Uniform scale along both the x and y axis.
Equivalent UIView property: transform.scale
Equivalent CALayer property: transform.scale
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathScale NS_SWIFT_NAME(scale);
/**
Shadow color.
Equivalent UIView property: N/A
Equivalent CALayer property: shadowColor
Expected value type: UIColor or CGColor.
Additive animation supported: No.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathShadowColor NS_SWIFT_NAME(shadowColor);
/**
Shadow offset.
Equivalent UIView property: N/A
Equivalent CALayer property: shadowOffset
Expected value type: CGSize or NSValue (containing a CGSize).
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathShadowOffset NS_SWIFT_NAME(shadowOffset);
/**
Shadow opacity.
Equivalent UIView property: N/A
Equivalent CALayer property: shadowOpacity
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathShadowOpacity NS_SWIFT_NAME(shadowOpacity);
/**
Shadow radius.
Equivalent UIView property: N/A
Equivalent CALayer property: shadowRadius
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathShadowRadius NS_SWIFT_NAME(shadowRadius);
/**
Stroke start.
Equivalent UIView property: N/A
Equivalent CALayer property: N/A
Equivalent CAShapeLayer property: strokeStart
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathStrokeStart NS_SWIFT_NAME(strokeStart);
/**
Stroke end.
Equivalent UIView property: N/A
Equivalent CALayer property: N/A
Equivalent CAShapeLayer property: strokeEnd
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathStrokeEnd NS_SWIFT_NAME(strokeEnd);
/**
Transform.
Equivalent UIView property: transform (2d only)
Equivalent CALayer property: transform (3d)
Expected value type: CGAffineTransform, CATransform or NSValue with either transform type.
CGAffineTransform value types will be converted to CATransform.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathTransform NS_SWIFT_NAME(transform);
/**
Width.
Equivalent UIView property: bounds.size.width
Equivalent CALayer property: bounds.size.width
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathWidth NS_SWIFT_NAME(width);
/**
X position.
Equivalent UIView property: center.x if the layer's anchorPoint.x is 0.5. N/A otherwise.
Equivalent CALayer property: position.x
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathX NS_SWIFT_NAME(x);
/**
Y position.
Equivalent UIView property: center.y if the layer's anchorPoint.y is 0.5. N/A otherwise.
Equivalent CALayer property: position.y
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathY NS_SWIFT_NAME(y);
/**
Z position.
Equivalent UIView property: N/A
Equivalent CALayer property: zPosition
Expected value type: CGFloat or NSNumber.
Additive animation supported: Yes.
*/
FOUNDATION_EXPORT MDMAnimatableKeyPath MDMKeyPathZ NS_SWIFT_NAME(z);
| 30.243542 | 96 | 0.804905 |
93489ac229d51c97a70e62005025223f8e92b5c2 | 1,517 | h | C | src/file.h | tamisoft/rtty | 9a7db400093bbc02c0aa27041db3b75cc5c96c5c | [
"MIT"
] | 1 | 2019-10-06T12:41:13.000Z | 2019-10-06T12:41:13.000Z | src/file.h | tamisoft/rtty | 9a7db400093bbc02c0aa27041db3b75cc5c96c5c | [
"MIT"
] | null | null | null | src/file.h | tamisoft/rtty | 9a7db400093bbc02c0aa27041db3b75cc5c96c5c | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2019 Jianhui Zhao <zhaojh329@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 _FILE_H
#define _FILE_H
#include <uwsc/buffer.h>
#include <ev.h>
#define RF_BLK_SIZE 8912 /* 8KB */
enum {
RF_SEND = 's',
RF_RECV = 'r'
};
struct transfer_context {
int size;
int offset;
int mode;
int fd;
char name[512];
ev_tstamp ts;
struct buffer b;
};
void transfer_file(const char *name);
#endif
| 29.173077 | 81 | 0.722479 |
934b8c2870b94dac495078ef2fd4b2328fd9cd99 | 1,045 | h | C | SocketTCP.h | Upd4ting/CLib | 91b6be60678d5c3bb779237492144a225f1f5f33 | [
"MIT"
] | null | null | null | SocketTCP.h | Upd4ting/CLib | 91b6be60678d5c3bb779237492144a225f1f5f33 | [
"MIT"
] | null | null | null | SocketTCP.h | Upd4ting/CLib | 91b6be60678d5c3bb779237492144a225f1f5f33 | [
"MIT"
] | null | null | null | #pragma once
#include "Socket.h"
void* cThreadFunctionA(void *param);
class SocketTCP : public Socket
{
private:
pthread_t thread;
int ssend(void *data, size_t size, int flag = 0);
int rrecv(void *data, size_t size, int flag = 0);
SocketTCP(const SocketTCP& so);
public:
friend void* cThreadFunctionA(void *param);
SocketTCP(Logger *l);
SocketTCP(int hS, struct sockaddr_in a, Logger *l);
void init(std::string data, int port, IPType type);
void link();
void onStart(bool wait);
void onStop(bool eoc);
// Ecrit des données sur le buffer
// Retourne le nombre de byte écrit
int write(void *data, size_t size, bool writeSize = false, int flag = 0);
// Lire une certaine taille de données depuis le buffer
int read(void *data, size_t size, int flag = 0);
// Lire des données dont la taille
// a été envoyée via un int sur le buffer
int read(void *data, int flag = 0);
// Lire des données sur le buffer jusqu'a un
// certain caractère qui sépare les trames.
int read(void *data, char separator, int flag = 0);
}; | 24.880952 | 74 | 0.704306 |
934cbab3867c1926b8ae8ad268e8406c4918eff8 | 448 | h | C | Animations/PNG.h | Bestmer/CommonAnimations | 61a3cb137aa07af2547da9ae3676fe825fcb4bb4 | [
"MIT"
] | null | null | null | Animations/PNG.h | Bestmer/CommonAnimations | 61a3cb137aa07af2547da9ae3676fe825fcb4bb4 | [
"MIT"
] | null | null | null | Animations/PNG.h | Bestmer/CommonAnimations | 61a3cb137aa07af2547da9ae3676fe825fcb4bb4 | [
"MIT"
] | null | null | null | //
// PNG.h
// PNGIconsCompressTool
//
// Created by YouXianMing on 2017/11/7.
// Copyright © 2017年 Techcode. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface PNG : NSObject
@property (nonatomic) NSString *fileName;
@property (nonatomic) CGFloat basePt;
@property (nonatomic) NSInteger multiply;
+ (PNG *)_1x;
+ (PNG *)_2x;
+ (PNG *)_3x;
- (PNG *)pt:(CGFloat)pt name:(NSString *)name;
@end
| 18.666667 | 52 | 0.678571 |
934ef535bbd6bf724de1b73e24d5a4ec04dd52c8 | 151 | h | C | project490/src/component399/headers/component399/lib29.h | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 2 | 2016-11-23T17:25:24.000Z | 2016-11-23T17:25:27.000Z | project490/src/component399/headers/component399/lib29.h | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 15 | 2016-09-15T03:19:32.000Z | 2016-09-17T09:15:32.000Z | project490/src/component399/headers/component399/lib29.h | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 2 | 2019-11-09T16:26:55.000Z | 2021-01-13T10:51:09.000Z | #ifndef PROJECT_HEADER_component399_29_H
#define PROJECT_HEADER_component399_29_H
int component399_29();
#endif // PROJECT_HEADER_component399_29_H | 18.875 | 42 | 0.86755 |
935195bed750f976c72863db809398b76ab8ef6a | 294 | c | C | Introduction/Overview/cels2farh.c | abhi1506manu/C-Programming | 38d2e62339c6248a4f907672277f7f4a3d47091a | [
"MIT"
] | 24 | 2017-06-13T21:18:32.000Z | 2022-03-07T08:45:59.000Z | Introduction/Overview/cels2farh.c | abhi1506manu/C-Programming | 38d2e62339c6248a4f907672277f7f4a3d47091a | [
"MIT"
] | 1 | 2020-10-15T15:34:24.000Z | 2020-10-15T15:34:24.000Z | Introduction/Overview/cels2farh.c | abhi1506manu/C-Programming | 38d2e62339c6248a4f907672277f7f4a3d47091a | [
"MIT"
] | 28 | 2017-12-15T03:11:19.000Z | 2022-01-09T09:13:47.000Z | #include <stdio.h>
int main()
{
double celsius = 0.0;
double fahrenheit = 0.0;
printf("Enter the temp in deg celsius: ");
scanf("%lf", &celsius);
fahrenheit = celsius * 9/5 + 32;
printf("%lf deg celsius = %lf deg fahrenheit\n", celsius, fahrenheit);
return 0;
}
| 18.375 | 74 | 0.598639 |
9356f62933d095a890a11ca67061d397f24f778f | 940 | h | C | src/prod/src/data/tstore/Index.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/data/tstore/Index.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/data/tstore/Index.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Data
{
namespace TStore
{
class Index
{
public:
Index(__in int partitionindex, __in int itemIndex);
~Index();
__declspec(property(get = get_ItemIndex)) int ItemIndex;
int get_ItemIndex() const
{
return itemIndex_;
}
__declspec(property(get = get_PartitionIndex)) int PartitionIndex;
int get_PartitionIndex() const
{
return partitionIndex_;
}
private:
int partitionIndex_;
int itemIndex_;
};
}
}
| 26.111111 | 98 | 0.476596 |
935bbbb64fc226dfce32f02d933a8dccc0b681c9 | 642 | c | C | spew.c | kbrafford/spew | 60c72426179facbd126fedbf5a3bb79d093932fc | [
"MIT"
] | null | null | null | spew.c | kbrafford/spew | 60c72426179facbd126fedbf5a3bb79d093932fc | [
"MIT"
] | null | null | null | spew.c | kbrafford/spew | 60c72426179facbd126fedbf5a3bb79d093932fc | [
"MIT"
] | null | null | null | #include <sys/syscall.h>
#include <unistd.h>
extern char _binary__work_resource_bin_start[];
extern char _binary__work_resource_bin_end[];
#define _BATCH_SIZE 1024
int spew_resource(char *ptr, int len)
{
int num_batch_packets = len / _BATCH_SIZE;
int leftover = len % _BATCH_SIZE;
while(num_batch_packets--)
{
syscall(SYS_write, STDOUT_FILENO, ptr, _BATCH_SIZE);
ptr += _BATCH_SIZE;
}
syscall(SYS_write, STDOUT_FILENO, ptr, leftover);
return 0;
}
int main(void)
{
spew_resource(_binary__work_resource_bin_start, (unsigned int)(_binary__work_resource_bin_end - _binary__work_resource_bin_start));
return 0;
}
| 20.709677 | 133 | 0.755452 |