hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cffa7473e7fddbe6b50f6344531ce1dbf5bbc012 | 9,764 | c | C | src/mpi/coll/ibarrier.c | humairakamal/FG-MPI | a0181ecde8a97e60ab6721a5e9a74dc7e7f77e77 | [
"BSD-3-Clause"
] | 7 | 2015-12-31T03:15:50.000Z | 2020-08-15T00:54:47.000Z | src/mpi/coll/ibarrier.c | humairakamal/FG-MPI | a0181ecde8a97e60ab6721a5e9a74dc7e7f77e77 | [
"BSD-3-Clause"
] | 3 | 2015-12-30T22:28:15.000Z | 2017-05-16T19:17:42.000Z | src/mpi/coll/ibarrier.c | humairakamal/FG-MPI | a0181ecde8a97e60ab6721a5e9a74dc7e7f77e77 | [
"BSD-3-Clause"
] | 3 | 2015-12-29T22:14:56.000Z | 2019-06-13T07:23:35.000Z | /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
* (C) 2010 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include "mpiimpl.h"
/* -- Begin Profiling Symbol Block for routine MPI_Ibarrier */
#if defined(HAVE_PRAGMA_WEAK)
#pragma weak MPI_Ibarrier = PMPI_Ibarrier
#elif defined(HAVE_PRAGMA_HP_SEC_DEF)
#pragma _HP_SECONDARY_DEF PMPI_Ibarrier MPI_Ibarrier
#elif defined(HAVE_PRAGMA_CRI_DUP)
#pragma _CRI duplicate MPI_Ibarrier as PMPI_Ibarrier
#elif defined(HAVE_WEAK_ATTRIBUTE)
int MPI_Ibarrier(MPI_Comm comm, MPI_Request *request) __attribute__((weak,alias("PMPI_Ibarrier")));
#endif
/* -- End Profiling Symbol Block */
/* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build
the MPI routines */
#ifndef MPICH_MPI_FROM_PMPI
#undef MPI_Ibarrier
#define MPI_Ibarrier PMPI_Ibarrier
/* any non-MPI functions go here, especially non-static ones */
/* This is the default implementation of the barrier operation. The
algorithm is:
Algorithm: MPI_Ibarrier
We use the dissemination algorithm described in:
Debra Hensgen, Raphael Finkel, and Udi Manber, "Two Algorithms for
Barrier Synchronization," International Journal of Parallel
Programming, 17(1):1-17, 1988.
It uses ceiling(lgp) steps. In step k, 0 <= k <= (ceiling(lgp)-1),
process i sends to process (i + 2^k) % p and receives from process
(i - 2^k + p) % p.
Possible improvements:
End Algorithm: MPI_Ibarrier
This is an intracommunicator barrier only!
*/
/* Provides a generic "flat" barrier that doesn't know anything about hierarchy.
* It will choose between several different algorithms based on the given
* parameters. */
#undef FUNCNAME
#define FUNCNAME MPIR_Ibarrier_intra
#undef FCNAME
#define FCNAME MPL_QUOTE(FUNCNAME)
int MPIR_Ibarrier_intra(MPID_Comm *comm_ptr, MPID_Sched_t s)
{
int mpi_errno = MPI_SUCCESS;
int size, rank, src, dst, mask;
MPIU_Assert(comm_ptr->comm_kind == MPID_INTRACOMM);
size = comm_ptr->local_size;
rank = comm_ptr->rank;
/* Trivial barriers return immediately */
if (size == 1) goto fn_exit;
mask = 0x1;
while (mask < size) {
dst = (rank + mask) % size;
src = (rank - mask + size) % size;
mpi_errno = MPID_Sched_send(NULL, 0, MPI_BYTE, dst, comm_ptr, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
mpi_errno = MPID_Sched_recv(NULL, 0, MPI_BYTE, src, comm_ptr, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
mpi_errno = MPID_Sched_barrier(s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
mask <<= 1;
}
fn_exit:
return mpi_errno;
fn_fail:
goto fn_exit;
}
/* Provides a generic "flat" barrier that doesn't know anything about hierarchy.
* It will choose between several different algorithms based on the given
* parameters. */
#undef FUNCNAME
#define FUNCNAME MPIR_Ibarrier_inter
#undef FCNAME
#define FCNAME MPL_QUOTE(FUNCNAME)
int MPIR_Ibarrier_inter(MPID_Comm *comm_ptr, MPID_Sched_t s)
{
int mpi_errno = MPI_SUCCESS;
int rank, root;
MPIR_SCHED_CHKPMEM_DECL(1);
char *buf = NULL;
MPIU_Assert(comm_ptr->comm_kind == MPID_INTERCOMM);
rank = comm_ptr->rank;
/* Get the local intracommunicator */
if (!comm_ptr->local_comm) {
mpi_errno = MPIR_Setup_intercomm_localcomm(comm_ptr);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
}
/* do a barrier on the local intracommunicator */
MPIU_Assert(comm_ptr->local_comm->coll_fns && comm_ptr->local_comm->coll_fns->Ibarrier_sched);
if(comm_ptr->local_size != 1) {
mpi_errno = comm_ptr->local_comm->coll_fns->Ibarrier_sched(comm_ptr->local_comm, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
MPID_SCHED_BARRIER(s);
}
/* rank 0 on each group does an intercommunicator broadcast to the
remote group to indicate that all processes in the local group
have reached the barrier. We do a 1-byte bcast because a 0-byte
bcast will just return without doing anything. */
MPIR_SCHED_CHKPMEM_MALLOC(buf, char *, 1, mpi_errno, "bcast buf");
buf[0] = 'D'; /* avoid valgrind warnings */
/* first broadcast from left to right group, then from right to
left group */
MPIU_Assert(comm_ptr->coll_fns && comm_ptr->coll_fns->Ibcast_sched);
if (comm_ptr->is_low_group) {
root = (rank == 0) ? MPI_ROOT : MPI_PROC_NULL;
mpi_errno = comm_ptr->coll_fns->Ibcast_sched(buf, 1, MPI_BYTE, root, comm_ptr, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
MPID_SCHED_BARRIER(s);
/* receive bcast from right */
root = 0;
mpi_errno = comm_ptr->coll_fns->Ibcast_sched(buf, 1, MPI_BYTE, root, comm_ptr, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
}
else {
/* receive bcast from left */
root = 0;
mpi_errno = comm_ptr->coll_fns->Ibcast_sched(buf, 1, MPI_BYTE, root, comm_ptr, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
MPID_SCHED_BARRIER(s);
/* bcast to left */
root = (rank == 0) ? MPI_ROOT : MPI_PROC_NULL;
mpi_errno = comm_ptr->coll_fns->Ibcast_sched(buf, 1, MPI_BYTE, root, comm_ptr, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
}
MPIR_SCHED_CHKPMEM_COMMIT(s);
fn_exit:
return mpi_errno;
fn_fail:
MPIR_SCHED_CHKPMEM_REAP(s);
goto fn_exit;
}
#undef FUNCNAME
#define FUNCNAME MPIR_Ibarrier_impl
#undef FCNAME
#define FCNAME MPL_QUOTE(FUNCNAME)
int MPIR_Ibarrier_impl(MPID_Comm *comm_ptr, MPI_Request *request)
{
int mpi_errno = MPI_SUCCESS;
MPID_Request *reqp = NULL;
int tag = -1;
MPID_Sched_t s = MPID_SCHED_NULL;
*request = MPI_REQUEST_NULL;
MPIU_Assert(comm_ptr->coll_fns != NULL);
if (comm_ptr->coll_fns->Ibarrier_req != NULL) { /* FG:NBC Double-check */
/* --BEGIN USEREXTENSION-- */
mpi_errno = comm_ptr->coll_fns->Ibarrier_req(comm_ptr, &reqp);
if (reqp) {
*request = reqp->handle;
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
goto fn_exit;
}
/* --END USEREXTENSION-- */
}
if (comm_ptr->local_size != 1 || comm_ptr->comm_kind == MPID_INTERCOMM) {
mpi_errno = MPID_Sched_next_tag(comm_ptr, &tag);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
mpi_errno = MPID_Sched_create(&s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
MPIU_Assert(comm_ptr->coll_fns->Ibarrier_sched != NULL);
mpi_errno = comm_ptr->coll_fns->Ibarrier_sched(comm_ptr, s);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
mpi_errno = MPID_Sched_start(&s, comm_ptr, tag, &reqp);
if (reqp)
*request = reqp->handle;
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
}
fn_exit:
return mpi_errno;
fn_fail:
goto fn_exit;
}
#endif /* MPICH_MPI_FROM_PMPI */
#undef FUNCNAME
#define FUNCNAME MPI_Ibarrier
#undef FCNAME
#define FCNAME MPL_QUOTE(FUNCNAME)
/*@
MPI_Ibarrier - Notifies the process that it has reached the barrier and returns
immediately
Input Parameters:
. comm - communicator (handle)
Output Parameters:
. request - communication request (handle)
Notes:
MPI_Ibarrier is a nonblocking version of MPI_barrier. By calling MPI_Ibarrier,
a process notifies that it has reached the barrier. The call returns
immediately, independent of whether other processes have called MPI_Ibarrier.
The usual barrier semantics are enforced at the corresponding completion
operation (test or wait), which in the intra-communicator case will complete
only after all other processes in the communicator have called MPI_Ibarrier. In
the intercommunicator case, it will complete when all processes in the remote
group have called MPI_Ibarrier.
.N ThreadSafe
.N Fortran
.N Errors
@*/
int MPI_Ibarrier(MPI_Comm comm, MPI_Request *request)
{
int mpi_errno = MPI_SUCCESS;
MPID_Comm *comm_ptr = NULL;
MPID_MPI_STATE_DECL(MPID_STATE_MPI_IBARRIER);
MPID_THREAD_CS_ENTER(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
MPID_MPI_FUNC_ENTER(MPID_STATE_MPI_IBARRIER);
/* Validate parameters, especially handles needing to be converted */
# ifdef HAVE_ERROR_CHECKING
{
MPID_BEGIN_ERROR_CHECKS
{
MPIR_ERRTEST_COMM(comm, mpi_errno);
/* TODO more checks may be appropriate */
}
MPID_END_ERROR_CHECKS
}
# endif /* HAVE_ERROR_CHECKING */
/* Convert MPI object handles to object pointers */
MPID_Comm_get_ptr(comm, comm_ptr);
/* Validate parameters and objects (post conversion) */
# ifdef HAVE_ERROR_CHECKING
{
MPID_BEGIN_ERROR_CHECKS
{
MPID_Comm_valid_ptr( comm_ptr, mpi_errno, FALSE );
if (mpi_errno != MPI_SUCCESS) goto fn_fail;
MPIR_ERRTEST_ARGNULL(request,"request", mpi_errno);
/* TODO more checks may be appropriate (counts, in_place, buffer aliasing, etc) */
}
MPID_END_ERROR_CHECKS
}
# endif /* HAVE_ERROR_CHECKING */
/* ... body of routine ... */
mpi_errno = MPIR_Ibarrier_impl(comm_ptr, request);
if (mpi_errno) MPIR_ERR_POP(mpi_errno);
/* ... end of body of routine ... */
fn_exit:
MPID_MPI_FUNC_EXIT(MPID_STATE_MPI_IBARRIER);
MPID_THREAD_CS_EXIT(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
return mpi_errno;
fn_fail:
/* --BEGIN ERROR HANDLING-- */
# ifdef HAVE_ERROR_CHECKING
{
mpi_errno = MPIR_Err_create_code(
mpi_errno, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_OTHER,
"**mpi_ibarrier", "**mpi_ibarrier %C %p", comm, request);
}
# endif
mpi_errno = MPIR_Err_return_comm(comm_ptr, FCNAME, mpi_errno);
goto fn_exit;
/* --END ERROR HANDLING-- */
goto fn_exit;
}
| 31.395498 | 99 | 0.687218 | [
"object"
] |
cffe4943d43c994e99b0942fa15791af74717619 | 32,668 | h | C | engine/client/render.h | BryanHaley/fteqw-applesilicon | 06714d400c13c3f50bcd03e3d2184648a71ddb29 | [
"Intel"
] | 1 | 2022-03-20T01:14:23.000Z | 2022-03-20T01:14:23.000Z | engine/client/render.h | BryanHaley/fteqw-applesilicon | 06714d400c13c3f50bcd03e3d2184648a71ddb29 | [
"Intel"
] | null | null | null | engine/client/render.h | BryanHaley/fteqw-applesilicon | 06714d400c13c3f50bcd03e3d2184648a71ddb29 | [
"Intel"
] | null | null | null | /*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// refresh.h -- public interface to refresh functions
// default soldier colors
#define TOP_DEFAULT 1
#define BOTTOM_DEFAULT 6
#define TOP_RANGE (TOP_DEFAULT<<4)
#define BOTTOM_RANGE (BOTTOM_DEFAULT<<4)
struct msurface_s;
struct batch_s;
struct model_s;
struct texnums_s;
struct texture_s;
static const texid_t r_nulltex = NULL;
//GLES2 requires GL_UNSIGNED_SHORT (gles3 or GL_OES_element_index_uint relax this requirement)
//geforce4 only does shorts. gffx can do ints, but with a performance hit (like most things on that gpu)
//ati is generally more capable, but generally also has a smaller market share
//desktop-gl will generally cope with ints, but expect a performance hit from that with old gpus (so we don't bother)
//vulkan+dx10 can cope with ints, but might be 24bit
//either way, all renderers in the same build need to use the same thing.
#ifndef sizeof_index_t
#ifdef VERTEXINDEXBYTES //maybe set in config_*.h
#define sizeof_index_t VERTEXINDEXBYTES
#elif (defined(GLQUAKE) && defined(HAVE_LEGACY)) || defined(MINIMAL) || defined(D3D8QUAKE) || defined(D3D9QUAKE) || defined(ANDROID) || defined(FTE_TARGET_WEB)
#define sizeof_index_t 2
#endif
#endif
#if sizeof_index_t == 2
#define GL_INDEX_TYPE GL_UNSIGNED_SHORT
#define D3DFMT_QINDEX D3DFMT_INDEX16
#define DXGI_FORMAT_INDEX_UINT DXGI_FORMAT_R16_UINT
#define VK_INDEX_TYPE VK_INDEX_TYPE_UINT16
typedef unsigned short index_t;
#define MAX_INDICIES 0xffffu
#else
#undef sizeof_index_t
#define sizeof_index_t 4
#define GL_INDEX_TYPE GL_UNSIGNED_INT
#define D3DFMT_QINDEX D3DFMT_INDEX32
#define DXGI_FORMAT_INDEX_UINT DXGI_FORMAT_R32_UINT
#define VK_INDEX_TYPE VK_INDEX_TYPE_UINT32
typedef unsigned int index_t;
#define MAX_INDICIES 0x00ffffffu
#endif
//=============================================================================
//the eye doesn't see different colours in the same proportion.
//must add to slightly less than 1
#define NTSC_RED 0.299
#define NTSC_GREEN 0.587
#define NTSC_BLUE 0.114
#define NTSC_SUM (NTSC_RED + NTSC_GREEN + NTSC_BLUE)
typedef enum {
RT_MODEL,
RT_POLY,
RT_SPRITE,
RT_BEAM,
RT_RAIL_CORE,
RT_RAIL_RINGS,
RT_LIGHTNING,
RT_PORTALSURFACE, // doesn't draw anything, just info for portals
//q3 ones stop here.
//fte ones start here
RT_PORTALCAMERA, // an alternative to RT_PORTALSURFACE.
RT_MAX_REF_ENTITY_TYPE
} refEntityType_t;
typedef unsigned int skinid_t; //skin 0 is 'unused'
struct dlight_s;
typedef struct entity_s
{
//FIXME: instancing somehow. separate visentity+visinstance. only viable with full glsl though.
//will need to generate a vbo somehow for the instances.
int keynum; // for matching entities in different frames
vec3_t origin;
vec3_t angles; // fixme: should be redundant.
vec3_t axis[3];
vec4_t shaderRGBAf; /*colormod+alpha, available for shaders to mix*/
float shaderTime; /*timestamp, for syncing shader times to spawns*/
vec3_t glowmod; /*meant to be a multiplier for the fullbrights*/
int light_known; /*bsp lighting has been calced*/
vec3_t light_avg; /*midpoint level*/
vec3_t light_range; /*avg + this = max, avg - this = min*/
vec3_t light_dir;
vec3_t oldorigin; /*for q2/q3 beams*/
struct model_s *model; // NULL = no model
int skinnum; // for Alias models
skinid_t customskin; // quake3 style skins
int playerindex; //for qw skins
int topcolour; //colourmapping
int bottomcolour; //colourmapping
#ifdef HEXEN2
int h2playerclass; //hexen2's quirky colourmapping
#endif
// struct efrag_s *efrag; // linked list of efrags (FIXME)
// int visframe; // last frame this entity was
// found in an active leaf
// only used for static objects
// int dlightframe; // dynamic lighting
// dlightbitmask_t dlightbits;
// FIXME: could turn these into a union
// int trivial_accept;
// struct mnode_s *topnode; // for bmodels, first world node
// that splits bmodel, or NULL if
// not split
framestate_t framestate;
int flags;
refEntityType_t rtype;
float rotation;
struct shader_s *forcedshader;
pvscache_t pvscache; //for culling of csqc ents.
#ifdef PEXT_SCALE
float scale;
#endif
#ifdef PEXT_FATNESS
float fatness;
#endif
#ifdef HEXEN2
int drawflags;
int abslight;
#endif
} entity_t;
#define MAX_GEOMSETS 32
#define Q1UNSPECIFIED 0x00ffffff //0xffRRGGBB or 0x0000000V are both valid values. so this is an otherwise-illegal value to say its not been set.
typedef struct
{
int refcount;
char skinname[MAX_QPATH];
int nummappings;
int maxmappings;
qbyte geomset[MAX_GEOMSETS]; //allows selecting a single set of geometry from alternatives. this might be a can of worms.
#ifdef QWSKINS
char qwskinname[MAX_QPATH];
struct qwskin_s *qwskin;
unsigned int q1upper; //Q1UNSPECIFIED
unsigned int q1lower; //Q1UNSPECIFIED
#endif
struct
{
char surface[MAX_QPATH];
shader_t *shader;
texnums_t texnums;
int needsfree; //which textures need to be freed.
} mappings[1];
} skinfile_t;
// plane_t structure
typedef struct mplane_s
{
vec3_t normal;
float dist;
qbyte type; // for texture axis selection and fast side tests
qbyte signbits; // signx + signy<<1 + signz<<1
qbyte pad[2];
} mplane_t;
#define MAXFRUSTUMPLANES 7 //4 side, 1 near, 1 far (fog), 1 water plane.
typedef struct
{
//note: uniforms expect specific padding/ordering. be really careful with reordering this
vec3_t colour; //w_fog[0].xyz
float alpha; //w_fog[0].w scales clamped fog value
float density; //w_fog[1].x egads, everyone has a different opinion.
float depthbias; //w_fog[1].y distance until the fog actually starts
float glslpad1; //w_fog[1].z
float glslpad2; //w_fog[1].w
// float start;
// float end;
// float height;
// float fadedepth;
float time; //timestamp for when its current.
} fogstate_t;
void CL_BlendFog(fogstate_t *result, fogstate_t *oldf, float time, fogstate_t *newf);
void CL_ResetFog(int fogtype);
typedef enum {
STEREO_OFF,
STEREO_QUAD,
STEREO_RED_CYAN,
STEREO_RED_BLUE,
STEREO_RED_GREEN,
STEREO_CROSSEYED,
//these are internal methods and do not form part of any public API
STEREO_LEFTONLY,
STEREO_RIGHTONLY
} stereomethod_t;
typedef enum
{
PROJ_STANDARD = 0,
PROJ_STEREOGRAPHIC = 1, //aka panini
PROJ_FISHEYE = 2, //standard fisheye
PROJ_PANORAMA = 3, //for nice panoramas
PROJ_LAEA = 4, //lambert azimuthal equal-area
PROJ_EQUIRECTANGULAR = 5 //projects a sphere into 2d. used by vr screenshots.
} qprojection_t;
typedef struct {
char texname[MAX_QPATH];
} rtname_t;
#define R_MAX_RENDERTARGETS 8
#ifndef R_MAX_RECURSE
#define R_MAX_RECURSE 6
#endif
#define RDFD_FOV 1
typedef struct refdef_s
{
vrect_t grect; // game rectangle. fullscreen except for csqc/splitscreen/hud.
vrect_t vrect; // subwindow in grect for 3d view. equal to grect if no hud.
vec3_t pvsorigin; /*render the view using this point for pvs (useful for mirror views)*/
vec3_t vieworg; /*logical view center*/
vec3_t viewangles;
vec3_t viewaxis[3]; /*forward, left, up (NOT RIGHT)*/
vec3_t eyeoffset; /*world space, for vr screenies*/
vec2_t projectionoffset; /*for off-centre rendering*/
qboolean base_known; /*otherwise we do some fallback behaviour (ie: viewangles.0y0 and forcing input_angles)*/
vec3_t base_angles, base_origin; /*for vr output, overrides per-eye viewangles according to that eye's matrix.*/
vec3_t weaponmatrix[4]; /*forward/left/up/origin*/
vec3_t weaponmatrix_bob[4]; /*forward/left/up/origin*/
float fov_x, fov_y, afov;
float fovv_x, fovv_y; //viewmodel fovs
float mindist, maxdist; //maxdist may be 0, for 'infinite', in which case mindist probably isn't valid either.
qboolean drawsbar;
qboolean drawcrosshair;
int flags; //(Q2)RDF_ flags
int dirty;
playerview_t *playerview;
// int currentplayernum;
float time;
// float waterheight; //updated by the renderer. stuff sitting at this height generate ripple effects
float m_projection_std[16]; //projection matrix for normal stuff
float m_projection_view[16]; //projection matrix for the viewmodel. because people are weird.
float m_view[16];
qbyte *scenevis; /*this is the vis that's currently being draw*/
int *sceneareas; /*this is the area info for the camera (should normally be count+one area, but could be two areas near an opaque water plane)*/
mplane_t frustum[MAXFRUSTUMPLANES];
int frustum_numworldplanes; //all but far, which isn't culled because this wouldn't cover the entire screen.
int frustum_numplanes; //includes far plane (which is reduced with fog).
fogstate_t globalfog;
float hdr_value;
vec3_t skyroom_pos; /*the camera position for sky rooms*/
vec4_t skyroom_spin; /*the camera spin for sky rooms*/
qboolean skyroom_enabled; /*whether a skyroom position is defined*/
int firstvisedict; /*so we can skip visedicts in skies*/
pxrect_t pxrect; /*vrect, but in pixels rather than virtual coords*/
qboolean externalview; /*draw external models and not viewmodels*/
int recurse; /*in a mirror/portal/half way through drawing something else*/
qboolean forcevis; /*if true, vis comes from the forcedvis field instead of recalculated*/
unsigned int flipcull; /*reflected/flipped view, requires inverted culling (should be set to SHADER_CULL_FLIPPED or 0 - its implemented as a xor)*/
unsigned int colourmask; /*shaderbits mask. anything not here will be forced to 0. this is for red/green type stereo*/
qboolean useperspective; /*not orthographic*/
stereomethod_t stereomethod;
rtname_t rt_destcolour[R_MAX_RENDERTARGETS]; /*used for 2d. written by 3d*/
rtname_t rt_sourcecolour; /*read by 2d. not used for 3d. */
rtname_t rt_depth; /*read by 2d. used by 3d (renderbuffer used if not set)*/
rtname_t rt_ripplemap; /*read by 2d. used by 3d (internal ripplemap buffer used if not set)*/
rtname_t nearenvmap; /*provides a fallback endmap cubemap to render with*/
qbyte *forcedvis; /*set if forcevis is set*/
qboolean areabitsknown;
qbyte areabits[MAX_MAP_AREA_BYTES];
vec4_t userdata[16]; /*for custom glsl*/
qboolean warndraw; /*buggy gamecode likes drawing outside of te drawing logic*/
} refdef_t;
extern refdef_t r_refdef;
extern vec3_t r_origin, vpn, vright, vup;
extern struct texture_s *r_notexture_mip;
extern entity_t r_worldentity;
void BE_GenModelBatches(struct batch_s **batches, const struct dlight_s *dl, unsigned int bemode, const qbyte *worldpvs, const int *worldareas); //if dl, filters based upon the dlight.
//gl_alias.c
void R_GAliasFlushSkinCache(qboolean final);
void R_GAlias_DrawBatch(struct batch_s *batch);
void R_GAlias_GenerateBatches(entity_t *e, struct batch_s **batches);
void R_LightArraysByte_BGR(const entity_t *entity, vecV_t *coords, byte_vec4_t *colours, int vertcount, vec3_t *normals, qboolean colormod);
void R_LightArrays(const entity_t *entity, vecV_t *coords, avec4_t *colours, int vertcount, vec3_t *normals, float scale, qboolean colormod);
qboolean R_DrawSkyChain (struct batch_s *batch); /*called from the backend, and calls back into it*/
void R_InitSky (shader_t *shader, const char *skyname, uploadfmt_t fmt, qbyte *src, unsigned int width, unsigned int height); /*generate q1 sky texnums*/
void R_Clutter_Emit(struct batch_s **batches);
void R_Clutter_Purge(void);
//r_surf.c
void Surf_NewMap (struct model_s *worldmodel);
void Surf_PreNewMap(void);
void Surf_SetupFrame(void); //determine pvs+viewcontents
void Surf_DrawWorld(void);
void Surf_GenBrushBatches(struct batch_s **batches, entity_t *ent);
void Surf_StainSurf(struct msurface_s *surf, float *parms);
void Surf_AddStain(vec3_t org, float red, float green, float blue, float radius);
void Surf_LessenStains(void);
void Surf_WipeStains(void);
void Surf_DeInit(void);
void Surf_Clear(struct model_s *mod);
void Surf_BuildLightmaps(void); //enables Surf_BuildModelLightmaps, calls it for each bsp.
void Surf_ClearSceneCache(void); //stops Surf_BuildModelLightmaps from working.
void Surf_BuildModelLightmaps (struct model_s *m); //rebuild lightmaps for a single bsp. beware of submodels.
void Surf_RenderDynamicLightmaps (struct msurface_s *fa);
void Surf_RenderAmbientLightmaps (struct msurface_s *fa, int ambient);
int Surf_LightmapShift (struct model_s *model);
#define LMBLOCK_SIZE_MAX 2048 //single axis
typedef struct glRect_s {
unsigned short l,t,r,b;
} glRect_t;
typedef unsigned char stmap;
struct mesh_s;
typedef struct {
texid_t lightmap_texture;
qboolean modified; //data was changed. consult rectchange to see the bounds.
qboolean external; //the data was loaded from a file (q3bsp feature where we shouldn't be blending lightmaps at all)
qboolean hasdeluxe; //says that the next lightmap index contains deluxemap info
uploadfmt_t fmt; //texture format that we're using
qbyte pixbytes; //yes, this means no compressed formats.
int width;
int height;
glRect_t rectchange;
qbyte *lightmaps; //[pixbytes*LMBLOCK_WIDTH*LMBLOCK_HEIGHT];
stmap *stainmaps; //[3*LMBLOCK_WIDTH*LMBLOCK_HEIGHT]; //rgb no a. added to lightmap for added (hopefully) speed.
#ifdef GLQUAKE
int pbo_handle; //when set, lightmaps is a persistently mapped write-only pbo for us to scribble data into, ready to be copied to the actual texture without waiting for glTexSubImage to complete.
#endif
} lightmapinfo_t;
extern lightmapinfo_t **lightmap;
extern int numlightmaps;
void QDECL Surf_RebuildLightmap_Callback (struct cvar_s *var, char *oldvalue);
void R_Sky_Register(void);
void R_SkyShutdown(void);
void R_SetSky(const char *skyname);
texid_t R_GetDefaultEnvmap(void);
#if defined(GLQUAKE)
void GLR_Init (void);
void GLR_InitTextures (void);
void GLR_InitEfrags (void);
void GLR_RenderView (void); // must set r_refdef first
// called whenever r_refdef or vid change
void GLR_DrawPortal(struct batch_s *batch, struct batch_s **blist, struct batch_s *depthmasklist[2], int portaltype);
void GLR_PushDlights (void);
void GLR_DrawWaterSurfaces (void);
void GLVID_DeInit (void);
void GLR_DeInit (void);
void GLSCR_DeInit (void);
void GLVID_Console_Resize(void);
#endif
int R_LightPoint (vec3_t p);
void R_RenderDlights (void);
typedef struct
{
int allocated[LMBLOCK_SIZE_MAX];
int firstlm;
int lmnum;
unsigned int width;
unsigned int height;
qboolean deluxe;
} lmalloc_t;
void Mod_LightmapAllocInit(lmalloc_t *lmallocator, qboolean hasdeluxe, unsigned int width, unsigned int height, int firstlm); //firstlm is for debugging stray lightmap indexes
//void Mod_LightmapAllocDone(lmalloc_t *lmallocator, model_t *mod);
void Mod_LightmapAllocBlock(lmalloc_t *lmallocator, int w, int h, unsigned short *x, unsigned short *y, int *tnum);
enum imageflags
{
/*warning: many of these flags only apply the first time it is requested*/
IF_CLAMP = 1<<0, //disable texture coord wrapping.
IF_NOMIPMAP = 1<<1, //disable mipmaps.
IF_NEAREST = 1<<2, //force nearest
IF_LINEAR = 1<<3, //force linear
IF_UIPIC = 1<<4, //subject to texturemode2d
//IF_DEPTHCMD = 1<<5, //Reserved for d3d11
IF_SRGB = 1<<6, //texture data is srgb (read-as-linear)
/*WARNING: If the above are changed, be sure to change shader pass flags*/
IF_NOPICMIP = 1<<7,
IF_NOALPHA = 1<<8, /*hint rather than requirement*/
IF_NOGAMMA = 1<<9, /*do not apply texture-based gamma*/
IF_TEXTYPEMASK = (1<<10) | (1<<11) | (1<<12), /*0=2d, 1=3d, 2=cubeface, 3=2d array texture*/
#define IF_TEXTYPESHIFT 10
#define IF_TEXTYPE_2D (PTI_2D<<IF_TEXTYPESHIFT)
#define IF_TEXTYPE_3D (PTI_3D<<IF_TEXTYPESHIFT)
#define IF_TEXTYPE_CUBE (PTI_CUBE<<IF_TEXTYPESHIFT)
#define IF_TEXTYPE_2D_ARRAY (PTI_2D_ARRAY<<IF_TEXTYPESHIFT)
#define IF_TEXTYPE_CUBE_ARRAY (PTI_CUBE_ARRAY<<IF_TEXTYPESHIFT)
#define IF_TEXTYPE_ANY (PTI_ANY<<IF_TEXTYPESHIFT)
IF_MIPCAP = 1<<13, //allow the use of d_mipcap
IF_PREMULTIPLYALPHA = 1<<14, //rgb *= alpha
IF_UNUSED15 = 1<<15, //
IF_UNUSED16 = 1<<16, //
IF_INEXACT = 1<<17, //subdir info isn't to be used for matching
IF_WORLDTEX = 1<<18, //gl_picmip_world
IF_SPRITETEX = 1<<19, //gl_picmip_sprites
IF_NOSRGB = 1<<20, //ignore srgb when loading. this is guarenteed to be linear, for normalmaps etc.
IF_PALETTIZE = 1<<21, //convert+load it as an RTI_P8 texture for the current palette/colourmap
IF_NOPURGE = 1<<22, //texture is not flushed when no more shaders refer to it (for C code that holds a permanant reference to it - still purged on vid_reloads though)
IF_HIGHPRIORITY = 1<<23, //pushed to start of worker queue instead of end...
IF_LOWPRIORITY = 1<<24, //
IF_LOADNOW = 1<<25, /*hit the disk now, and delay the gl load until its actually needed. this is used only so that the width+height are known in advance. valid on worker threads.*/
IF_NOPCX = 1<<26, /*block pcx format. meaning qw skins can use team colours and cropping*/
IF_TRYBUMP = 1<<27, /*attempt to load _bump if the specified _norm texture wasn't found*/
IF_RENDERTARGET = 1<<28, /*never loaded from disk, loading can't fail*/
IF_EXACTEXTENSION = 1<<29, /*don't mangle extensions, use what is specified and ONLY that*/
IF_NOREPLACE = 1<<30, /*don't load a replacement, for some reason*/
IF_NOWORKER = 1u<<31 /*don't pass the work to a loader thread. this gives fully synchronous loading. only valid from the main thread.*/
};
#define R_LoadTexture8(id,w,h,d,f,t) Image_GetTexture(id, NULL, f, d, NULL, w, h, t?TF_TRANS8:TF_SOLID8)
#define R_LoadTexture32(id,w,h,d,f) Image_GetTexture(id, NULL, f, d, NULL, w, h, TF_RGBA32)
#define R_LoadTextureFB(id,w,h,d,f) Image_GetTexture(id, NULL, f, d, NULL, w, h, TF_TRANS8_FULLBRIGHT)
#define R_LoadTexture(id,w,h,fmt,d,fl) Image_GetTexture(id, NULL, fl, d, NULL, w, h, fmt)
image_t *Image_TextureIsValid(qintptr_t address);
image_t *Image_FindTexture (const char *identifier, const char *subpath, unsigned int flags);
image_t *Image_CreateTexture(const char *identifier, const char *subpath, unsigned int flags);
image_t *QDECL Image_GetTexture (const char *identifier, const char *subpath, unsigned int flags, void *fallbackdata, void *fallbackpalette, int fallbackwidth, int fallbackheight, uploadfmt_t fallbackfmt);
qboolean Image_UnloadTexture(image_t *tex); //true if it did something.
void Image_DestroyTexture (image_t *tex);
qboolean Image_LoadTextureFromMemory(texid_t tex, int flags, const char *iname, const char *fname, qbyte *filedata, int filesize); //intended really for worker threads, but should be fine from the main thread too
qboolean Image_LocateHighResTexture(image_t *tex, flocation_t *bestloc, char *bestname, size_t bestnamesize, unsigned int *bestflags);
void Image_Upload (texid_t tex, uploadfmt_t fmt, void *data, void *palette, int width, int height, int depth, unsigned int flags);
void Image_Purge(void); //purge any textures which are not needed any more (releases memory, but doesn't give null pointers).
void Image_Init(void);
void Image_Shutdown(void);
void Image_PrintInputFormatVersions(void); //for version info
qboolean Image_WriteKTXFile(const char *filename, enum fs_relative fsroot, struct pendingtextureinfo *mips);
qboolean Image_WriteDDSFile(const char *filename, enum fs_relative fsroot, struct pendingtextureinfo *mips);
void Image_BlockSizeForEncoding(uploadfmt_t encoding, unsigned int *blockbytes, unsigned int *blockwidth, unsigned int *blockheight, unsigned int *blockdepth);
const char *Image_FormatName(uploadfmt_t encoding);
qboolean Image_FormatHasAlpha(uploadfmt_t encoding);
image_t *Image_LoadTexture (const char *identifier, int width, int height, uploadfmt_t fmt, void *data, unsigned int flags);
struct pendingtextureinfo *Image_LoadMipsFromMemory(int flags, const char *iname, const char *fname, qbyte *filedata, int filesize);
void Image_ChangeFormat(struct pendingtextureinfo *mips, qboolean *allowedformats, uploadfmt_t origfmt, const char *imagename);
void Image_Premultiply(struct pendingtextureinfo *mips);
void *Image_FlipImage(const void *inbuffer, void *outbuffer, int *inoutwidth, int *inoutheight, int pixelbytes, qboolean flipx, qboolean flipy, qboolean flipd);
typedef struct
{
const char *loadername;
size_t pendingtextureinfosize;
qboolean canloadcubemaps;
struct pendingtextureinfo *(*ReadImageFile)(unsigned int imgflags, const char *fname, qbyte *filedata, size_t filesize);
#define plugimageloaderfuncs_name "ImageLoader"
} plugimageloaderfuncs_t;
qboolean Image_RegisterLoader(void *module, plugimageloaderfuncs_t *loader);
#ifdef D3D8QUAKE
void D3D8_Set2D (void);
void D3D8_UpdateFiltering (image_t *imagelist, int filtermip[3], int filterpic[3], int mipcap[2], float anis);
qboolean D3D8_LoadTextureMips (texid_t tex, const struct pendingtextureinfo *mips);
void D3D8_DestroyTexture (texid_t tex);
#endif
#ifdef D3D9QUAKE
void D3D9_Set2D (void);
void D3D9_UpdateFiltering (image_t *imagelist, int filtermip[3], int filterpic[3], int mipcap[2], float lodbias, float anis);
qboolean D3D9_LoadTextureMips (texid_t tex, const struct pendingtextureinfo *mips);
void D3D9_DestroyTexture (texid_t tex);
#endif
#ifdef D3D11QUAKE
void D3D11_UpdateFiltering (image_t *imagelist, int filtermip[3], int filterpic[3], int mipcap[2], float lodbias, float anis);
qboolean D3D11_LoadTextureMips (texid_t tex, const struct pendingtextureinfo *mips);
void D3D11_DestroyTexture (texid_t tex);
#endif
//extern int image_width, image_height;
texid_t R_LoadReplacementTexture(const char *name, const char *subpath, unsigned int flags, void *lowres, int lowreswidth, int lowresheight, uploadfmt_t fmt);
texid_tf R_LoadHiResTexture(const char *name, const char *subpath, unsigned int flags);
texid_tf R_LoadBumpmapTexture(const char *name, const char *subpath);
void R_LoadNumberedLightTexture(struct dlight_s *dl, int cubetexnum);
extern texid_t particletexture;
extern texid_t particlecqtexture;
extern texid_t explosiontexture;
extern texid_t balltexture;
extern texid_t beamtexture;
extern texid_t ptritexture;
skinid_t Mod_RegisterSkinFile(const char *skinname);
skinid_t Mod_ReadSkinFile(const char *skinname, const char *skintext);
void Mod_WipeSkin(skinid_t id, qboolean force);
skinfile_t *Mod_LookupSkin(skinid_t id);
void Mod_Init (qboolean initial);
void Mod_Shutdown (qboolean final);
int Mod_TagNumForName(struct model_s *model, const char *name, int firsttag);
int Mod_SkinNumForName(struct model_s *model, int surfaceidx, const char *name);
int Mod_FrameNumForName(struct model_s *model, int surfaceidx, const char *name);
int Mod_FrameNumForAction(struct model_s *model, int surfaceidx, int actionid);
float Mod_GetFrameDuration(struct model_s *model, int surfaceidx, int frameno);
void Mod_ResortShaders(void);
void Mod_ClearAll (void);
struct model_s *Mod_FindName (const char *name);
void *Mod_Extradata (struct model_s *mod); // handles caching
void Mod_TouchModel (const char *name);
void Mod_RebuildLightmaps (void);
void Mod_NowLoadExternal(struct model_s *loadmodel);
void GLR_LoadSkys (void);
void R_BloomRegister(void);
int Mod_RegisterModelFormatText(void *module, const char *formatname, char *magictext, qboolean (QDECL *load) (struct model_s *mod, void *buffer, size_t fsize));
int Mod_RegisterModelFormatMagic(void *module, const char *formatname, qbyte *magic, size_t magicsize, qboolean (QDECL *load) (struct model_s *mod, void *buffer, size_t fsize));
void Mod_UnRegisterModelFormat(void *module, int idx);
void Mod_UnRegisterAllModelFormats(void *module);
void Mod_ModelLoaded(void *ctx, void *data, size_t a, size_t b);
void Mod_SubmodelLoaded(struct model_s *mod, int state);
#ifdef RUNTIMELIGHTING
struct relight_ctx_s;
struct llightinfo_s;
void LightPlane (struct relight_ctx_s *ctx, struct llightinfo_s *threadctx, lightstyleindex_t surf_styles[4], unsigned int *surf_expsamples, qbyte *surf_rgbsamples, qbyte *surf_deluxesamples, vec4_t surf_plane, vec4_t surf_texplanes[2], vec2_t exactmins, vec2_t exactmaxs, int texmins[2], int texsize[2], float lmscale); //special version that doesn't know what a face is or anything.
struct relight_ctx_s *LightStartup(struct relight_ctx_s *ctx, struct model_s *model, qboolean shadows, qboolean skiplit);
void LightReloadEntities(struct relight_ctx_s *ctx, const char *entstring, qboolean ignorestyles);
void LightShutdown(struct relight_ctx_s *ctx);
extern const size_t lightthreadctxsize;
qboolean RelightSetup (struct model_s *model, size_t lightsamples, qboolean generatelit);
void RelightThink (void);
const char *RelightGetProgress(float *progress); //reports filename and progress
void RelightTerminate(struct model_s *mod); //NULL acts as a wildcard
#endif
struct builddata_s
{
void (*buildfunc)(struct model_s *mod, struct msurface_s *surf, struct builddata_s *bd);
qboolean paintlightmaps;
void *facedata;
};
void Mod_Batches_Build(struct model_s *mod, struct builddata_s *bd);
shader_t *Mod_RegisterBasicShader(struct model_s *mod, const char *texname, unsigned int usageflags, const char *shadertext, uploadfmt_t pixelfmt, unsigned int width, unsigned int height, void *pixeldata, void *palettedata);
extern struct model_s *currentmodel;
void Media_CaptureDemoEnd(void);
void Media_RecordFrame (void);
qboolean Media_PausedDemo (qboolean fortiming);
int Media_Capturing (void);
double Media_TweekCaptureFrameTime(double oldtime, double time);
void Media_WriteCurrentTrack(sizebuf_t *buf);
void Media_VideoRestarting(void);
void Media_VideoRestarted(void);
void MYgluPerspective(double fovx, double fovy, double zNear, double zFar);
void R_PushDlights (void);
void R_SetFrustum (float projmat[16], float viewmat[16]);
void R_SetRenderer(rendererinfo_t *ri);
qboolean R_RegisterRenderer(void *module, rendererinfo_t *ri);
struct plugvrfuncs_s;
qboolean R_RegisterVRDriver(void *module, struct plugvrfuncs_s *vrfuncs);
qboolean R_UnRegisterModule(void *module);
void R_AnimateLight (void);
void R_UpdateHDR(vec3_t org);
void R_UpdateLightStyle(unsigned int style, const char *stylestring, float r, float g, float b);
void R_BumpLightstyles(unsigned int maxstyle); //bumps the cl_max_lightstyles array size, if needed.
qboolean R_CalcModelLighting(entity_t *e, struct model_s *clmodel);
struct texture_s *R_TextureAnimation (int frame, struct texture_s *base); //mostly deprecated, only lingers for rtlights so world only.
struct texture_s *R_TextureAnimation_Q2 (struct texture_s *base); //mostly deprecated, only lingers for rtlights so world only.
void RQ_Init(void);
void RQ_Shutdown(void);
qboolean WritePCXfile (const char *filename, enum fs_relative fsroot, qbyte *data, int width, int height, int rowbytes, qbyte *palette, qboolean upload); //data is 8bit.
qbyte *ReadPCXFile(qbyte *buf, int length, int *width, int *height);
void *ReadTargaFile(qbyte *buf, int length, int *width, int *height, uploadfmt_t *format, qboolean greyonly, uploadfmt_t forceformat);
qbyte *ReadPNGFile(const char *fname, qbyte *buf, int length, int *width, int *height, uploadfmt_t *format);
qbyte *ReadPCXPalette(qbyte *buf, int len, qbyte *out);
qbyte *ReadRawImageFile(qbyte *buf, int len, int *width, int *height, uploadfmt_t *format, qboolean force_rgba8, const char *fname);
void *Image_ResampleTexture (uploadfmt_t format, const void *in, int inwidth, int inheight, void *out, int outwidth, int outheight);
void Image_ReadExternalAlpha(qbyte *rgbadata, size_t imgwidth, size_t imgheight, const char *fname, uploadfmt_t *format);
void BoostGamma(qbyte *rgba, int width, int height, uploadfmt_t fmt);
void SaturateR8G8B8(qbyte *data, int size, float sat);
void AddOcranaLEDsIndexed (qbyte *image, int h, int w);
void Renderer_Init(void);
void Renderer_Start(void);
qboolean Renderer_Started(void);
void R_ShutdownRenderer(qboolean videotoo);
void R_RestartRenderer_f (void);//this goes here so we can save some stack when first initing the sw renderer.
//used to live in glquake.h
qbyte GetPaletteIndexRange(int first, int stop, int red, int green, int blue);
qbyte GetPaletteIndex(int red, int green, int blue);
extern cvar_t r_norefresh;
extern cvar_t r_drawentities;
extern cvar_t r_drawworld;
extern cvar_t r_drawviewmodel;
extern cvar_t r_drawviewmodelinvis;
extern cvar_t r_speeds;
extern cvar_t r_waterwarp;
extern cvar_t r_fullbright;
extern cvar_t r_lightmap;
extern cvar_t r_glsl_offsetmapping;
extern cvar_t r_skyfog; //additional fog alpha on sky
extern cvar_t r_shadow_playershadows;
extern cvar_t r_shadow_realtime_dlight, r_shadow_realtime_dlight_shadows;
extern cvar_t r_shadow_realtime_dlight_ambient;
extern cvar_t r_shadow_realtime_dlight_diffuse;
extern cvar_t r_shadow_realtime_dlight_specular;
extern cvar_t r_shadow_realtime_world, r_shadow_realtime_world_shadows, r_shadow_realtime_world_lightmaps, r_shadow_realtime_world_importlightentitiesfrommap;
extern float r_shadow_realtime_world_lightmaps_force;
extern cvar_t r_shadow_shadowmapping;
extern cvar_t r_mirroralpha;
extern cvar_t r_wateralpha;
extern cvar_t r_lavaalpha;
extern cvar_t r_slimealpha;
extern cvar_t r_telealpha;
extern cvar_t r_waterstyle;
extern cvar_t r_lavastyle;
extern cvar_t r_slimestyle;
extern cvar_t r_telestyle;
extern cvar_t r_dynamic;
extern cvar_t r_temporalscenecache;
extern cvar_t r_novis;
extern cvar_t r_netgraph;
extern cvar_t r_deluxemapping_cvar;
extern qboolean r_deluxemapping;
#ifdef RTLIGHTS
extern qboolean r_fakeshadows; //enables the use of ortho model-only shadows
#endif
extern float r_blobshadows;
extern cvar_t r_softwarebanding_cvar;
extern qboolean r_softwarebanding;
extern cvar_t r_lightprepass_cvar;
extern int r_lightprepass; //0=off,1=16bit,2=32bit
#ifdef R_XFLIP
extern cvar_t r_xflip;
#endif
extern cvar_t gl_mindist, gl_maxdist;
extern cvar_t r_clear;
extern cvar_t r_clearcolour;
extern cvar_t gl_poly;
extern cvar_t gl_affinemodels;
extern cvar_t r_renderscale;
extern cvar_t gl_nohwblend;
extern cvar_t r_coronas, r_coronas_intensity, r_coronas_occlusion, r_coronas_mindist, r_coronas_fadedist, r_flashblend, r_flashblendscale;
extern cvar_t r_lightstylesmooth;
extern cvar_t r_lightstylesmooth_limit;
extern cvar_t r_lightstylespeed;
extern cvar_t r_lightstylescale;
extern cvar_t r_lightmap_scale;
#ifdef QWSKINS
extern cvar_t gl_nocolors;
#endif
extern cvar_t gl_load24bit;
extern cvar_t gl_finish;
extern cvar_t gl_max_size;
extern cvar_t gl_playermip;
extern cvar_t r_lightmap_saturation;
extern cvar_t r_meshpitch;
extern cvar_t r_meshroll; //gah!
extern cvar_t vid_hardwaregamma;
enum {
RSPEED_TOTALREFRESH,
RSPEED_CSQCPHYSICS,
RSPEED_CSQCREDRAW,
RSPEED_LINKENTITIES,
RSPEED_WORLDNODE,
RSPEED_DYNAMIC,
RSPEED_OPAQUE,
RSPEED_RTLIGHTS,
RSPEED_TRANSPARENTS,
RSPEED_PROTOCOL,
RSPEED_PARTICLES,
RSPEED_PARTICLESDRAW,
RSPEED_PALETTEFLASHES,
RSPEED_2D,
RSPEED_SERVER,
RSPEED_SETUP,
RSPEED_SUBMIT,
RSPEED_PRESENT,
RSPEED_ACQUIRE,
RSPEED_MAX
};
extern int rspeeds[RSPEED_MAX];
enum {
RQUANT_MSECS, //old r_speeds
RQUANT_PRIMITIVEINDICIES,
RQUANT_DRAWS,
RQUANT_ENTBATCHES,
RQUANT_WORLDBATCHES,
RQUANT_2DBATCHES,
RQUANT_SHADOWINDICIES,
RQUANT_SHADOWEDGES,
RQUANT_SHADOWSIDES,
RQUANT_LITFACES,
RQUANT_RTLIGHT_DRAWN,
RQUANT_RTLIGHT_CULL_FRUSTUM,
RQUANT_RTLIGHT_CULL_PVS,
RQUANT_RTLIGHT_CULL_SCISSOR,
RQUANT_MAX
};
extern int rquant[RQUANT_MAX];
#define RQuantAdd(type,quant) rquant[type] += quant
#if 0//defined(NDEBUG) || !defined(_WIN32)
#define RSpeedLocals()
#define RSpeedMark()
#define RSpeedRemark()
#define RSpeedEnd(spt)
#else
#define RSpeedLocals() double rsp
#define RSpeedMark() double rsp = (r_speeds.ival>1)?Sys_DoubleTime()*1000000:0
#define RSpeedRemark() rsp = (r_speeds.ival>1)?Sys_DoubleTime()*1000000:0
#if defined(_WIN32) && defined(GLQUAKE)
extern void (_stdcall *qglFinish) (void);
#define RSpeedEnd(spt) do {if(r_speeds.ival > 1){if(r_speeds.ival > 2 && qglFinish)qglFinish(); rspeeds[spt] += (double)(Sys_DoubleTime()*1000000) - rsp;}}while (0)
#else
#define RSpeedEnd(spt) rspeeds[spt] += (r_speeds.ival>1)?Sys_DoubleTime()*1000000 - rsp:0
#endif
#endif
| 40.886108 | 384 | 0.775499 | [
"geometry",
"render",
"model",
"3d"
] |
cffee86b482ef2968f25350da2d7a18c86bff638 | 9,815 | h | C | open_spiel/games/leduc_poker_dummy.h | xiaohangt/open_spiel | 457dff794276599b4c7095db38579a052fb8404a | [
"Apache-2.0"
] | null | null | null | open_spiel/games/leduc_poker_dummy.h | xiaohangt/open_spiel | 457dff794276599b4c7095db38579a052fb8404a | [
"Apache-2.0"
] | null | null | null | open_spiel/games/leduc_poker_dummy.h | xiaohangt/open_spiel | 457dff794276599b4c7095db38579a052fb8404a | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 DeepMind Technologies Ltd. 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.
// A generalized version of a Leduc poker, a simple but non-trivial poker game
// described in http://poker.cs.ualberta.ca/publications/UAI05.pdf .
//
// Taken verbatim from the linked paper above: "In Leduc hold'em, the deck
// consists of two suits with three cards in each suit. There are two rounds.
// In the first round a single private card is dealt to each player. In the
// second round a single board card is revealed. There is a two-bet maximum,
// with raise amounts of 2 and 4 in the first and second round, respectively.
// Both players start the first round with 1 already in the pot.
//
// So the maximin sequence is of the form:
// private card player 0, private card player 1, [bets], public card, [bets]
//
// Parameters:
// "players" int number of players (default = 2)
// "action_mapping" bool regard all actions as legal and internally
// map otherwise illegal actions to check/call
// (default = false)
// "suit_isomorphism" bool player observations do not distinguish
// between cards of different suits with
// the same rank (default = false)
#ifndef OPEN_SPIEL_GAMES_LEDUC_POKER_DUMMY_H_
#define OPEN_SPIEL_GAMES_LEDUC_POKER_DUMMY_H_
#include <array>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "open_spiel/observer.h"
#include "open_spiel/policy.h"
#include "open_spiel/spiel.h"
namespace open_spiel {
namespace leduc_poker_dummy {
// Default parameters.
// TODO(b/127425075): Use std::optional instead of sentinel values once absl is
// added as a dependency.
inline constexpr int num_actions = 6;
inline constexpr int kInvalidCard = -10000;
inline constexpr int kDefaultPlayers = 2;
inline constexpr int kNumSuits = 2;
inline constexpr int kFirstRaiseAmount = 2;
inline constexpr int kSecondRaiseAmount = 4;
inline constexpr int kTotalRaisesPerRound = 2;
inline constexpr int kMaxRaises = 2;
inline constexpr int kStartingMoney = 100;
// Number of info states in the 2P game with default params.
inline constexpr int kNumInfoStates = 936;
class LeducDummyGame;
class LeducObserver;
enum ActionType { kFold = 0, kCall = 1, kRaise = 2, kLose = 3 };
class LeducDummyState : public State {
public:
explicit LeducDummyState(std::shared_ptr<const Game> game,
bool action_mapping, bool suit_isomorphism);
Player CurrentPlayer() const override;
std::string ActionToString(Player player, Action move) const override;
std::string ToString() const override;
bool IsTerminal() const override;
std::vector<double> Returns() const override;
std::string InformationStateString(Player player) const override;
std::string ObservationString(Player player) const override;
void InformationStateTensor(Player player,
absl::Span<float> values) const override;
void ObservationTensor(Player player,
absl::Span<float> values) const override;
std::unique_ptr<State> Clone() const override;
// The probability of taking each possible action in a particular info state.
std::vector<std::pair<Action, double>> ChanceOutcomes() const override;
// Additional methods
int round() const { return round_; }
int deck_size() const { return deck_size_; }
int public_card() const { return public_card_; }
int raises() const { return num_raises_; }
int private_card(Player player) const { return private_cards_[player]; }
std::vector<Action> LegalActions() const override;
// Returns a vector of MaxGameLength containing all of the betting actions
// taken so far. If the round has ended, the actions are kInvalidAction.
std::vector<int> padded_betting_sequence() const;
std::unique_ptr<State> ResampleFromInfostate(
int player_id, std::function<double()> rng) const override;
std::vector<Action> ActionsConsistentWithInformationFrom(
Action action) const override {
return {action};
}
protected:
// The meaning of `action_id` varies:
// - At decision nodes, one of ActionType::{kFold, kCall, kRaise, kLose}.
// - At a chance node, indicates the card to be dealt to the player or
// revealed publicly. The interpretation of each chance outcome depends on
// the number of players, but always follows:
// lowest value of first suit,
// lowest value of second suit,
// next lowest value of first suit,
// next lowest value of second suit,
// .
// .
// .
// highest value of first suit,
// highest value of second suit.
// So, e.g. in the two player case (6 cards): 0 = Jack1, 1 = Jack2,
// 2 = Queen1, ... , 5 = King2.
void DoApplyAction(Action move) override;
private:
friend class LeducObserver;
int NextPlayer() const;
void ResolveWinner();
bool ReadyForNextRound() const;
void NewRound();
int RankHand(Player player) const;
void SequenceAppendMove(int move);
void Ante(Player player, int amount);
void SetPrivate(Player player, Action move);
int NumObservableCards() const;
int MaxBetsPerRound() const;
// Fields sets to bad/invalid values. Use Game::NewInitialState().
Player cur_player_;
int num_calls_; // Number of calls this round (total, not per player).
int num_raises_; // Number of raises made in the round (not per player).
int round_; // Round number (1 or 2).
int stakes_; // The current 'level' of the bet.
int num_winners_; // Number of winning players.
int pot_; // Number of chips in the pot.
int public_card_; // The public card revealed after round 1.
int deck_size_; // Number of cards remaining; not equal deck_.size()
int private_cards_dealt_; // How many private cards currently dealt.
int remaining_players_; // Num. players still in (not folded).
// Is this player a winner? Indexed by pid.
std::vector<bool> winner_;
// Each player's single private card. Indexed by pid.
std::vector<int> private_cards_;
// Cards by value (0-6 for standard 2-player game, -1 if no longer in the
// deck.)
std::vector<int> deck_;
// How much money each player has, indexed by pid.
std::vector<double> money_;
// How much each player has contributed to the pot, indexed by pid.
std::vector<int> ante_;
// Flag for whether the player has folded, indexed by pid.
std::vector<bool> folded_;
// Sequence of actions for each round. Needed to report information state.
std::vector<int> round1_sequence_;
std::vector<int> round2_sequence_;
// Always regard all actions as legal, and internally map otherwise illegal
// actions to check/call.
bool action_mapping_;
// Players cannot distinguish between cards of different suits with the same
// rank.
bool suit_isomorphism_;
};
class LeducDummyGame : public Game {
public:
explicit LeducDummyGame(const GameParameters& params);
// CHANGED FROM 3
int NumDistinctActions() const override { return num_actions; }
std::unique_ptr<State> NewInitialState() const override;
int MaxChanceOutcomes() const override;
int NumPlayers() const override { return num_players_; }
double MinUtility() const override;
double MaxUtility() const override;
double UtilitySum() const override { return 0; }
std::vector<int> InformationStateTensorShape() const override;
std::vector<int> ObservationTensorShape() const override;
constexpr int MaxBetsPerRound() const {
// E.g. longest round for 4-player is 10 bets:
// check, check, check, bet, call, call, raise, call, call, call
// = 1 bet + 1 raise + (num_players_-1)*2 calls + (num_players_-2) calls
return 3 * num_players_ - 2;
}
int MaxGameLength() const override {
// 2 rounds.
return 2 * MaxBetsPerRound();
}
int MaxChanceNodesInHistory() const override { return 3; }
int NumObservableCards() const {
return suit_isomorphism_ ? total_cards_ / 2 : total_cards_;
}
std::string ActionToString(Player player, Action action) const override;
// New Observation API
std::shared_ptr<Observer> MakeObserver(
absl::optional<IIGObservationType> iig_obs_type,
const GameParameters& params) const override;
// Used to implement the old observation API.
std::shared_ptr<LeducObserver> default_observer_;
std::shared_ptr<LeducObserver> info_state_observer_;
private:
int num_players_; // Number of players.
int total_cards_; // Number of cards total cards in the game.
// Always regard all actions as legal, and internally map otherwise illegal
// actions to check/call.
bool action_mapping_;
// Players cannot distinguish between cards of different suits with the same
// rank.
bool suit_isomorphism_;
};
// Returns policy that always folds.
TabularPolicy GetAlwaysFoldPolicy(const Game& game);
// Returns policy that always calls.
TabularPolicy GetAlwaysCallPolicy(const Game& game);
// Returns policy that always raises.
TabularPolicy GetAlwaysRaisePolicy(const Game& game);
} // namespace leduc_poker
} // namespace open_spiel
#endif // OPEN_SPIEL_GAMES_LEDUC_POKER_DUMMY_H_
| 39.26 | 79 | 0.710443 | [
"vector"
] |
cfffeec426a3f2127b0e9e030bee669e62c2265c | 3,839 | h | C | code/addons/effects/effects/camerashakeeffect.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/addons/effects/effects/camerashakeeffect.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/addons/effects/effects/camerashakeeffect.h | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | #pragma once
//------------------------------------------------------------------------------
/**
@class EffectsFeature::CameraShakeEffect
A shake effect applies a shake shake to the world as long as it's alive.
The FX::CameraShakeMixer should calculate the final shake values
over all CameraShakeFX's and apply the modified transform to the current
camera
(C) 2005 Radon Labs GmbH
(C) 2013-2016 Individual contributors, see AUTHORS file
*/
#include "effect.h"
#include "math/vector.h"
//------------------------------------------------------------------------------
namespace EffectsFeature
{
class CameraShakeEffect : public Effect
{
__DeclareClass(CameraShakeEffect);
public:
/// constructor
CameraShakeEffect();
/// set range
void SetRange(float r);
/// get range
float GetRange() const;
/// set intensity
void SetIntensity(const Math::vector& i);
/// get intensity
const Math::vector& GetIntensity() const;
/// set additional rotation intensity
void SetRotation(const Math::vector& r);
/// get additional rotation intensity
const Math::vector& GetRotation() const;
/// set additional rotation intensity
void SetSpeed(float s);
/// get additional rotation intensity
float GetSpeed() const;
/// start the effect
virtual void OnStart(Timing::Time time);
/// trigger the effect
virtual void OnFrame(Timing::Time time);
/// get current intensity, valid after Update has been called
const Math::vector& GetCurrentIntensity() const;
/// get current rotation intensity, valid after Update has been called
const Math::vector& GetCurrentRotation() const;
private:
float range;
Math::vector intensity;
Math::vector rotation;
Math::vector curIntensity; // current intensity, updated by Trigger
Math::vector curRotation; // current rotation, updated by Trigger
float speed;
};
//------------------------------------------------------------------------------
/**
*/
inline
void
CameraShakeEffect::SetSpeed(float s)
{
this->speed = s;
}
//------------------------------------------------------------------------------
/**
*/
inline
float
CameraShakeEffect::GetSpeed() const
{
return this->speed;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
CameraShakeEffect::SetRange(float r)
{
this->range = r;
}
//------------------------------------------------------------------------------
/**
*/
inline
float
CameraShakeEffect::GetRange() const
{
return this->range;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
CameraShakeEffect::SetIntensity(const Math::vector& i)
{
this->intensity = i;
}
//------------------------------------------------------------------------------
/**
*/
inline
const Math::vector&
CameraShakeEffect::GetIntensity() const
{
return this->intensity;
}
//------------------------------------------------------------------------------
/**
*/
inline
const Math::vector&
CameraShakeEffect::GetCurrentIntensity() const
{
return this->curIntensity;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
CameraShakeEffect::SetRotation(const Math::vector& r)
{
this->rotation = r;
}
//------------------------------------------------------------------------------
/**
*/
inline
const Math::vector&
CameraShakeEffect::GetRotation() const
{
return this->rotation;
}
//------------------------------------------------------------------------------
/**
*/
inline
const Math::vector&
CameraShakeEffect::GetCurrentRotation() const
{
return this->curRotation;
}
}; // namespace FX
//------------------------------------------------------------------------------ | 22.988024 | 80 | 0.499349 | [
"vector",
"transform"
] |
3200f4d98192e53770ca034915a400bef5983352 | 2,425 | h | C | Source/inv.h | austinwagner/devilutionX | 7ce1deb51439475bbb4187854acd404573dd34f6 | [
"Unlicense"
] | null | null | null | Source/inv.h | austinwagner/devilutionX | 7ce1deb51439475bbb4187854acd404573dd34f6 | [
"Unlicense"
] | null | null | null | Source/inv.h | austinwagner/devilutionX | 7ce1deb51439475bbb4187854acd404573dd34f6 | [
"Unlicense"
] | null | null | null | /**
* @file inv.h
*
* Interface of player inventory.
*/
#pragma once
#include "items.h"
#include "player.h"
namespace devilution {
#ifdef __cplusplus
extern "C" {
#endif
typedef enum item_color {
// clang-format off
ICOL_WHITE = PAL16_YELLOW + 5,
ICOL_BLUE = PAL16_BLUE + 5,
ICOL_RED = PAL16_RED + 5,
// clang-format on
} item_color;
typedef struct InvXY {
Sint32 X;
Sint32 Y;
} InvXY;
extern bool invflag;
extern bool drawsbarflag;
extern const InvXY InvRect[73];
void FreeInvGFX();
void InitInv();
/**
* @brief Render the inventory panel to the given buffer.
*/
void DrawInv(CelOutputBuffer out);
void DrawInvBelt(CelOutputBuffer out);
bool AutoEquipEnabled(const PlayerStruct &player, const ItemStruct &item);
bool AutoEquip(int playerNumber, const ItemStruct &item, bool persistItem = true);
bool AutoPlaceItemInInventory(int playerNumber, const ItemStruct &item, bool persistItem = false);
bool AutoPlaceItemInInventorySlot(int playerNumber, int slotIndex, const ItemStruct &item, bool persistItem);
bool AutoPlaceItemInBelt(int playerNumber, const ItemStruct &item, bool persistItem = false);
bool GoldAutoPlace(int pnum);
void CheckInvSwap(int pnum, BYTE bLoc, int idx, WORD wCI, int seed, bool bId, uint32_t dwBuff);
void inv_update_rem_item(int pnum, BYTE iv);
void RemoveInvItem(int pnum, int iv);
void RemoveSpdBarItem(int pnum, int iv);
void CheckInvItem(bool isShiftHeld = false);
void CheckInvScrn(bool isShiftHeld);
void CheckItemStats(int pnum);
void InvGetItem(int pnum, ItemStruct *item, int ii);
void AutoGetItem(int pnum, ItemStruct *item, int ii);
int FindGetItem(int idx, WORD ci, int iseed);
void SyncGetItem(int x, int y, int idx, WORD ci, int iseed);
bool CanPut(int x, int y);
bool TryInvPut();
void DrawInvMsg(const char *msg);
int InvPutItem(int pnum, int x, int y);
int SyncPutItem(int pnum, int x, int y, int idx, WORD icreateinfo, int iseed, int Id, int dur, int mdur, int ch, int mch, int ivalue, DWORD ibuff, int to_hit, int max_dam, int min_str, int min_mag, int min_dex, int ac);
char CheckInvHLight();
void RemoveScroll(int pnum);
bool UseScroll();
void UseStaffCharge(int pnum);
bool UseStaff();
bool UseInvItem(int pnum, int cii);
void DoTelekinesis();
int CalculateGold(int pnum);
bool DropItemBeforeTrig();
/* data */
extern int AP2x2Tbl[10];
#ifdef __cplusplus
}
#endif
}
| 28.869048 | 220 | 0.726186 | [
"render"
] |
32054d071cd92edfdea9193c1577df9925ba1f11 | 1,335 | h | C | src/cytonLib/WeightFactory.h | arthurxlw/cytonNss | f56ba72ab22a9df3b19a0b995cc2115476203e21 | [
"Apache-2.0"
] | 1 | 2019-11-25T16:02:17.000Z | 2019-11-25T16:02:17.000Z | src/cytonLib/WeightFactory.h | arthurxlw/cytonNss | f56ba72ab22a9df3b19a0b995cc2115476203e21 | [
"Apache-2.0"
] | null | null | null | src/cytonLib/WeightFactory.h | arthurxlw/cytonNss | f56ba72ab22a9df3b19a0b995cc2115476203e21 | [
"Apache-2.0"
] | 2 | 2019-11-21T14:17:52.000Z | 2020-08-19T23:42:23.000Z | /*
Copyright 2018 XIAOLIN WANG
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 _CYTONLIB_WEIGHTFACTORY_H_
#define _CYTONLIB_WEIGHTFACTORY_H_
#include "Weight.h"
namespace cytonLib {
class WeightFactory
{
public:
vector<Weight*> weights;
Weight whole;
bool optSgd;
DevMatPrec dWeight;
bool optAdam;
DevMatPrec momentum;
DevMatPrec gradientVariance;
Precision adamGamma;
Precision adamGamma2;
Precision adamEpsilon;
WeightFactory()
{
optSgd=false;
optAdam=false;
}
void init(const string& method);
void create(Weight& weight, string tag, int ni, int nj);
void alloc(Precision clipGradient);
void clearGrad();
void update(Precision lambda);
void save(const string& fileName);
void load(const string& fileName);
};
extern WeightFactory weightFactory;
} /* namespace cytonLib */
#endif /* WEIGHTFACTORY_H_ */
| 19.925373 | 72 | 0.765543 | [
"vector"
] |
32065e403510022a82746ab28a0173d1d4d8e5fc | 7,231 | h | C | dlc/include/tencentcloud/dlc/v20210125/model/Script.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | dlc/include/tencentcloud/dlc/v20210125/model/Script.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | dlc/include/tencentcloud/dlc/v20210125/model/Script.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_DLC_V20210125_MODEL_SCRIPT_H_
#define TENCENTCLOUD_DLC_V20210125_MODEL_SCRIPT_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Dlc
{
namespace V20210125
{
namespace Model
{
/**
* script实例。
*/
class Script : public AbstractModel
{
public:
Script();
~Script() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取脚本Id,长度36字节。
注意:此字段可能返回 null,表示取不到有效值。
* @return ScriptId 脚本Id,长度36字节。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetScriptId() const;
/**
* 设置脚本Id,长度36字节。
注意:此字段可能返回 null,表示取不到有效值。
* @param ScriptId 脚本Id,长度36字节。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetScriptId(const std::string& _scriptId);
/**
* 判断参数 ScriptId 是否已赋值
* @return ScriptId 是否已赋值
*/
bool ScriptIdHasBeenSet() const;
/**
* 获取脚本名称,长度0-25。
注意:此字段可能返回 null,表示取不到有效值。
* @return ScriptName 脚本名称,长度0-25。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetScriptName() const;
/**
* 设置脚本名称,长度0-25。
注意:此字段可能返回 null,表示取不到有效值。
* @param ScriptName 脚本名称,长度0-25。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetScriptName(const std::string& _scriptName);
/**
* 判断参数 ScriptName 是否已赋值
* @return ScriptName 是否已赋值
*/
bool ScriptNameHasBeenSet() const;
/**
* 获取脚本描述,长度0-50。
注意:此字段可能返回 null,表示取不到有效值。
* @return ScriptDesc 脚本描述,长度0-50。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetScriptDesc() const;
/**
* 设置脚本描述,长度0-50。
注意:此字段可能返回 null,表示取不到有效值。
* @param ScriptDesc 脚本描述,长度0-50。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetScriptDesc(const std::string& _scriptDesc);
/**
* 判断参数 ScriptDesc 是否已赋值
* @return ScriptDesc 是否已赋值
*/
bool ScriptDescHasBeenSet() const;
/**
* 获取默认关联数据库。
注意:此字段可能返回 null,表示取不到有效值。
* @return DatabaseName 默认关联数据库。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetDatabaseName() const;
/**
* 设置默认关联数据库。
注意:此字段可能返回 null,表示取不到有效值。
* @param DatabaseName 默认关联数据库。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetDatabaseName(const std::string& _databaseName);
/**
* 判断参数 DatabaseName 是否已赋值
* @return DatabaseName 是否已赋值
*/
bool DatabaseNameHasBeenSet() const;
/**
* 获取SQL描述,长度0-10000。
注意:此字段可能返回 null,表示取不到有效值。
* @return SQLStatement SQL描述,长度0-10000。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetSQLStatement() const;
/**
* 设置SQL描述,长度0-10000。
注意:此字段可能返回 null,表示取不到有效值。
* @param SQLStatement SQL描述,长度0-10000。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetSQLStatement(const std::string& _sQLStatement);
/**
* 判断参数 SQLStatement 是否已赋值
* @return SQLStatement 是否已赋值
*/
bool SQLStatementHasBeenSet() const;
/**
* 获取更新时间戳, 单位:ms。
注意:此字段可能返回 null,表示取不到有效值。
* @return UpdateTime 更新时间戳, 单位:ms。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t GetUpdateTime() const;
/**
* 设置更新时间戳, 单位:ms。
注意:此字段可能返回 null,表示取不到有效值。
* @param UpdateTime 更新时间戳, 单位:ms。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetUpdateTime(const int64_t& _updateTime);
/**
* 判断参数 UpdateTime 是否已赋值
* @return UpdateTime 是否已赋值
*/
bool UpdateTimeHasBeenSet() const;
private:
/**
* 脚本Id,长度36字节。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_scriptId;
bool m_scriptIdHasBeenSet;
/**
* 脚本名称,长度0-25。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_scriptName;
bool m_scriptNameHasBeenSet;
/**
* 脚本描述,长度0-50。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_scriptDesc;
bool m_scriptDescHasBeenSet;
/**
* 默认关联数据库。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_databaseName;
bool m_databaseNameHasBeenSet;
/**
* SQL描述,长度0-10000。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_sQLStatement;
bool m_sQLStatementHasBeenSet;
/**
* 更新时间戳, 单位:ms。
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t m_updateTime;
bool m_updateTimeHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_DLC_V20210125_MODEL_SCRIPT_H_
| 31.168103 | 116 | 0.46356 | [
"vector",
"model"
] |
32080551059f00a0010962d6e7f2df9125853a42 | 48,463 | c | C | output/outmacho.c | dlundqvist/nam | 0b71bbf5b6b9a2c2c3f116a86a928699a83c9515 | [
"BSD-2-Clause"
] | 1 | 2020-12-11T22:11:09.000Z | 2020-12-11T22:11:09.000Z | output/outmacho.c | dlundqvist/nasm | 0b71bbf5b6b9a2c2c3f116a86a928699a83c9515 | [
"BSD-2-Clause"
] | null | null | null | output/outmacho.c | dlundqvist/nasm | 0b71bbf5b6b9a2c2c3f116a86a928699a83c9515 | [
"BSD-2-Clause"
] | null | null | null | /* ----------------------------------------------------------------------- *
*
* Copyright 1996-2016 The NASM Authors - All Rights Reserved
* See the file AUTHORS included with the NASM distribution for
* the specific copyright holders.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ----------------------------------------------------------------------- */
/*
* outmacho.c output routines for the Netwide Assembler to produce
* NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X object files
*/
#include "compiler.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "nasm.h"
#include "nasmlib.h"
#include "saa.h"
#include "raa.h"
#include "rbtree.h"
#include "outform.h"
#include "outlib.h"
#if defined(OF_MACHO) || defined(OF_MACHO64)
/* Mach-O in-file header structure sizes */
#define MACHO_HEADER_SIZE 28
#define MACHO_SEGCMD_SIZE 56
#define MACHO_SECTCMD_SIZE 68
#define MACHO_SYMCMD_SIZE 24
#define MACHO_NLIST_SIZE 12
#define MACHO_RELINFO_SIZE 8
#define MACHO_HEADER64_SIZE 32
#define MACHO_SEGCMD64_SIZE 72
#define MACHO_SECTCMD64_SIZE 80
#define MACHO_NLIST64_SIZE 16
/* Mach-O file header values */
#define MH_MAGIC 0xfeedface
#define MH_MAGIC_64 0xfeedfacf
#define CPU_TYPE_I386 7 /* x86 platform */
#define CPU_TYPE_X86_64 0x01000007 /* x86-64 platform */
#define CPU_SUBTYPE_I386_ALL 3 /* all-x86 compatible */
#define MH_OBJECT 0x1 /* object file */
/* Mach-O load commands */
#define LC_SEGMENT 0x1 /* 32-bit segment load cmd */
#define LC_SEGMENT_64 0x19 /* 64-bit segment load cmd */
#define LC_SYMTAB 0x2 /* symbol table load command */
/* Mach-O relocations numbers */
/* Generic relocs, used by i386 Mach-O */
#define GENERIC_RELOC_VANILLA 0 /* Generic relocation */
#define GENERIC_RELOC_TLV 5 /* Thread local */
#define X86_64_RELOC_UNSIGNED 0 /* Absolute address */
#define X86_64_RELOC_SIGNED 1 /* Signed 32-bit disp */
#define X86_64_RELOC_BRANCH 2 /* CALL/JMP with 32-bit disp */
#define X86_64_RELOC_GOT_LOAD 3 /* MOVQ of GOT entry */
#define X86_64_RELOC_GOT 4 /* Different GOT entry */
#define X86_64_RELOC_SUBTRACTOR 5 /* Subtracting two symbols */
#define X86_64_RELOC_SIGNED_1 6 /* SIGNED with -1 addend */
#define X86_64_RELOC_SIGNED_2 7 /* SIGNED with -2 addend */
#define X86_64_RELOC_SIGNED_4 8 /* SIGNED with -4 addend */
#define X86_64_RELOC_TLV 9 /* Thread local */
/* Mach-O VM permission constants */
#define VM_PROT_NONE (0x00)
#define VM_PROT_READ (0x01)
#define VM_PROT_WRITE (0x02)
#define VM_PROT_EXECUTE (0x04)
#define VM_PROT_DEFAULT (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
#define VM_PROT_ALL (VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
/* Our internal relocation types */
enum reltype {
RL_ABS, /* Absolute relocation */
RL_REL, /* Relative relocation */
RL_TLV, /* Thread local */
RL_BRANCH, /* Relative direct branch */
RL_SUB, /* X86_64_RELOC_SUBTRACT */
RL_GOT, /* X86_64_RELOC_GOT */
RL_GOTLOAD /* X86_64_RELOC_GOT_LOAD */
};
#define RL_MAX_32 RL_TLV
#define RL_MAX_64 RL_GOTLOAD
struct macho_fmt {
uint32_t ptrsize; /* Pointer size in bytes */
uint32_t mh_magic; /* Which magic number to use */
uint32_t cpu_type; /* Which CPU type */
uint32_t lc_segment; /* Which segment load command */
uint32_t header_size; /* Header size */
uint32_t segcmd_size; /* Segment command size */
uint32_t sectcmd_size; /* Section command size */
uint32_t nlist_size; /* Nlist (symbol) size */
enum reltype maxreltype; /* Maximum entry in enum reltype permitted */
uint32_t reloc_abs; /* Absolute relocation type */
uint32_t reloc_rel; /* Relative relocation type */
uint32_t reloc_tlv; /* Thread local relocation type */
};
static struct macho_fmt fmt;
static void fwriteptr(uint64_t data, FILE * fp)
{
fwriteaddr(data, fmt.ptrsize, fp);
}
struct section {
/* nasm internal data */
struct section *next;
struct SAA *data;
int32_t index;
int32_t fileindex;
struct reloc *relocs;
struct rbtree *gsyms; /* Global symbols in section */
int align;
bool by_name; /* This section was specified by full MachO name */
/* data that goes into the file */
char sectname[16]; /* what this section is called */
char segname[16]; /* segment this section will be in */
uint64_t addr; /* in-memory address (subject to alignment) */
uint64_t size; /* in-memory and -file size */
uint64_t offset; /* in-file offset */
uint32_t pad; /* padding bytes before section */
uint32_t nreloc; /* relocation entry count */
uint32_t flags; /* type and attributes (masked) */
uint32_t extreloc; /* external relocations */
};
#define SECTION_TYPE 0x000000ff /* section type mask */
#define S_REGULAR (0x0) /* standard section */
#define S_ZEROFILL (0x1) /* zerofill, in-memory only */
#define SECTION_ATTRIBUTES_SYS 0x00ffff00 /* system setable attributes */
#define S_ATTR_SOME_INSTRUCTIONS 0x00000400 /* section contains some
machine instructions */
#define S_ATTR_EXT_RELOC 0x00000200 /* section has external
relocation entries */
#define S_ATTR_LOC_RELOC 0x00000100 /* section has local
relocation entries */
#define S_ATTR_PURE_INSTRUCTIONS 0x80000000 /* section uses pure
machine instructions */
/* Fake section for absolute symbols, *not* part of the section linked list */
static struct section absolute_sect;
static const struct sectmap {
const char *nasmsect;
const char *segname;
const char *sectname;
const int32_t flags;
} sectmap[] = {
{".text", "__TEXT", "__text", S_REGULAR|S_ATTR_SOME_INSTRUCTIONS|S_ATTR_PURE_INSTRUCTIONS},
{".data", "__DATA", "__data", S_REGULAR},
{".rodata", "__DATA", "__const", S_REGULAR},
{".bss", "__DATA", "__bss", S_ZEROFILL},
{NULL, NULL, NULL, 0}
};
struct reloc {
/* nasm internal data */
struct reloc *next;
/* data that goes into the file */
int32_t addr; /* op's offset in section */
uint32_t snum:24, /* contains symbol index if
** ext otherwise in-file
** section number */
pcrel:1, /* relative relocation */
length:2, /* 0=byte, 1=word, 2=int32_t, 3=int64_t */
ext:1, /* external symbol referenced */
type:4; /* reloc type */
};
#define R_ABS 0 /* absolute relocation */
#define R_SCATTERED 0x80000000 /* reloc entry is scattered if
** highest bit == 1 */
struct symbol {
/* nasm internal data */
struct rbtree symv; /* Global symbol rbtree; "key" contains the
symbol offset. */
struct symbol *next; /* next symbol in the list */
char *name; /* name of this symbol */
int32_t initial_snum; /* symbol number used above in reloc */
int32_t snum; /* true snum for reloc */
/* data that goes into the file */
uint32_t strx; /* string table index */
uint8_t type; /* symbol type */
uint8_t sect; /* NO_SECT or section number */
uint16_t desc; /* for stab debugging, 0 for us */
};
/* symbol type bits */
#define N_EXT 0x01 /* global or external symbol */
#define N_UNDF 0x0 /* undefined symbol | n_sect == */
#define N_ABS 0x2 /* absolute symbol | NO_SECT */
#define N_SECT 0xe /* defined symbol, n_sect holds
** section number */
#define N_TYPE 0x0e /* type bit mask */
#define DEFAULT_SECTION_ALIGNMENT 0 /* byte (i.e. no) alignment */
/* special section number values */
#define NO_SECT 0 /* no section, invalid */
#define MAX_SECT 255 /* maximum number of sections */
static struct section *sects, **sectstail, **sectstab;
static struct symbol *syms, **symstail;
static uint32_t nsyms;
/* These variables are set by macho_layout_symbols() to organize
the symbol table and string table in order the dynamic linker
expects. They are then used in macho_write() to put out the
symbols and strings in that order.
The order of the symbol table is:
local symbols
defined external symbols (sorted by name)
undefined external symbols (sorted by name)
The order of the string table is:
strings for external symbols
strings for local symbols
*/
static uint32_t ilocalsym = 0;
static uint32_t iextdefsym = 0;
static uint32_t iundefsym = 0;
static uint32_t nlocalsym;
static uint32_t nextdefsym;
static uint32_t nundefsym;
static struct symbol **extdefsyms = NULL;
static struct symbol **undefsyms = NULL;
static struct RAA *extsyms;
static struct SAA *strs;
static uint32_t strslen;
/* Global file information. This should be cleaned up into either
a structure or as function arguments. */
static uint32_t head_ncmds = 0;
static uint32_t head_sizeofcmds = 0;
static uint64_t seg_filesize = 0;
static uint64_t seg_vmsize = 0;
static uint32_t seg_nsects = 0;
static uint64_t rel_padcnt = 0;
#define xstrncpy(xdst, xsrc) \
memset(xdst, '\0', sizeof(xdst)); /* zero out whole buffer */ \
strncpy(xdst, xsrc, sizeof(xdst)); /* copy over string */ \
xdst[sizeof(xdst) - 1] = '\0'; /* proper null-termination */
#define alignint32_t(x) \
ALIGN(x, sizeof(int32_t)) /* align x to int32_t boundary */
#define alignint64_t(x) \
ALIGN(x, sizeof(int64_t)) /* align x to int64_t boundary */
#define alignptr(x) \
ALIGN(x, fmt.ptrsize) /* align x to output format width */
static struct section *get_section_by_name(const char *segname,
const char *sectname)
{
struct section *s;
for (s = sects; s != NULL; s = s->next)
if (!strcmp(s->segname, segname) && !strcmp(s->sectname, sectname))
break;
return s;
}
static struct section *get_section_by_index(const int32_t index)
{
struct section *s;
for (s = sects; s != NULL; s = s->next)
if (index == s->index)
break;
return s;
}
/*
* Special section numbers which are used to define Mach-O special
* symbols, which can be used with WRT to provide PIC relocation
* types.
*/
static int32_t macho_tlvp_sect;
static int32_t macho_gotpcrel_sect;
static void macho_init(void)
{
sects = NULL;
sectstail = §s;
/* Fake section for absolute symbols */
absolute_sect.index = NO_SEG;
syms = NULL;
symstail = &syms;
nsyms = 0;
nlocalsym = 0;
nextdefsym = 0;
nundefsym = 0;
extsyms = raa_init();
strs = saa_init(1L);
/* string table starts with a zero byte so index 0 is an empty string */
saa_wbytes(strs, zero_buffer, 1);
strslen = 1;
/* add special symbol for TLVP */
macho_tlvp_sect = seg_alloc() + 1;
define_label("..tlvp", macho_tlvp_sect, 0L, NULL, false, false);
}
static void sect_write(struct section *sect,
const uint8_t *data, uint32_t len)
{
saa_wbytes(sect->data, data, len);
sect->size += len;
}
/*
* Find a suitable global symbol for a ..gotpcrel or ..tlvp reference
*/
static struct symbol *macho_find_gsym(struct section *s,
uint64_t offset, bool exact)
{
struct rbtree *srb;
srb = rb_search(s->gsyms, offset);
if (!srb || (exact && srb->key != offset)) {
nasm_error(ERR_NONFATAL, "unable to find a suitable %s symbol"
" for this reference",
s == &absolute_sect ? "absolute" : "global");
return NULL;
}
return container_of(srb, struct symbol, symv);
}
static int64_t add_reloc(struct section *sect, int32_t section,
int64_t offset,
enum reltype reltype, int bytes)
{
struct reloc *r;
struct section *s;
int32_t fi;
int64_t adjust;
/* Double check this is a valid relocation type for this platform */
nasm_assert(reltype <= fmt.maxreltype);
/* the current end of the section will be the symbol's address for
** now, might have to be fixed by macho_fixup_relocs() later on. make
** sure we don't make the symbol scattered by setting the highest
** bit by accident */
r = nasm_malloc(sizeof(struct reloc));
r->addr = sect->size & ~R_SCATTERED;
r->ext = 1;
adjust = bytes;
/* match byte count 1, 2, 4, 8 to length codes 0, 1, 2, 3 respectively */
r->length = ilog2_32(bytes);
/* set default relocation values */
r->type = fmt.reloc_abs;
r->pcrel = 0;
r->snum = R_ABS;
s = NULL;
if (section != NO_SEG)
s = get_section_by_index(section);
fi = s ? s->fileindex : NO_SECT;
/* absolute relocation */
switch (reltype) {
case RL_ABS:
if (section == NO_SEG) {
/* absolute (can this even happen?) */
r->ext = 0;
r->snum = R_ABS;
} else if (fi == NO_SECT) {
/* external */
r->snum = raa_read(extsyms, section);
} else {
/* local */
r->ext = 0;
r->snum = fi;
adjust = -sect->size;
}
break;
case RL_REL:
case RL_BRANCH:
r->type = fmt.reloc_rel;
r->pcrel = 1;
if (section == NO_SEG) {
/* absolute - seems to produce garbage no matter what */
nasm_error(ERR_NONFATAL, "Mach-O does not support relative "
"references to absolute addresses");
goto bail;
#if 0
/* This "seems" to be how it ought to work... */
struct symbol *sym = macho_find_gsym(&absolute_sect,
offset, false);
if (!sym)
goto bail;
sect->extreloc = 1;
r->snum = NO_SECT;
adjust = -sect->size;
#endif
} else if (fi == NO_SECT) {
/* external */
sect->extreloc = 1;
r->snum = raa_read(extsyms, section);
if (reltype == RL_BRANCH)
r->type = X86_64_RELOC_BRANCH;
else if (r->type == GENERIC_RELOC_VANILLA)
adjust = -sect->size;
} else {
/* local */
r->ext = 0;
r->snum = fi;
adjust = -sect->size;
}
break;
case RL_SUB:
r->pcrel = 0;
r->type = X86_64_RELOC_SUBTRACTOR;
break;
case RL_GOT:
r->type = X86_64_RELOC_GOT;
goto needsym;
case RL_GOTLOAD:
r->type = X86_64_RELOC_GOT_LOAD;
goto needsym;
case RL_TLV:
r->type = fmt.reloc_tlv;
goto needsym;
needsym:
r->pcrel = 1;
if (section == NO_SEG) {
nasm_error(ERR_NONFATAL, "Unsupported use of use of WRT");
} else if (fi == NO_SECT) {
/* external */
r->snum = raa_read(extsyms, section);
} else {
/* internal */
struct symbol *sym = macho_find_gsym(s, offset, reltype != RL_TLV);
if (!sym)
goto bail;
r->snum = sym->initial_snum;
}
break;
}
/* NeXT as puts relocs in reversed order (address-wise) into the
** files, so we do the same, doesn't seem to make much of a
** difference either way */
r->next = sect->relocs;
sect->relocs = r;
if (r->ext)
sect->extreloc = 1;
++sect->nreloc;
return adjust;
bail:
nasm_free(r);
return 0;
}
static void macho_output(int32_t secto, const void *data,
enum out_type type, uint64_t size,
int32_t section, int32_t wrt)
{
struct section *s;
int64_t addr, offset;
uint8_t mydata[16], *p;
bool is_bss;
enum reltype reltype;
if (secto == NO_SEG) {
if (type != OUT_RESERVE)
nasm_error(ERR_NONFATAL, "attempt to assemble code in "
"[ABSOLUTE] space");
return;
}
s = get_section_by_index(secto);
if (s == NULL) {
nasm_error(ERR_WARNING, "attempt to assemble code in"
" section %d: defaulting to `.text'", secto);
s = get_section_by_name("__TEXT", "__text");
/* should never happen */
if (s == NULL)
nasm_panic(0, "text section not found");
}
is_bss = (s->flags & SECTION_TYPE) == S_ZEROFILL;
if (is_bss && type != OUT_RESERVE) {
nasm_error(ERR_WARNING, "attempt to initialize memory in "
"BSS section: ignored");
s->size += realsize(type, size);
return;
}
memset(mydata, 0, sizeof(mydata));
switch (type) {
case OUT_RESERVE:
if (!is_bss) {
nasm_error(ERR_WARNING, "uninitialized space declared in"
" %s,%s section: zeroing", s->segname, s->sectname);
sect_write(s, NULL, size);
} else
s->size += size;
break;
case OUT_RAWDATA:
if (section != NO_SEG)
nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
sect_write(s, data, size);
break;
case OUT_ADDRESS:
{
int asize = abs((int)size);
addr = *(int64_t *)data;
if (section != NO_SEG) {
if (section % 2) {
nasm_error(ERR_NONFATAL, "Mach-O format does not support"
" section base references");
} else if (wrt == NO_SEG) {
if (fmt.ptrsize == 8 && asize != 8) {
nasm_error(ERR_NONFATAL,
"Mach-O 64-bit format does not support"
" 32-bit absolute addresses");
} else {
add_reloc(s, section, addr, RL_ABS, asize);
}
} else {
nasm_error(ERR_NONFATAL, "Mach-O format does not support"
" this use of WRT");
}
}
p = mydata;
WRITEADDR(p, addr, asize);
sect_write(s, mydata, asize);
break;
}
case OUT_REL2ADR:
nasm_assert(section != secto);
p = mydata;
offset = *(int64_t *)data;
addr = offset - size;
if (section != NO_SEG && section % 2) {
nasm_error(ERR_NONFATAL, "Mach-O format does not support"
" section base references");
} else if (fmt.ptrsize == 8) {
nasm_error(ERR_NONFATAL, "Unsupported non-32-bit"
" Macho-O relocation [2]");
} else if (wrt != NO_SEG) {
nasm_error(ERR_NONFATAL, "Mach-O format does not support"
" this use of WRT");
wrt = NO_SEG; /* we can at least _try_ to continue */
} else {
addr += add_reloc(s, section, addr+size, RL_REL, 2);
}
WRITESHORT(p, addr);
sect_write(s, mydata, 2);
break;
case OUT_REL4ADR:
nasm_assert(section != secto);
p = mydata;
offset = *(int64_t *)data;
addr = offset - size;
reltype = RL_REL;
if (section != NO_SEG && section % 2) {
nasm_error(ERR_NONFATAL, "Mach-O format does not support"
" section base references");
} else if (wrt == NO_SEG) {
if (fmt.ptrsize == 8 &&
(s->flags & S_ATTR_SOME_INSTRUCTIONS)) {
uint8_t opcode[2];
opcode[0] = opcode[1] = 0;
/* HACK: Retrieve instruction opcode */
if (likely(s->data->datalen >= 2)) {
saa_fread(s->data, s->data->datalen-2, opcode, 2);
} else if (s->data->datalen == 1) {
saa_fread(s->data, 0, opcode+1, 1);
}
if ((opcode[0] != 0x0f && (opcode[1] & 0xfe) == 0xe8) ||
(opcode[0] == 0x0f && (opcode[1] & 0xf0) == 0x80)) {
/* Direct call, jmp, or jcc */
reltype = RL_BRANCH;
}
}
} else if (wrt == macho_gotpcrel_sect) {
reltype = RL_GOT;
if ((s->flags & S_ATTR_SOME_INSTRUCTIONS) &&
s->data->datalen >= 3) {
uint8_t gotload[3];
/* HACK: Retrieve instruction opcode */
saa_fread(s->data, s->data->datalen-3, gotload, 3);
if ((gotload[0] & 0xf8) == 0x48 &&
gotload[1] == 0x8b &&
(gotload[2] & 0307) == 0005) {
/* movq <reg>,[rel sym wrt ..gotpcrel] */
reltype = RL_GOTLOAD;
}
}
} else if (wrt == macho_tlvp_sect) {
reltype = RL_TLV;
} else {
nasm_error(ERR_NONFATAL, "Mach-O format does not support"
" this use of WRT");
/* continue with RL_REL */
}
addr += add_reloc(s, section, offset, reltype, 4);
WRITELONG(p, addr);
sect_write(s, mydata, 4);
break;
default:
nasm_error(ERR_NONFATAL, "Unrepresentable relocation in Mach-O");
break;
}
}
static int32_t macho_section(char *name, int pass, int *bits)
{
char *sectionAttributes;
const struct sectmap *sm;
struct section *s;
const char *section, *segment;
uint32_t flags;
char *currentAttribute;
char *comma;
bool new_seg;
(void)pass;
/* Default to the appropriate number of bits. */
if (!name) {
*bits = fmt.ptrsize << 3;
name = ".text";
sectionAttributes = NULL;
} else {
sectionAttributes = name;
name = nasm_strsep(§ionAttributes, " \t");
}
section = segment = NULL;
flags = 0;
comma = strchr(name, ',');
if (comma) {
int len;
*comma = '\0';
segment = name;
section = comma+1;
len = strlen(segment);
if (len == 0) {
nasm_error(ERR_NONFATAL, "empty segment name\n");
} else if (len >= 16) {
nasm_error(ERR_NONFATAL, "segment name %s too long\n", segment);
}
len = strlen(section);
if (len == 0) {
nasm_error(ERR_NONFATAL, "empty section name\n");
} else if (len >= 16) {
nasm_error(ERR_NONFATAL, "section name %s too long\n", section);
}
if (!strcmp(section, "__text")) {
flags = S_REGULAR | S_ATTR_SOME_INSTRUCTIONS |
S_ATTR_PURE_INSTRUCTIONS;
} else if (!strcmp(section, "__bss")) {
flags = S_ZEROFILL;
} else {
flags = S_REGULAR;
}
} else {
for (sm = sectmap; sm->nasmsect != NULL; ++sm) {
/* make lookup into section name translation table */
if (!strcmp(name, sm->nasmsect)) {
segment = sm->segname;
section = sm->sectname;
flags = sm->flags;
goto found;
}
}
nasm_error(ERR_NONFATAL, "unknown section name\n");
return NO_SEG;
}
found:
/* try to find section with that name */
s = get_section_by_name(segment, section);
/* create it if it doesn't exist yet */
if (!s) {
new_seg = true;
s = *sectstail = nasm_zalloc(sizeof(struct section));
sectstail = &s->next;
s->data = saa_init(1L);
s->index = seg_alloc();
s->fileindex = ++seg_nsects;
s->align = -1;
s->pad = -1;
s->offset = -1;
s->by_name = false;
xstrncpy(s->segname, segment);
xstrncpy(s->sectname, section);
s->size = 0;
s->nreloc = 0;
s->flags = flags;
} else {
new_seg = false;
}
if (comma)
*comma = ','; /* Restore comma */
s->by_name = s->by_name || comma; /* Was specified by name */
flags = (uint32_t)-1;
while ((NULL != sectionAttributes)
&& (currentAttribute = nasm_strsep(§ionAttributes, " \t"))) {
if (0 != *currentAttribute) {
if (!nasm_strnicmp("align=", currentAttribute, 6)) {
char *end;
int newAlignment, value;
value = strtoul(currentAttribute + 6, (char**)&end, 0);
newAlignment = alignlog2_32(value);
if (0 != *end) {
nasm_error(ERR_NONFATAL,
"unknown or missing alignment value \"%s\" "
"specified for section \"%s\"",
currentAttribute + 6,
name);
} else if (0 > newAlignment) {
nasm_error(ERR_NONFATAL,
"alignment of %d (for section \"%s\") is not "
"a power of two",
value,
name);
}
if (s->align < newAlignment)
s->align = newAlignment;
} else if (!nasm_stricmp("data", currentAttribute)) {
flags = S_REGULAR;
} else if (!nasm_stricmp("code", currentAttribute) ||
!nasm_stricmp("text", currentAttribute)) {
flags = S_REGULAR | S_ATTR_SOME_INSTRUCTIONS |
S_ATTR_PURE_INSTRUCTIONS;
} else if (!nasm_stricmp("mixed", currentAttribute)) {
flags = S_REGULAR | S_ATTR_SOME_INSTRUCTIONS;
} else if (!nasm_stricmp("bss", currentAttribute)) {
flags = S_ZEROFILL;
} else {
nasm_error(ERR_NONFATAL,
"unknown section attribute %s for section %s",
currentAttribute,
name);
}
}
if (flags != (uint32_t)-1) {
if (!new_seg && s->flags != flags) {
nasm_error(ERR_NONFATAL,
"inconsistent section attributes for section %s\n",
name);
} else {
s->flags = flags;
}
}
}
return s->index;
}
static void macho_symdef(char *name, int32_t section, int64_t offset,
int is_global, char *special)
{
struct symbol *sym;
if (special) {
nasm_error(ERR_NONFATAL, "The Mach-O output format does "
"not support any special symbol types");
return;
}
if (is_global == 3) {
nasm_error(ERR_NONFATAL, "The Mach-O format does not "
"(yet) support forward reference fixups.");
return;
}
if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
/*
* This is a NASM special symbol. We never allow it into
* the Macho-O symbol table, even if it's a valid one. If it
* _isn't_ a valid one, we should barf immediately.
*/
if (strcmp(name, "..gotpcrel") && strcmp(name, "..tlvp"))
nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
return;
}
sym = *symstail = nasm_zalloc(sizeof(struct symbol));
sym->next = NULL;
symstail = &sym->next;
sym->name = name;
sym->strx = strslen;
sym->type = 0;
sym->desc = 0;
sym->symv.key = offset;
sym->initial_snum = -1;
/* external and common symbols get N_EXT */
if (is_global != 0) {
sym->type |= N_EXT;
}
if (section == NO_SEG) {
/* symbols in no section get absolute */
sym->type |= N_ABS;
sym->sect = NO_SECT;
/* all absolute symbols are available to use as references */
absolute_sect.gsyms = rb_insert(absolute_sect.gsyms, &sym->symv);
} else {
struct section *s = get_section_by_index(section);
sym->type |= N_SECT;
/* get the in-file index of the section the symbol was defined in */
sym->sect = s ? s->fileindex : NO_SECT;
/* track the initially allocated symbol number for use in future fix-ups */
sym->initial_snum = nsyms;
if (!s) {
/* remember symbol number of references to external
** symbols, this works because every external symbol gets
** its own section number allocated internally by nasm and
** can so be used as a key */
extsyms = raa_write(extsyms, section, nsyms);
switch (is_global) {
case 1:
case 2:
/* there isn't actually a difference between global
** and common symbols, both even have their size in
** sym->symv.key */
sym->type = N_EXT;
break;
default:
/* give an error on unfound section if it's not an
** external or common symbol (assemble_file() does a
** seg_alloc() on every call for them) */
nasm_panic(0, "in-file index for section %d not found, is_global = %d", section, is_global);
break;
}
} else if (is_global) {
s->gsyms = rb_insert(s->gsyms, &sym->symv);
}
}
++nsyms;
}
static void macho_sectalign(int32_t seg, unsigned int value)
{
struct section *s;
int align;
nasm_assert(!(seg & 1));
s = get_section_by_index(seg);
if (!s || !is_power2(value))
return;
align = alignlog2_32(value);
if (s->align < align)
s->align = align;
}
static int32_t macho_segbase(int32_t section)
{
return section;
}
static void macho_filename(char *inname, char *outname)
{
standard_extension(inname, outname, ".o");
}
extern macros_t macho_stdmac[];
/* Comparison function for qsort symbol layout. */
static int layout_compare (const struct symbol **s1,
const struct symbol **s2)
{
return (strcmp ((*s1)->name, (*s2)->name));
}
/* The native assembler does a few things in a similar function
* Remove temporary labels
* Sort symbols according to local, external, undefined (by name)
* Order the string table
We do not remove temporary labels right now.
numsyms is the total number of symbols we have. strtabsize is the
number entries in the string table. */
static void macho_layout_symbols (uint32_t *numsyms,
uint32_t *strtabsize)
{
struct symbol *sym, **symp;
uint32_t i,j;
*numsyms = 0;
*strtabsize = sizeof (char);
symp = &syms;
while ((sym = *symp)) {
/* Undefined symbols are now external. */
if (sym->type == N_UNDF)
sym->type |= N_EXT;
if ((sym->type & N_EXT) == 0) {
sym->snum = *numsyms;
*numsyms = *numsyms + 1;
nlocalsym++;
}
else {
if ((sym->type & N_TYPE) != N_UNDF) {
nextdefsym++;
} else {
nundefsym++;
}
/* If we handle debug info we'll want
to check for it here instead of just
adding the symbol to the string table. */
sym->strx = *strtabsize;
saa_wbytes (strs, sym->name, (int32_t)(strlen(sym->name) + 1));
*strtabsize += strlen(sym->name) + 1;
}
symp = &(sym->next);
}
/* Next, sort the symbols. Most of this code is a direct translation from
the Apple cctools symbol layout. We need to keep compatibility with that. */
/* Set the indexes for symbol groups into the symbol table */
ilocalsym = 0;
iextdefsym = nlocalsym;
iundefsym = nlocalsym + nextdefsym;
/* allocate arrays for sorting externals by name */
extdefsyms = nasm_malloc(nextdefsym * sizeof(struct symbol *));
undefsyms = nasm_malloc(nundefsym * sizeof(struct symbol *));
i = 0;
j = 0;
symp = &syms;
while ((sym = *symp)) {
if((sym->type & N_EXT) == 0) {
sym->strx = *strtabsize;
saa_wbytes (strs, sym->name, (int32_t)(strlen (sym->name) + 1));
*strtabsize += strlen(sym->name) + 1;
}
else {
if((sym->type & N_TYPE) != N_UNDF) {
extdefsyms[i++] = sym;
} else {
undefsyms[j++] = sym;
}
}
symp = &(sym->next);
}
qsort(extdefsyms, nextdefsym, sizeof(struct symbol *),
(int (*)(const void *, const void *))layout_compare);
qsort(undefsyms, nundefsym, sizeof(struct symbol *),
(int (*)(const void *, const void *))layout_compare);
for(i = 0; i < nextdefsym; i++) {
extdefsyms[i]->snum = *numsyms;
*numsyms += 1;
}
for(j = 0; j < nundefsym; j++) {
undefsyms[j]->snum = *numsyms;
*numsyms += 1;
}
}
/* Calculate some values we'll need for writing later. */
static void macho_calculate_sizes (void)
{
struct section *s;
int fi;
/* count sections and calculate in-memory and in-file offsets */
for (s = sects; s != NULL; s = s->next) {
uint64_t newaddr;
/* recalculate segment address based on alignment and vm size */
s->addr = seg_vmsize;
/* we need section alignment to calculate final section address */
if (s->align == -1)
s->align = DEFAULT_SECTION_ALIGNMENT;
newaddr = ALIGN(s->addr, 1 << s->align);
s->addr = newaddr;
seg_vmsize = newaddr + s->size;
/* zerofill sections aren't actually written to the file */
if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
/*
* LLVM/Xcode as always aligns the section data to 4
* bytes; there is a comment in the LLVM source code that
* perhaps aligning to pointer size would be better.
*/
s->pad = ALIGN(seg_filesize, 4) - seg_filesize;
s->offset = seg_filesize + s->pad;
seg_filesize += s->size + s->pad;
}
}
/* calculate size of all headers, load commands and sections to
** get a pointer to the start of all the raw data */
if (seg_nsects > 0) {
++head_ncmds;
head_sizeofcmds += fmt.segcmd_size + seg_nsects * fmt.sectcmd_size;
}
if (nsyms > 0) {
++head_ncmds;
head_sizeofcmds += MACHO_SYMCMD_SIZE;
}
if (seg_nsects > MAX_SECT) {
nasm_fatal(0, "MachO output is limited to %d sections\n",
MAX_SECT);
}
/* Create a table of sections by file index to avoid linear search */
sectstab = nasm_malloc((seg_nsects + 1) * sizeof(*sectstab));
sectstab[NO_SECT] = &absolute_sect;
for (s = sects, fi = 1; s != NULL; s = s->next, fi++)
sectstab[fi] = s;
}
/* Write out the header information for the file. */
static void macho_write_header (void)
{
fwriteint32_t(fmt.mh_magic, ofile); /* magic */
fwriteint32_t(fmt.cpu_type, ofile); /* CPU type */
fwriteint32_t(CPU_SUBTYPE_I386_ALL, ofile); /* CPU subtype */
fwriteint32_t(MH_OBJECT, ofile); /* Mach-O file type */
fwriteint32_t(head_ncmds, ofile); /* number of load commands */
fwriteint32_t(head_sizeofcmds, ofile); /* size of load commands */
fwriteint32_t(0, ofile); /* no flags */
fwritezero(fmt.header_size - 7*4, ofile); /* reserved fields */
}
/* Write out the segment load command at offset. */
static uint32_t macho_write_segment (uint64_t offset)
{
uint64_t rel_base = alignptr(offset + seg_filesize);
uint32_t s_reloff = 0;
struct section *s;
fwriteint32_t(fmt.lc_segment, ofile); /* cmd == LC_SEGMENT_64 */
/* size of load command including section load commands */
fwriteint32_t(fmt.segcmd_size + seg_nsects * fmt.sectcmd_size,
ofile);
/* in an MH_OBJECT file all sections are in one unnamed (name
** all zeros) segment */
fwritezero(16, ofile);
fwriteptr(0, ofile); /* in-memory offset */
fwriteptr(seg_vmsize, ofile); /* in-memory size */
fwriteptr(offset, ofile); /* in-file offset to data */
fwriteptr(seg_filesize, ofile); /* in-file size */
fwriteint32_t(VM_PROT_DEFAULT, ofile); /* maximum vm protection */
fwriteint32_t(VM_PROT_DEFAULT, ofile); /* initial vm protection */
fwriteint32_t(seg_nsects, ofile); /* number of sections */
fwriteint32_t(0, ofile); /* no flags */
/* emit section headers */
for (s = sects; s != NULL; s = s->next) {
if (s->nreloc) {
nasm_assert((s->flags & SECTION_TYPE) != S_ZEROFILL);
s->flags |= S_ATTR_LOC_RELOC;
if (s->extreloc)
s->flags |= S_ATTR_EXT_RELOC;
} else if (!strcmp(s->segname, "__DATA") &&
!strcmp(s->sectname, "__const") &&
!s->by_name &&
!get_section_by_name("__TEXT", "__const")) {
/*
* The MachO equivalent to .rodata can be either
* __DATA,__const or __TEXT,__const; the latter only if
* there are no relocations. However, when mixed it is
* better to specify the segments explicitly.
*/
xstrncpy(s->segname, "__TEXT");
}
nasm_write(s->sectname, sizeof(s->sectname), ofile);
nasm_write(s->segname, sizeof(s->segname), ofile);
fwriteptr(s->addr, ofile);
fwriteptr(s->size, ofile);
/* dummy data for zerofill sections or proper values */
if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
nasm_assert(s->pad != (uint32_t)-1);
offset += s->pad;
fwriteint32_t(offset, ofile);
offset += s->size;
/* Write out section alignment, as a power of two.
e.g. 32-bit word alignment would be 2 (2^2 = 4). */
fwriteint32_t(s->align, ofile);
/* To be compatible with cctools as we emit
a zero reloff if we have no relocations. */
fwriteint32_t(s->nreloc ? rel_base + s_reloff : 0, ofile);
fwriteint32_t(s->nreloc, ofile);
s_reloff += s->nreloc * MACHO_RELINFO_SIZE;
} else {
fwriteint32_t(0, ofile);
fwriteint32_t(s->align, ofile);
fwriteint32_t(0, ofile);
fwriteint32_t(0, ofile);
}
fwriteint32_t(s->flags, ofile); /* flags */
fwriteint32_t(0, ofile); /* reserved */
fwriteptr(0, ofile); /* reserved */
}
rel_padcnt = rel_base - offset;
offset = rel_base + s_reloff;
return offset;
}
/* For a given chain of relocs r, write out the entire relocation
chain to the object file. */
static void macho_write_relocs (struct reloc *r)
{
while (r) {
uint32_t word2;
fwriteint32_t(r->addr, ofile); /* reloc offset */
word2 = r->snum;
word2 |= r->pcrel << 24;
word2 |= r->length << 25;
word2 |= r->ext << 27;
word2 |= r->type << 28;
fwriteint32_t(word2, ofile); /* reloc data */
r = r->next;
}
}
/* Write out the section data. */
static void macho_write_section (void)
{
struct section *s;
struct reloc *r;
uint8_t *p;
int32_t len;
int64_t l;
union offset {
uint64_t val;
uint8_t buf[8];
} blk;
for (s = sects; s != NULL; s = s->next) {
if ((s->flags & SECTION_TYPE) == S_ZEROFILL)
continue;
/* Like a.out Mach-O references things in the data or bss
* sections by addresses which are actually relative to the
* start of the _text_ section, in the _file_. See outaout.c
* for more information. */
saa_rewind(s->data);
for (r = s->relocs; r != NULL; r = r->next) {
len = (uint32_t)1 << r->length;
if (len > 4) /* Can this ever be an issue?! */
len = 8;
blk.val = 0;
saa_fread(s->data, r->addr, blk.buf, len);
/* get offset based on relocation type */
#ifdef WORDS_LITTLEENDIAN
l = blk.val;
#else
l = blk.buf[0];
l += ((int64_t)blk.buf[1]) << 8;
l += ((int64_t)blk.buf[2]) << 16;
l += ((int64_t)blk.buf[3]) << 24;
l += ((int64_t)blk.buf[4]) << 32;
l += ((int64_t)blk.buf[5]) << 40;
l += ((int64_t)blk.buf[6]) << 48;
l += ((int64_t)blk.buf[7]) << 56;
#endif
/* If the relocation is internal add to the current section
offset. Otherwise the only value we need is the symbol
offset which we already have. The linker takes care
of the rest of the address. */
if (!r->ext) {
/* generate final address by section address and offset */
nasm_assert(r->snum <= seg_nsects);
l += sectstab[r->snum]->addr;
if (r->pcrel)
l -= s->addr;
} else if (r->pcrel && r->type == GENERIC_RELOC_VANILLA) {
l -= s->addr;
}
/* write new offset back */
p = blk.buf;
WRITEDLONG(p, l);
saa_fwrite(s->data, r->addr, blk.buf, len);
}
/* dump the section data to file */
fwritezero(s->pad, ofile);
saa_fpwrite(s->data, ofile);
}
/* pad last section up to reloc entries on pointer boundary */
fwritezero(rel_padcnt, ofile);
/* emit relocation entries */
for (s = sects; s != NULL; s = s->next)
macho_write_relocs (s->relocs);
}
/* Write out the symbol table. We should already have sorted this
before now. */
static void macho_write_symtab (void)
{
struct symbol *sym;
uint64_t i;
/* we don't need to pad here since MACHO_RELINFO_SIZE == 8 */
for (sym = syms; sym != NULL; sym = sym->next) {
if ((sym->type & N_EXT) == 0) {
fwriteint32_t(sym->strx, ofile); /* string table entry number */
nasm_write(&sym->type, 1, ofile); /* symbol type */
nasm_write(&sym->sect, 1, ofile); /* section */
fwriteint16_t(sym->desc, ofile); /* description */
/* Fix up the symbol value now that we know the final section
sizes. */
if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
nasm_assert(sym->sect <= seg_nsects);
sym->symv.key += sectstab[sym->sect]->addr;
}
fwriteptr(sym->symv.key, ofile); /* value (i.e. offset) */
}
}
for (i = 0; i < nextdefsym; i++) {
sym = extdefsyms[i];
fwriteint32_t(sym->strx, ofile);
nasm_write(&sym->type, 1, ofile); /* symbol type */
nasm_write(&sym->sect, 1, ofile); /* section */
fwriteint16_t(sym->desc, ofile); /* description */
/* Fix up the symbol value now that we know the final section
sizes. */
if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
nasm_assert(sym->sect <= seg_nsects);
sym->symv.key += sectstab[sym->sect]->addr;
}
fwriteptr(sym->symv.key, ofile); /* value (i.e. offset) */
}
for (i = 0; i < nundefsym; i++) {
sym = undefsyms[i];
fwriteint32_t(sym->strx, ofile);
nasm_write(&sym->type, 1, ofile); /* symbol type */
nasm_write(&sym->sect, 1, ofile); /* section */
fwriteint16_t(sym->desc, ofile); /* description */
/* Fix up the symbol value now that we know the final section
sizes. */
if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
nasm_assert(sym->sect <= seg_nsects);
sym->symv.key += sectstab[sym->sect]->addr;
}
fwriteptr(sym->symv.key, ofile); /* value (i.e. offset) */
}
}
/* Fixup the snum in the relocation entries, we should be
doing this only for externally referenced symbols. */
static void macho_fixup_relocs (struct reloc *r)
{
struct symbol *sym;
while (r != NULL) {
if (r->ext) {
for (sym = syms; sym != NULL; sym = sym->next) {
if (sym->initial_snum == r->snum) {
r->snum = sym->snum;
break;
}
}
}
r = r->next;
}
}
/* Write out the object file. */
static void macho_write (void)
{
uint64_t offset = 0;
/* mach-o object file structure:
**
** mach header
** uint32_t magic
** int cpu type
** int cpu subtype
** uint32_t mach file type
** uint32_t number of load commands
** uint32_t size of all load commands
** (includes section struct size of segment command)
** uint32_t flags
**
** segment command
** uint32_t command type == LC_SEGMENT[_64]
** uint32_t size of load command
** (including section load commands)
** char[16] segment name
** pointer in-memory offset
** pointer in-memory size
** pointer in-file offset to data area
** pointer in-file size
** (in-memory size excluding zerofill sections)
** int maximum vm protection
** int initial vm protection
** uint32_t number of sections
** uint32_t flags
**
** section commands
** char[16] section name
** char[16] segment name
** pointer in-memory offset
** pointer in-memory size
** uint32_t in-file offset
** uint32_t alignment
** (irrelevant in MH_OBJECT)
** uint32_t in-file offset of relocation entires
** uint32_t number of relocations
** uint32_t flags
** uint32_t reserved
** uint32_t reserved
**
** symbol table command
** uint32_t command type == LC_SYMTAB
** uint32_t size of load command
** uint32_t symbol table offset
** uint32_t number of symbol table entries
** uint32_t string table offset
** uint32_t string table size
**
** raw section data
**
** padding to pointer boundary
**
** relocation data (struct reloc)
** int32_t offset
** uint data (symbolnum, pcrel, length, extern, type)
**
** symbol table data (struct nlist)
** int32_t string table entry number
** uint8_t type
** (extern, absolute, defined in section)
** uint8_t section
** (0 for global symbols, section number of definition (>= 1, <=
** 254) for local symbols, size of variable for common symbols
** [type == extern])
** int16_t description
** (for stab debugging format)
** pointer value (i.e. file offset) of symbol or stab offset
**
** string table data
** list of null-terminated strings
*/
/* Emit the Mach-O header. */
macho_write_header();
offset = fmt.header_size + head_sizeofcmds;
/* emit the segment load command */
if (seg_nsects > 0)
offset = macho_write_segment (offset);
else
nasm_error(ERR_WARNING, "no sections?");
if (nsyms > 0) {
/* write out symbol command */
fwriteint32_t(LC_SYMTAB, ofile); /* cmd == LC_SYMTAB */
fwriteint32_t(MACHO_SYMCMD_SIZE, ofile); /* size of load command */
fwriteint32_t(offset, ofile); /* symbol table offset */
fwriteint32_t(nsyms, ofile); /* number of symbol
** table entries */
offset += nsyms * fmt.nlist_size;
fwriteint32_t(offset, ofile); /* string table offset */
fwriteint32_t(strslen, ofile); /* string table size */
}
/* emit section data */
if (seg_nsects > 0)
macho_write_section ();
/* emit symbol table if we have symbols */
if (nsyms > 0)
macho_write_symtab ();
/* we don't need to pad here, we are already aligned */
/* emit string table */
saa_fpwrite(strs, ofile);
}
/* We do quite a bit here, starting with finalizing all of the data
for the object file, writing, and then freeing all of the data from
the file. */
static void macho_cleanup(void)
{
struct section *s;
struct reloc *r;
struct symbol *sym;
/* Sort all symbols. */
macho_layout_symbols (&nsyms, &strslen);
/* Fixup relocation entries */
for (s = sects; s != NULL; s = s->next) {
macho_fixup_relocs (s->relocs);
}
/* First calculate and finalize needed values. */
macho_calculate_sizes();
macho_write();
/* free up everything */
while (sects->next) {
s = sects;
sects = sects->next;
saa_free(s->data);
while (s->relocs != NULL) {
r = s->relocs;
s->relocs = s->relocs->next;
nasm_free(r);
}
nasm_free(s);
}
saa_free(strs);
raa_free(extsyms);
while (syms) {
sym = syms;
syms = syms->next;
nasm_free (sym);
}
nasm_free(extdefsyms);
nasm_free(undefsyms);
nasm_free(sectstab);
}
#ifdef OF_MACHO32
static const struct macho_fmt macho32_fmt = {
4,
MH_MAGIC,
CPU_TYPE_I386,
LC_SEGMENT,
MACHO_HEADER_SIZE,
MACHO_SEGCMD_SIZE,
MACHO_SECTCMD_SIZE,
MACHO_NLIST_SIZE,
RL_MAX_32,
GENERIC_RELOC_VANILLA,
GENERIC_RELOC_VANILLA,
GENERIC_RELOC_TLV
};
static void macho32_init(void)
{
fmt = macho32_fmt;
macho_init();
macho_gotpcrel_sect = NO_SEG;
}
const struct ofmt of_macho32 = {
"NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (i386) object files",
"macho32",
0,
32,
null_debug_arr,
&null_debug_form,
macho_stdmac,
macho32_init,
null_setinfo,
nasm_do_legacy_output,
macho_output,
macho_symdef,
macho_section,
macho_sectalign,
macho_segbase,
null_directive,
macho_filename,
macho_cleanup
};
#endif
#ifdef OF_MACHO64
static const struct macho_fmt macho64_fmt = {
8,
MH_MAGIC_64,
CPU_TYPE_X86_64,
LC_SEGMENT_64,
MACHO_HEADER64_SIZE,
MACHO_SEGCMD64_SIZE,
MACHO_SECTCMD64_SIZE,
MACHO_NLIST64_SIZE,
RL_MAX_64,
X86_64_RELOC_UNSIGNED,
X86_64_RELOC_SIGNED,
X86_64_RELOC_TLV
};
static void macho64_init(void)
{
fmt = macho64_fmt;
macho_init();
/* add special symbol for ..gotpcrel */
macho_gotpcrel_sect = seg_alloc() + 1;
define_label("..gotpcrel", macho_gotpcrel_sect, 0L, NULL, false, false);
}
const struct ofmt of_macho64 = {
"NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (x86_64) object files",
"macho64",
0,
64,
null_debug_arr,
&null_debug_form,
macho_stdmac,
macho64_init,
null_setinfo,
nasm_do_legacy_output,
macho_output,
macho_symdef,
macho_section,
macho_sectalign,
macho_segbase,
null_directive,
macho_filename,
macho_cleanup
};
#endif
#endif
/*
* Local Variables:
* mode:c
* c-basic-offset:4
* End:
*
* end of file */
| 28.524426 | 108 | 0.61092 | [
"object"
] |
3212dfe8b98edeb71e09a21ca91e13118eac916e | 7,616 | c | C | shared-module/displayio/TileGrid.c | mattracing/circuitpython | 652bbff64371aa7797e5baffec45eff097def4b5 | [
"MIT"
] | 4 | 2018-09-25T06:32:11.000Z | 2019-04-21T12:09:24.000Z | shared-module/displayio/TileGrid.c | mattracing/circuitpython | 652bbff64371aa7797e5baffec45eff097def4b5 | [
"MIT"
] | 6 | 2020-02-12T12:59:31.000Z | 2020-02-19T19:31:29.000Z | shared-module/displayio/TileGrid.c | mattracing/circuitpython | 652bbff64371aa7797e5baffec45eff097def4b5 | [
"MIT"
] | 3 | 2020-02-12T13:21:47.000Z | 2021-12-02T15:56:16.000Z | /*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Scott Shawcroft for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "shared-bindings/displayio/TileGrid.h"
#include "shared-bindings/displayio/Bitmap.h"
#include "shared-bindings/displayio/ColorConverter.h"
#include "shared-bindings/displayio/OnDiskBitmap.h"
#include "shared-bindings/displayio/Palette.h"
#include "shared-bindings/displayio/Shape.h"
void common_hal_displayio_tilegrid_construct(displayio_tilegrid_t *self, mp_obj_t bitmap,
uint16_t bitmap_width_in_tiles,
mp_obj_t pixel_shader, uint16_t width, uint16_t height,
uint16_t tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint8_t default_tile) {
uint32_t total_tiles = width * height;
// Sprites will only have one tile so save a little memory by inlining values in the pointer.
uint8_t inline_tiles = sizeof(uint8_t*);
if (total_tiles <= inline_tiles) {
self->tiles = 0;
// Pack values into the pointer since there are only a few.
for (uint32_t i = 0; i < inline_tiles; i++) {
((uint8_t*) &self->tiles)[i] = default_tile;
}
self->inline_tiles = true;
} else {
self->tiles = (uint8_t*) m_malloc(total_tiles, false);
for (uint32_t i = 0; i < total_tiles; i++) {
self->tiles[i] = default_tile;
}
self->inline_tiles = false;
}
self->bitmap_width_in_tiles = bitmap_width_in_tiles;
self->width_in_tiles = width;
self->height_in_tiles = height;
self->total_width = width * tile_width;
self->total_height = height * tile_height;
self->tile_width = tile_width;
self->tile_height = tile_height;
self->bitmap = bitmap;
self->pixel_shader = pixel_shader;
self->x = x;
self->y = y;
}
mp_int_t common_hal_displayio_tilegrid_get_x(displayio_tilegrid_t *self) {
return self->x;
}
void common_hal_displayio_tilegrid_set_x(displayio_tilegrid_t *self, mp_int_t x) {
self->needs_refresh = self->x != x;
self->x = x;
}
mp_int_t common_hal_displayio_tilegrid_get_y(displayio_tilegrid_t *self) {
return self->y;
}
void common_hal_displayio_tilegrid_set_y(displayio_tilegrid_t *self, mp_int_t y) {
self->needs_refresh = self->y != y;
self->y = y;
}
mp_obj_t common_hal_displayio_tilegrid_get_pixel_shader(displayio_tilegrid_t *self) {
return self->pixel_shader;
}
void common_hal_displayio_tilegrid_set_pixel_shader(displayio_tilegrid_t *self, mp_obj_t pixel_shader) {
self->pixel_shader = pixel_shader;
self->needs_refresh = true;
}
uint16_t common_hal_displayio_tilegrid_get_width(displayio_tilegrid_t *self) {
return self->width_in_tiles;
}
uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self) {
return self->height_in_tiles;
}
uint8_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y) {
uint8_t* tiles = self->tiles;
if (self->inline_tiles) {
tiles = (uint8_t*) &self->tiles;
}
if (tiles == NULL) {
return 0;
}
return tiles[y * self->width_in_tiles + x];
}
void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint8_t tile_index) {
uint8_t* tiles = self->tiles;
if (self->inline_tiles) {
tiles = (uint8_t*) &self->tiles;
}
if (tiles == NULL) {
return;
}
tiles[y * self->width_in_tiles + x] = tile_index;
self->needs_refresh = true;
}
void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint16_t x, uint16_t y) {
self->top_left_x = x;
self->top_left_y = y;
}
bool displayio_tilegrid_get_pixel(displayio_tilegrid_t *self, int16_t x, int16_t y, uint16_t* pixel) {
x -= self->x;
y -= self->y;
if (y < 0 || y >= self->total_height || x >= self->total_width || x < 0) {
return false;
}
uint8_t* tiles = self->tiles;
if (self->inline_tiles) {
tiles = (uint8_t*) &self->tiles;
}
if (tiles == NULL) {
return false;
}
uint16_t tile_location = ((y / self->tile_height + self->top_left_y) % self->height_in_tiles) * self->width_in_tiles + (x / self->tile_width + self->top_left_x) % self->width_in_tiles;
uint8_t tile = tiles[tile_location];
uint16_t tile_x = tile_x = (tile % self->bitmap_width_in_tiles) * self->tile_width + x % self->tile_width;
uint16_t tile_y = tile_y = (tile / self->bitmap_width_in_tiles) * self->tile_height + y % self->tile_height;
uint32_t value = 0;
if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) {
value = common_hal_displayio_bitmap_get_pixel(self->bitmap, tile_x, tile_y);
} else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_shape_type)) {
value = common_hal_displayio_shape_get_pixel(self->bitmap, tile_x, tile_y);
} else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_ondiskbitmap_type)) {
value = common_hal_displayio_ondiskbitmap_get_pixel(self->bitmap, tile_x, tile_y);
}
if (self->pixel_shader == mp_const_none) {
*pixel = value;
return true;
} else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type) && displayio_palette_get_color(self->pixel_shader, value, pixel)) {
return true;
} else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type) && common_hal_displayio_colorconverter_convert(self->pixel_shader, value, pixel)) {
return true;
}
return false;
}
bool displayio_tilegrid_needs_refresh(displayio_tilegrid_t *self) {
if (self->needs_refresh) {
return true;
} else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) {
return displayio_palette_needs_refresh(self->pixel_shader);
} else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) {
return displayio_colorconverter_needs_refresh(self->pixel_shader);
}
return false;
}
void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self) {
self->needs_refresh = false;
if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) {
displayio_palette_finish_refresh(self->pixel_shader);
} else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) {
displayio_colorconverter_finish_refresh(self->pixel_shader);
}
// TODO(tannewt): We could double buffer changes to position and move them over here.
// That way they won't change during a refresh and tear.
}
| 39.257732 | 188 | 0.711003 | [
"shape"
] |
32138bc8afb3e4fe59945bc58e4c212cb42d9b1b | 3,278 | h | C | tools/comdb2ar/increment.h | isabella232/comdb2 | 438cb26e2299c31a165176dd4f0fa6afe31c172a | [
"Apache-2.0"
] | 1 | 2019-12-23T06:42:09.000Z | 2019-12-23T06:42:09.000Z | tools/comdb2ar/increment.h | jepsen-io/comdb2 | 438cb26e2299c31a165176dd4f0fa6afe31c172a | [
"Apache-2.0"
] | 1 | 2021-02-23T21:00:40.000Z | 2021-02-23T22:38:53.000Z | tools/comdb2ar/increment.h | isabella232/comdb2 | 438cb26e2299c31a165176dd4f0fa6afe31c172a | [
"Apache-2.0"
] | 2 | 2020-06-05T19:16:05.000Z | 2020-12-02T10:59:50.000Z | #ifndef INCLUDED_INCREMENT
#define INCLUDED_INCREMENT
#include <string>
#include <vector>
#include <set>
#include <map>
#include <utility>
#include "file_info.h"
bool is_not_incr_file(std::string filename);
// Determine whether a file is not .incr or .sha
std::string get_sha_fingerprint(std::string filename, std::string incr_path);
// Read a .sha file to get the SHA fingerprint
std::string read_serialised_sha_file();
// read from STDIN to get the fingerprint from a serialised .SHA file
bool compare_checksum(
FileInfo file,
const std::string& incr_path,
std::vector<uint32_t>& pages,
ssize_t *data_size,
std::set<std::string>& incr_files
);
// Compare a file's checksum and LSN with it's diff file to determine whether pages
// have been changed
void write_incr_manifest_entry(
std::ostream& os,
const FileInfo& file,
const std::vector<uint32_t>& pages
);
// Write the manifest entry for a file that has been changed
void write_del_manifest_entry(std::ostream& os, const std::string& incr_filename);
// Write the manifest entry for a file that has been deleted
ssize_t serialise_incr_file(
const FileInfo& file,
std::vector<uint32_t> pages,
std::string incr_path
);
// Given a file and a list of changed pages, serialise those pages to STDOUT
std::string getDTString();
// Get the YYYYMMDDHHMMSS string of the current timestamp
void incr_deserialise_database(
const std::string& lrldestdir,
const std::string& datadestdir,
const std::string& dbname,
std::set<std::string>& table_set,
std::string& sha_fingerprint,
unsigned percent_full,
bool force_mode,
std::vector<std::string>& options,
bool& is_disk_full
);
// Deserialise an incremental backup from STDOUT
std::string read_incr_manifest(unsigned long long filesize);
// Read from STDIN the manifest file
bool process_incr_manifest(
const std::string text,
const std::string datadestdir,
std::map<std::string, std::pair<FileInfo, std::vector<uint32_t>>>&
updated_files,
std::map<std::string, FileInfo>& new_files,
std::set<std::string>& deleted_files,
std::vector<std::string>& file_order,
std::vector<std::string>& options,
std::string& process_incr_manifest
);
// Process the tokens from the manifest file to create a map of
// changed, new, and deleted files as well as the order the changed files
// will be read in from STDIN
void unpack_incr_data(
const std::vector<std::string>& file_order,
const std::map<std::string, std::pair<FileInfo, std::vector<uint32_t>>>& updated_files,
const std::string& datadestdir
);
// Unpack the changed files from the .data file read in from STDIN
void handle_deleted_files(
std::set<std::string>& deleted_files,
const std::string& datadestdir,
std::set<std::string>& table_set
);
// Delete delted files
void unpack_full_file(
FileInfo *file_info_pt,
const std::string filename,
unsigned long long filesize,
const std::string datadestdir,
bool is_data_file,
unsigned percent_full,
bool& is_disk_full
);
// Deserialise a full file
void clear_log_folder(const std::string& datadestdir, const std::string& dbname);
// Delete everything in the log folder to ensure there aren't log gaps
#endif
| 29.267857 | 91 | 0.729408 | [
"vector"
] |
3216cfe5efb5eab7b31f8b950fbf92c52f2b19ce | 4,787 | h | C | chrome/browser/ash/policy/uploading/status_uploader.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/ash/policy/uploading/status_uploader.h | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/ash/policy/uploading/status_uploader.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_POLICY_UPLOADING_STATUS_UPLOADER_H_
#define CHROME_BROWSER_ASH_POLICY_UPLOADING_STATUS_UPLOADER_H_
#include <memory>
#include "base/bind.h"
#include "base/cancelable_callback.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/proto/device_management_backend.pb.h"
namespace base {
class SequencedTaskRunner;
}
namespace policy {
class CloudPolicyClient;
class StatusCollector;
struct StatusCollectorParams;
// Class responsible for periodically uploading device status from the
// passed StatusCollector.
class StatusUploader : public MediaCaptureDevicesDispatcher::Observer {
public:
// Constructor. |client| must be registered and must stay
// valid and registered through the lifetime of this StatusUploader
// object.
StatusUploader(CloudPolicyClient* client,
std::unique_ptr<StatusCollector> collector,
const scoped_refptr<base::SequencedTaskRunner>& task_runner,
base::TimeDelta default_upload_frequency);
StatusUploader(const StatusUploader&) = delete;
StatusUploader& operator=(const StatusUploader&) = delete;
~StatusUploader() override;
// Returns the time of the last successful upload, or Time(0) if no upload
// has ever happened.
base::Time last_upload() const { return last_upload_; }
// Returns true if session data upload (screenshots, logs, etc) is allowed.
// This checks to ensure that the current session is a kiosk session, and
// that no user input (keyboard, mouse, touch, audio/video) has been received.
bool IsSessionDataUploadAllowed();
// MediaCaptureDevicesDispatcher::Observer implementation
void OnRequestUpdate(int render_process_id,
int render_frame_id,
blink::mojom::MediaStreamType stream_type,
const content::MediaRequestState state) override;
// Returns true if the next status upload has been scheduled successfully.
// Returns false if there is already an ongoing status report.
bool ScheduleNextStatusUploadImmediately();
StatusCollector* status_collector() const { return collector_.get(); }
private:
// Callback invoked periodically to upload the device status from the
// StatusCollector.
void UploadStatus();
// Called asynchronously by StatusCollector when status arrives.
void OnStatusReceived(StatusCollectorParams callback_params);
// Invoked once a status upload has completed.
void OnUploadCompleted(bool success);
// Helper method that figures out when the next status upload should
// be scheduled. Returns true if the next status upload has been scheduled
// successfully, returns false if there is already an ongoing status report.
bool ScheduleNextStatusUpload(bool immediately = false);
// Updates the upload frequency from settings and schedules a new upload
// if appropriate.
void RefreshUploadFrequency();
// Updates the status collector being used.
void UpdateStatusCollector();
// CloudPolicyClient used to issue requests to the server.
CloudPolicyClient* client_;
// StatusCollector that provides status for uploading.
std::unique_ptr<StatusCollector> collector_;
// TaskRunner used for scheduling upload tasks.
const scoped_refptr<base::SequencedTaskRunner> task_runner_;
// How long to wait between status uploads.
base::TimeDelta upload_frequency_;
// Subscription for the callback about changes in the upload frequency.
base::CallbackListSubscription upload_frequency_subscription_;
// The time the last upload was performed.
base::Time last_upload_;
// Subscription for whether or not to user granular reporting.
base::CallbackListSubscription granular_reporting_subscription_;
// Callback invoked via a delay to upload device status.
base::CancelableOnceClosure upload_callback_;
// True if there has been any captured media in this session.
bool has_captured_media_;
// Used to prevent a race condition where two status uploads are being
// executed in parallel.
bool status_upload_in_progress_ = false;
// Note: This should remain the last member so it'll be destroyed and
// invalidate the weak pointers before any other members are destroyed.
base::WeakPtrFactory<StatusUploader> weak_factory_{this};
};
} // namespace policy
#endif // CHROME_BROWSER_ASH_POLICY_UPLOADING_STATUS_UPLOADER_H_
| 36.823077 | 80 | 0.766033 | [
"object"
] |
3218b21b2f0f08bafcfa3f0b25405c85eddccd1f | 34,073 | c | C | dlls/d3d10_1/tests/d3d10_1.c | Heersin/wine | 36b45c6d1c124dd16b3475ba743fcbbc99d6862d | [
"MIT"
] | 5 | 2022-01-21T01:36:07.000Z | 2022-02-03T16:23:30.000Z | dlls/d3d10_1/tests/d3d10_1.c | Heersin/wine | 36b45c6d1c124dd16b3475ba743fcbbc99d6862d | [
"MIT"
] | null | null | null | dlls/d3d10_1/tests/d3d10_1.c | Heersin/wine | 36b45c6d1c124dd16b3475ba743fcbbc99d6862d | [
"MIT"
] | 2 | 2022-01-20T13:42:27.000Z | 2022-03-14T05:11:13.000Z | /*
* Copyright 2008 Henri Verbeet for CodeWeavers
* Copyright 2015 Józef Kucia for CodeWeavers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#define COBJMACROS
#include "d3d10_1.h"
#include "initguid.h"
#include "d3d11_1.h"
#include "wine/test.h"
static const D3D10_FEATURE_LEVEL1 d3d10_feature_levels[] =
{
D3D10_FEATURE_LEVEL_10_1,
D3D10_FEATURE_LEVEL_10_0,
D3D10_FEATURE_LEVEL_9_3,
D3D10_FEATURE_LEVEL_9_2,
D3D10_FEATURE_LEVEL_9_1
};
static ULONG get_refcount(IUnknown *iface)
{
IUnknown_AddRef(iface);
return IUnknown_Release(iface);
}
struct device_desc
{
D3D10_FEATURE_LEVEL1 feature_level;
UINT flags;
};
static ID3D10Device1 *create_device(const struct device_desc *desc)
{
D3D10_FEATURE_LEVEL1 feature_level = D3D10_FEATURE_LEVEL_10_1;
ID3D10Device1 *device;
UINT flags = 0;
if (desc)
{
feature_level = desc->feature_level;
flags = desc->flags;
}
if (SUCCEEDED(D3D10CreateDevice1(NULL, D3D10_DRIVER_TYPE_HARDWARE,
NULL, flags, feature_level, D3D10_1_SDK_VERSION, &device)))
return device;
if (SUCCEEDED(D3D10CreateDevice1(NULL, D3D10_DRIVER_TYPE_WARP,
NULL, flags, feature_level, D3D10_1_SDK_VERSION, &device)))
return device;
if (SUCCEEDED(D3D10CreateDevice1(NULL, D3D10_DRIVER_TYPE_REFERENCE,
NULL, flags, feature_level, D3D10_1_SDK_VERSION, &device)))
return device;
return NULL;
}
#define check_interface(a, b, c, d) check_interface_(__LINE__, a, b, c, d)
static HRESULT check_interface_(unsigned int line, void *iface, REFIID iid, BOOL supported, BOOL is_broken)
{
HRESULT hr, expected_hr, broken_hr;
IUnknown *unknown = iface, *out;
if (supported)
{
expected_hr = S_OK;
broken_hr = E_NOINTERFACE;
}
else
{
expected_hr = E_NOINTERFACE;
broken_hr = S_OK;
}
hr = IUnknown_QueryInterface(unknown, iid, (void **)&out);
ok_(__FILE__, line)(hr == expected_hr || broken(is_broken && hr == broken_hr),
"Got unexpected hr %#lx, expected %#lx.\n", hr, expected_hr);
if (SUCCEEDED(hr))
IUnknown_Release(out);
return hr;
}
static void test_create_device(void)
{
D3D10_FEATURE_LEVEL1 feature_level, supported_feature_level;
DXGI_SWAP_CHAIN_DESC swapchain_desc, obtained_desc;
IDXGISwapChain *swapchain;
ID3D10Device1 *device;
unsigned int i;
ULONG refcount;
HWND window;
HRESULT hr;
for (i = 0; i < ARRAY_SIZE(d3d10_feature_levels); ++i)
{
if (SUCCEEDED(hr = D3D10CreateDevice1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
d3d10_feature_levels[i], D3D10_1_SDK_VERSION, &device)))
{
supported_feature_level = d3d10_feature_levels[i];
break;
}
}
if (FAILED(hr))
{
skip("Failed to create HAL device.\n");
return;
}
feature_level = ID3D10Device1_GetFeatureLevel(device);
ok(feature_level == supported_feature_level, "Got feature level %#x, expected %#x.\n",
feature_level, supported_feature_level);
ID3D10Device1_Release(device);
hr = D3D10CreateDevice1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, NULL);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
device = (ID3D10Device1 *)0xdeadbeef;
hr = D3D10CreateDevice1(NULL, 0xffffffff, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, &device);
todo_wine ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
ok(!device, "Got unexpected device pointer %p.\n", device);
device = (ID3D10Device1 *)0xdeadbeef;
hr = D3D10CreateDevice1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
0, D3D10_1_SDK_VERSION, &device);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
ok(!device, "Got unexpected device pointer %p.\n", device);
window = CreateWindowA("static", "d3d10_1_test", 0, 0, 0, 0, 0, 0, 0, 0, 0);
swapchain_desc.BufferDesc.Width = 800;
swapchain_desc.BufferDesc.Height = 600;
swapchain_desc.BufferDesc.RefreshRate.Numerator = 60;
swapchain_desc.BufferDesc.RefreshRate.Denominator = 60;
swapchain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapchain_desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapchain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapchain_desc.SampleDesc.Count = 1;
swapchain_desc.SampleDesc.Quality = 0;
swapchain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapchain_desc.BufferCount = 1;
swapchain_desc.OutputWindow = window;
swapchain_desc.Windowed = TRUE;
swapchain_desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapchain_desc.Flags = 0;
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, &swapchain_desc, &swapchain, &device);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
check_interface(swapchain, &IID_IDXGISwapChain1, TRUE, FALSE);
memset(&obtained_desc, 0, sizeof(obtained_desc));
hr = IDXGISwapChain_GetDesc(swapchain, &obtained_desc);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
ok(obtained_desc.BufferDesc.Width == swapchain_desc.BufferDesc.Width,
"Got unexpected BufferDesc.Width %u.\n", obtained_desc.BufferDesc.Width);
ok(obtained_desc.BufferDesc.Height == swapchain_desc.BufferDesc.Height,
"Got unexpected BufferDesc.Height %u.\n", obtained_desc.BufferDesc.Height);
todo_wine ok(obtained_desc.BufferDesc.RefreshRate.Numerator == swapchain_desc.BufferDesc.RefreshRate.Numerator,
"Got unexpected BufferDesc.RefreshRate.Numerator %u.\n",
obtained_desc.BufferDesc.RefreshRate.Numerator);
todo_wine ok(obtained_desc.BufferDesc.RefreshRate.Denominator == swapchain_desc.BufferDesc.RefreshRate.Denominator,
"Got unexpected BufferDesc.RefreshRate.Denominator %u.\n",
obtained_desc.BufferDesc.RefreshRate.Denominator);
ok(obtained_desc.BufferDesc.Format == swapchain_desc.BufferDesc.Format,
"Got unexpected BufferDesc.Format %#x.\n", obtained_desc.BufferDesc.Format);
ok(obtained_desc.BufferDesc.ScanlineOrdering == swapchain_desc.BufferDesc.ScanlineOrdering,
"Got unexpected BufferDesc.ScanlineOrdering %#x.\n", obtained_desc.BufferDesc.ScanlineOrdering);
ok(obtained_desc.BufferDesc.Scaling == swapchain_desc.BufferDesc.Scaling,
"Got unexpected BufferDesc.Scaling %#x.\n", obtained_desc.BufferDesc.Scaling);
ok(obtained_desc.SampleDesc.Count == swapchain_desc.SampleDesc.Count,
"Got unexpected SampleDesc.Count %u.\n", obtained_desc.SampleDesc.Count);
ok(obtained_desc.SampleDesc.Quality == swapchain_desc.SampleDesc.Quality,
"Got unexpected SampleDesc.Quality %u.\n", obtained_desc.SampleDesc.Quality);
ok(obtained_desc.BufferUsage == swapchain_desc.BufferUsage,
"Got unexpected BufferUsage %#x.\n", obtained_desc.BufferUsage);
ok(obtained_desc.BufferCount == swapchain_desc.BufferCount,
"Got unexpected BufferCount %u.\n", obtained_desc.BufferCount);
ok(obtained_desc.OutputWindow == swapchain_desc.OutputWindow,
"Got unexpected OutputWindow %p.\n", obtained_desc.OutputWindow);
ok(obtained_desc.Windowed == swapchain_desc.Windowed,
"Got unexpected Windowed %#x.\n", obtained_desc.Windowed);
ok(obtained_desc.SwapEffect == swapchain_desc.SwapEffect,
"Got unexpected SwapEffect %#x.\n", obtained_desc.SwapEffect);
ok(obtained_desc.Flags == swapchain_desc.Flags,
"Got unexpected Flags %#x.\n", obtained_desc.Flags);
refcount = IDXGISwapChain_Release(swapchain);
ok(!refcount, "Swapchain has %lu references left.\n", refcount);
feature_level = ID3D10Device1_GetFeatureLevel(device);
ok(feature_level == supported_feature_level, "Got feature level %#x, expected %#x.\n",
feature_level, supported_feature_level);
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, NULL, NULL, &device);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, NULL, NULL, NULL);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, &swapchain_desc, NULL, NULL);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
swapchain = (IDXGISwapChain *)0xdeadbeef;
device = (ID3D10Device1 *)0xdeadbeef;
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
0, D3D10_1_SDK_VERSION, &swapchain_desc, &swapchain, &device);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
ok(!swapchain, "Got unexpected swapchain pointer %p.\n", swapchain);
ok(!device, "Got unexpected device pointer %p.\n", device);
swapchain = (IDXGISwapChain *)0xdeadbeef;
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, &swapchain_desc, &swapchain, NULL);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
ok(!swapchain, "Got unexpected swapchain pointer %p.\n", swapchain);
swapchain_desc.OutputWindow = NULL;
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, &swapchain_desc, NULL, &device);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
swapchain = (IDXGISwapChain *)0xdeadbeef;
device = (ID3D10Device1 *)0xdeadbeef;
swapchain_desc.OutputWindow = NULL;
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, &swapchain_desc, &swapchain, &device);
ok(hr == DXGI_ERROR_INVALID_CALL, "Got unexpected hr %#lx.\n", hr);
ok(!swapchain, "Got unexpected swapchain pointer %p.\n", swapchain);
ok(!device, "Got unexpected device pointer %p.\n", device);
swapchain = (IDXGISwapChain *)0xdeadbeef;
device = (ID3D10Device1 *)0xdeadbeef;
swapchain_desc.OutputWindow = window;
swapchain_desc.BufferDesc.Format = DXGI_FORMAT_BC5_UNORM;
hr = D3D10CreateDeviceAndSwapChain1(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0,
supported_feature_level, D3D10_1_SDK_VERSION, &swapchain_desc, &swapchain, &device);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
ok(!swapchain, "Got unexpected swapchain pointer %p.\n", swapchain);
ok(!device, "Got unexpected device pointer %p.\n", device);
DestroyWindow(window);
}
static void test_device_interfaces(void)
{
IDXGIAdapter *dxgi_adapter;
IDXGIDevice *dxgi_device;
ID3D10Device1 *device;
IUnknown *iface;
ULONG refcount;
unsigned int i;
HRESULT hr;
for (i = 0; i < ARRAY_SIZE(d3d10_feature_levels); ++i)
{
struct device_desc device_desc;
device_desc.feature_level = d3d10_feature_levels[i];
device_desc.flags = 0;
if (!(device = create_device(&device_desc)))
{
skip("Failed to create device for feature level %#x.\n", d3d10_feature_levels[i]);
continue;
}
check_interface(device, &IID_IUnknown, TRUE, FALSE);
check_interface(device, &IID_IDXGIObject, TRUE, FALSE);
check_interface(device, &IID_IDXGIDevice, TRUE, FALSE);
check_interface(device, &IID_IDXGIDevice1, TRUE, FALSE);
check_interface(device, &IID_ID3D10Multithread, TRUE, TRUE); /* Not available on all Windows versions. */
check_interface(device, &IID_ID3D10Device, TRUE, FALSE);
check_interface(device, &IID_ID3D10InfoQueue, FALSE, FALSE); /* Non-debug mode. */
check_interface(device, &IID_ID3D11Device, TRUE, TRUE); /* Not available on all Windows versions. */
hr = ID3D10Device1_QueryInterface(device, &IID_IDXGIDevice, (void **)&dxgi_device);
ok(SUCCEEDED(hr), "Device should implement IDXGIDevice.\n");
hr = IDXGIDevice_GetParent(dxgi_device, &IID_IDXGIAdapter, (void **)&dxgi_adapter);
ok(SUCCEEDED(hr), "Device parent should implement IDXGIAdapter.\n");
hr = IDXGIAdapter_GetParent(dxgi_adapter, &IID_IDXGIFactory, (void **)&iface);
ok(SUCCEEDED(hr), "Adapter parent should implement IDXGIFactory.\n");
IUnknown_Release(iface);
IDXGIAdapter_Release(dxgi_adapter);
hr = IDXGIDevice_GetParent(dxgi_device, &IID_IDXGIAdapter1, (void **)&dxgi_adapter);
ok(SUCCEEDED(hr), "Device parent should implement IDXGIAdapter1.\n");
hr = IDXGIAdapter_GetParent(dxgi_adapter, &IID_IDXGIFactory1, (void **)&iface);
ok(hr == E_NOINTERFACE, "Adapter parent should not implement IDXGIFactory1.\n");
IDXGIAdapter_Release(dxgi_adapter);
IDXGIDevice_Release(dxgi_device);
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
}
for (i = 0; i < ARRAY_SIZE(d3d10_feature_levels); ++i)
{
struct device_desc device_desc;
device_desc.feature_level = d3d10_feature_levels[i];
device_desc.flags = D3D10_CREATE_DEVICE_DEBUG;
if (!(device = create_device(&device_desc)))
{
skip("Failed to create device for feature level %#x.\n", d3d10_feature_levels[i]);
continue;
}
todo_wine
check_interface(device, &IID_ID3D10InfoQueue, TRUE, FALSE);
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
}
}
static void test_create_shader_resource_view(void)
{
D3D10_SHADER_RESOURCE_VIEW_DESC1 srv_desc;
D3D10_TEXTURE2D_DESC texture_desc;
ULONG refcount, expected_refcount;
ID3D10ShaderResourceView1 *srview;
D3D10_BUFFER_DESC buffer_desc;
ID3D10Texture2D *texture;
ID3D10Device *tmp_device;
ID3D10Device1 *device;
ID3D10Buffer *buffer;
HRESULT hr;
if (!(device = create_device(NULL)))
{
skip("Failed to create device.\n");
return;
}
buffer_desc.ByteWidth = 1024;
buffer_desc.Usage = D3D10_USAGE_DEFAULT;
buffer_desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
buffer_desc.CPUAccessFlags = 0;
buffer_desc.MiscFlags = 0;
hr = ID3D10Device1_CreateBuffer(device, &buffer_desc, NULL, &buffer);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = ID3D10Device1_CreateShaderResourceView1(device, (ID3D10Resource *)buffer, NULL, &srview);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
srv_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
srv_desc.ViewDimension = D3D10_1_SRV_DIMENSION_BUFFER;
U(srv_desc).Buffer.ElementOffset = 0;
U(srv_desc).Buffer.ElementWidth = 64;
hr = ID3D10Device1_CreateShaderResourceView1(device, NULL, &srv_desc, &srview);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
expected_refcount = get_refcount((IUnknown *)device) + 1;
hr = ID3D10Device1_CreateShaderResourceView1(device, (ID3D10Resource *)buffer, &srv_desc, &srview);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
refcount = get_refcount((IUnknown *)device);
ok(refcount >= expected_refcount, "Got unexpected refcount %lu, expected >= %lu.\n", refcount, expected_refcount);
tmp_device = NULL;
expected_refcount = refcount + 1;
ID3D10ShaderResourceView1_GetDevice(srview, &tmp_device);
ok(tmp_device == (ID3D10Device *)device, "Got unexpected device %p, expected %p.\n", tmp_device, device);
refcount = get_refcount((IUnknown *)device);
ok(refcount == expected_refcount, "Got unexpected refcount %lu, expected %lu.\n", refcount, expected_refcount);
ID3D10Device_Release(tmp_device);
check_interface(srview, &IID_ID3D10ShaderResourceView, TRUE, FALSE);
/* Not available on all Windows versions. */
check_interface(srview, &IID_ID3D11ShaderResourceView, TRUE, TRUE);
ID3D10ShaderResourceView1_Release(srview);
ID3D10Buffer_Release(buffer);
/* Without D3D10_BIND_SHADER_RESOURCE. */
buffer_desc.ByteWidth = 1024;
buffer_desc.Usage = D3D10_USAGE_DEFAULT;
buffer_desc.BindFlags = 0;
buffer_desc.CPUAccessFlags = 0;
buffer_desc.MiscFlags = 0;
hr = ID3D10Device1_CreateBuffer(device, &buffer_desc, NULL, &buffer);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = ID3D10Device1_CreateShaderResourceView1(device, (ID3D10Resource *)buffer, &srv_desc, &srview);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
ID3D10Buffer_Release(buffer);
texture_desc.Width = 512;
texture_desc.Height = 512;
texture_desc.MipLevels = 0;
texture_desc.ArraySize = 1;
texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texture_desc.SampleDesc.Count = 1;
texture_desc.SampleDesc.Quality = 0;
texture_desc.Usage = D3D10_USAGE_DEFAULT;
texture_desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
texture_desc.CPUAccessFlags = 0;
texture_desc.MiscFlags = 0;
hr = ID3D10Device1_CreateTexture2D(device, &texture_desc, NULL, &texture);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = ID3D10Device1_CreateShaderResourceView1(device, (ID3D10Resource *)texture, NULL, &srview);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
ID3D10ShaderResourceView1_GetDesc1(srview, &srv_desc);
ok(srv_desc.Format == texture_desc.Format, "Got unexpected format %#x.\n", srv_desc.Format);
ok(srv_desc.ViewDimension == D3D10_1_SRV_DIMENSION_TEXTURE2D,
"Got unexpected view dimension %#x.\n", srv_desc.ViewDimension);
ok(U(srv_desc).Texture2D.MostDetailedMip == 0, "Got unexpected MostDetailedMip %u.\n",
U(srv_desc).Texture2D.MostDetailedMip);
ok(U(srv_desc).Texture2D.MipLevels == 10, "Got unexpected MipLevels %u.\n", U(srv_desc).Texture2D.MipLevels);
check_interface(srview, &IID_ID3D10ShaderResourceView, TRUE, FALSE);
/* Not available on all Windows versions. */
check_interface(srview, &IID_ID3D11ShaderResourceView, TRUE, TRUE);
ID3D10ShaderResourceView1_Release(srview);
ID3D10Texture2D_Release(texture);
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
}
static void test_create_blend_state(void)
{
static const D3D10_BLEND_DESC1 desc_conversion_tests[] =
{
{
FALSE, FALSE,
{
{
FALSE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD
},
},
},
{
FALSE, TRUE,
{
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
FALSE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_RED
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
FALSE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_GREEN
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
},
},
{
FALSE, TRUE,
{
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_SUBTRACT,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ZERO, D3D10_BLEND_ONE, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ZERO, D3D10_BLEND_ONE, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ONE, D3D10_BLEND_OP_MAX,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
TRUE, D3D10_BLEND_ONE, D3D10_BLEND_ONE, D3D10_BLEND_OP_MIN,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
FALSE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
{
FALSE, D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD,
D3D10_BLEND_ONE, D3D10_BLEND_ZERO, D3D10_BLEND_OP_ADD, D3D10_COLOR_WRITE_ENABLE_ALL
},
},
},
};
ID3D10BlendState1 *blend_state1, *blend_state2;
D3D10_BLEND_DESC1 desc, obtained_desc;
ID3D10BlendState *d3d10_blend_state;
D3D10_BLEND_DESC d3d10_blend_desc;
ULONG refcount, expected_refcount;
ID3D10Device1 *device;
ID3D10Device *tmp;
unsigned int i, j;
HRESULT hr;
if (!(device = create_device(NULL)))
{
skip("Failed to create device.\n");
return;
}
hr = ID3D10Device1_CreateBlendState1(device, NULL, &blend_state1);
ok(hr == E_INVALIDARG, "Got unexpected hr %#lx.\n", hr);
memset(&desc, 0, sizeof(desc));
desc.AlphaToCoverageEnable = FALSE;
desc.IndependentBlendEnable = FALSE;
desc.RenderTarget[0].BlendEnable = FALSE;
desc.RenderTarget[0].SrcBlend = D3D10_BLEND_ONE;
desc.RenderTarget[0].DestBlend = D3D10_BLEND_ZERO;
desc.RenderTarget[0].BlendOp = D3D10_BLEND_OP_ADD;
desc.RenderTarget[0].SrcBlendAlpha = D3D10_BLEND_ONE;
desc.RenderTarget[0].DestBlendAlpha = D3D10_BLEND_ZERO;
desc.RenderTarget[0].BlendOpAlpha = D3D10_BLEND_OP_ADD;
desc.RenderTarget[0].RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
expected_refcount = get_refcount((IUnknown *)device) + 1;
hr = ID3D10Device1_CreateBlendState1(device, &desc, &blend_state1);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = ID3D10Device1_CreateBlendState1(device, &desc, &blend_state2);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
ok(blend_state1 == blend_state2, "Got different blend state objects.\n");
refcount = get_refcount((IUnknown *)device);
ok(refcount >= expected_refcount, "Got unexpected refcount %lu, expected >= %lu.\n", refcount, expected_refcount);
tmp = NULL;
expected_refcount = refcount + 1;
ID3D10BlendState1_GetDevice(blend_state1, &tmp);
ok(tmp == (ID3D10Device *)device, "Got unexpected device %p, expected %p.\n", tmp, device);
refcount = get_refcount((IUnknown *)device);
ok(refcount == expected_refcount, "Got unexpected refcount %lu, expected %lu.\n", refcount, expected_refcount);
ID3D10Device_Release(tmp);
ID3D10BlendState1_GetDesc1(blend_state1, &obtained_desc);
ok(obtained_desc.AlphaToCoverageEnable == FALSE, "Got unexpected alpha to coverage enable %#x.\n",
obtained_desc.AlphaToCoverageEnable);
ok(obtained_desc.IndependentBlendEnable == FALSE, "Got unexpected independent blend enable %#x.\n",
obtained_desc.IndependentBlendEnable);
for (i = 0; i < D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
{
ok(obtained_desc.RenderTarget[i].BlendEnable == FALSE,
"Got unexpected blend enable %#x for render target %u.\n",
obtained_desc.RenderTarget[i].BlendEnable, i);
ok(obtained_desc.RenderTarget[i].SrcBlend == D3D10_BLEND_ONE,
"Got unexpected src blend %u for render target %u.\n",
obtained_desc.RenderTarget[i].SrcBlend, i);
ok(obtained_desc.RenderTarget[i].DestBlend == D3D10_BLEND_ZERO,
"Got unexpected dest blend %u for render target %u.\n",
obtained_desc.RenderTarget[i].DestBlend, i);
ok(obtained_desc.RenderTarget[i].BlendOp == D3D10_BLEND_OP_ADD,
"Got unexpected blend op %u for render target %u.\n",
obtained_desc.RenderTarget[i].BlendOp, i);
ok(obtained_desc.RenderTarget[i].SrcBlendAlpha == D3D10_BLEND_ONE,
"Got unexpected src blend alpha %u for render target %u.\n",
obtained_desc.RenderTarget[i].SrcBlendAlpha, i);
ok(obtained_desc.RenderTarget[i].DestBlendAlpha == D3D10_BLEND_ZERO,
"Got unexpected dest blend alpha %u for render target %u.\n",
obtained_desc.RenderTarget[i].DestBlendAlpha, i);
ok(obtained_desc.RenderTarget[i].BlendOpAlpha == D3D10_BLEND_OP_ADD,
"Got unexpected blend op alpha %u for render target %u.\n",
obtained_desc.RenderTarget[i].BlendOpAlpha, i);
ok(obtained_desc.RenderTarget[i].RenderTargetWriteMask == D3D10_COLOR_WRITE_ENABLE_ALL,
"Got unexpected render target write mask %#x for render target %u.\n",
obtained_desc.RenderTarget[0].RenderTargetWriteMask, i);
}
check_interface(blend_state1, &IID_ID3D10BlendState, TRUE, FALSE);
/* Not available on all Windows versions. */
check_interface(blend_state1, &IID_ID3D11BlendState, TRUE, TRUE);
refcount = ID3D10BlendState1_Release(blend_state1);
ok(refcount == 1, "Got unexpected refcount %lu.\n", refcount);
refcount = ID3D10BlendState1_Release(blend_state2);
ok(!refcount, "Blend state has %lu references left.\n", refcount);
for (i = 0; i < ARRAY_SIZE(desc_conversion_tests); ++i)
{
const D3D10_BLEND_DESC1 *current_desc = &desc_conversion_tests[i];
hr = ID3D10Device1_CreateBlendState1(device, current_desc, &blend_state1);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = ID3D10BlendState1_QueryInterface(blend_state1, &IID_ID3D10BlendState, (void **)&d3d10_blend_state);
ok(SUCCEEDED(hr), "Blend state should implement ID3D10BlendState.\n");
ID3D10BlendState_GetDesc(d3d10_blend_state, &d3d10_blend_desc);
ok(d3d10_blend_desc.AlphaToCoverageEnable == current_desc->AlphaToCoverageEnable,
"Got unexpected alpha to coverage enable %#x for test %u.\n",
d3d10_blend_desc.AlphaToCoverageEnable, i);
ok(d3d10_blend_desc.SrcBlend == current_desc->RenderTarget[0].SrcBlend,
"Got unexpected src blend %u for test %u.\n", d3d10_blend_desc.SrcBlend, i);
ok(d3d10_blend_desc.DestBlend == current_desc->RenderTarget[0].DestBlend,
"Got unexpected dest blend %u for test %u.\n", d3d10_blend_desc.DestBlend, i);
ok(d3d10_blend_desc.BlendOp == current_desc->RenderTarget[0].BlendOp,
"Got unexpected blend op %u for test %u.\n", d3d10_blend_desc.BlendOp, i);
ok(d3d10_blend_desc.SrcBlendAlpha == current_desc->RenderTarget[0].SrcBlendAlpha,
"Got unexpected src blend alpha %u for test %u.\n", d3d10_blend_desc.SrcBlendAlpha, i);
ok(d3d10_blend_desc.DestBlendAlpha == current_desc->RenderTarget[0].DestBlendAlpha,
"Got unexpected dest blend alpha %u for test %u.\n", d3d10_blend_desc.DestBlendAlpha, i);
ok(d3d10_blend_desc.BlendOpAlpha == current_desc->RenderTarget[0].BlendOpAlpha,
"Got unexpected blend op alpha %u for test %u.\n", d3d10_blend_desc.BlendOpAlpha, i);
for (j = 0; j < D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT; j++)
{
unsigned int k = current_desc->IndependentBlendEnable ? j : 0;
ok(d3d10_blend_desc.BlendEnable[j] == current_desc->RenderTarget[k].BlendEnable,
"Got unexpected blend enable %#x for test %u, render target %u.\n",
d3d10_blend_desc.BlendEnable[j], i, j);
ok(d3d10_blend_desc.RenderTargetWriteMask[j] == current_desc->RenderTarget[k].RenderTargetWriteMask,
"Got unexpected render target write mask %#x for test %u, render target %u.\n",
d3d10_blend_desc.RenderTargetWriteMask[j], i, j);
}
ID3D10BlendState_Release(d3d10_blend_state);
refcount = ID3D10BlendState1_Release(blend_state1);
ok(!refcount, "Got unexpected refcount %lu.\n", refcount);
}
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
}
static void test_getdc(void)
{
struct device_desc device_desc;
D3D10_TEXTURE2D_DESC desc;
ID3D10Texture2D *texture;
IDXGISurface1 *surface1;
ID3D10Device1 *device;
ULONG refcount;
HRESULT hr;
HDC dc;
device_desc.feature_level = D3D10_FEATURE_LEVEL_10_1;
device_desc.flags = D3D10_CREATE_DEVICE_BGRA_SUPPORT;
if (!(device = create_device(&device_desc)))
{
skip("Failed to create device.\n");
return;
}
/* Without D3D10_RESOURCE_MISC_GDI_COMPATIBLE. */
desc.Width = 512;
desc.Height = 512;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D10_USAGE_DEFAULT;
desc.BindFlags = D3D10_BIND_RENDER_TARGET;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
hr = ID3D10Device1_CreateTexture2D(device, &desc, NULL, &texture);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = ID3D10Texture2D_QueryInterface(texture, &IID_IDXGISurface1, (void**)&surface1);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = IDXGISurface1_GetDC(surface1, FALSE, &dc);
todo_wine ok(hr == DXGI_ERROR_INVALID_CALL, "Got unexpected hr %#lx.\n", hr);
IDXGISurface1_Release(surface1);
ID3D10Texture2D_Release(texture);
desc.MiscFlags = D3D10_RESOURCE_MISC_GDI_COMPATIBLE;
hr = ID3D10Device1_CreateTexture2D(device, &desc, NULL, &texture);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = ID3D10Texture2D_QueryInterface(texture, &IID_IDXGISurface1, (void**)&surface1);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = IDXGISurface1_ReleaseDC(surface1, NULL);
todo_wine ok(hr == DXGI_ERROR_INVALID_CALL, "Got unexpected hr %#lx.\n", hr);
hr = IDXGISurface1_GetDC(surface1, FALSE, &dc);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
/* One more time. */
dc = (HDC)0xdeadbeef;
hr = IDXGISurface1_GetDC(surface1, FALSE, &dc);
todo_wine ok(hr == DXGI_ERROR_INVALID_CALL, "Got unexpected hr %#lx.\n", hr);
ok(dc == (HDC)0xdeadbeef, "Got unexpected dc %p.\n", dc);
hr = IDXGISurface1_ReleaseDC(surface1, NULL);
ok(hr == S_OK, "Got unexpected hr %#lx.\n", hr);
hr = IDXGISurface1_ReleaseDC(surface1, NULL);
todo_wine ok(hr == DXGI_ERROR_INVALID_CALL, "Got unexpected hr %#lx.\n", hr);
IDXGISurface1_Release(surface1);
ID3D10Texture2D_Release(texture);
refcount = ID3D10Device1_Release(device);
ok(!refcount, "Device has %lu references left.\n", refcount);
}
START_TEST(d3d10_1)
{
test_create_device();
test_device_interfaces();
test_create_shader_resource_view();
test_create_blend_state();
test_getdc();
}
| 44.656619 | 119 | 0.681185 | [
"render"
] |
32210597bf48a1c86c33d2b4d88aad8abb12ab82 | 5,509 | h | C | hi_components/drag_plot/SliderPack.h | psobot/HISE | cb97378039bae22c8eade3d4b699931bfd65c7d1 | [
"Intel",
"MIT"
] | 1 | 2021-03-04T19:37:06.000Z | 2021-03-04T19:37:06.000Z | hi_components/drag_plot/SliderPack.h | psobot/HISE | cb97378039bae22c8eade3d4b699931bfd65c7d1 | [
"Intel",
"MIT"
] | null | null | null | hi_components/drag_plot/SliderPack.h | psobot/HISE | cb97378039bae22c8eade3d4b699931bfd65c7d1 | [
"Intel",
"MIT"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE 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.
*
* HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which must be separately licensed for closed source applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
#ifndef SLIDERPACK_H_INCLUDED
#define SLIDERPACK_H_INCLUDED
namespace hise { using namespace juce;
/** The data model for a SliderPack widget. */
class SliderPackData: public SafeChangeBroadcaster
{
public:
SliderPackData();
~SliderPackData();
void setRange(double minValue, double maxValue, double stepSize);
Range<double> getRange() const;
double getStepSize() const;
void setNumSliders(int numSliders);
int getNumSliders() const;
void setValue(int sliderIndex, float value, NotificationType notifySliderPack=dontSendNotification);
float getValue(int index) const;
void setFromFloatArray(const Array<float> &valueArray);
void writeToFloatArray(Array<float> &valueArray) const;
String toBase64() const;
void fromBase64(const String &encodedValues);
int getNextIndexToDisplay() const
{
return nextIndexToDisplay;
}
void clearDisplayIndex()
{
nextIndexToDisplay = -1;
}
void swapData(Array<var> &otherData)
{
values = var(otherData);
sendChangeMessage();
}
void setDisplayedIndex(int index)
{
nextIndexToDisplay = index;
sendAllocationFreeChangeMessage();
}
var getDataArray() const { return values; }
void setFlashActive(bool shouldBeShown) { flashActive = shouldBeShown; };
void setShowValueOverlay(bool shouldBeShown) { showValueOverlay = shouldBeShown; };
bool isFlashActive() const { return flashActive; }
bool isValueOverlayShown() const { return showValueOverlay; }
private:
bool flashActive;
bool showValueOverlay;
WeakReference<SliderPackData>::Master masterReference;
friend class WeakReference < SliderPackData > ;
int nextIndexToDisplay;
Range<double> sliderRange;
double stepSize;
var values;
//Array<float> values;
};
/** A widget which contains multiple Sliders which support dragging & bipolar display. */
class SliderPack : public Component,
public Slider::Listener,
public SafeChangeListener,
public Timer
{
public:
class Listener
{
public:
virtual ~Listener();
virtual void sliderPackChanged(SliderPack *s, int index ) = 0;
private:
WeakReference<Listener>::Master masterReference;
friend class WeakReference<Listener>;
};
SET_GENERIC_PANEL_ID("ArrayEditor");
/** Creates a new SliderPack. */
SliderPack(SliderPackData *data=nullptr);
~SliderPack();
void addListener(Listener *listener)
{
listeners.addIfNotAlreadyThere(listener);
}
void removeListener(Listener *listener)
{
listeners.removeAllInstancesOf(listener);
}
void timerCallback() override;
/** Sets the number of sliders shown. This clears all values. */
void setNumSliders(int numSliders);
/** Returns the value of the slider index. If the index is bigger than the slider amount, it will return -1. */
double getValue(int sliderIndex);
/** Sets the value of one of the sliders. If the index is bigger than the slider amount, it will do nothing. */
void setValue(int sliderIndex, double newValue);
void updateSliders();
void changeListenerCallback(SafeChangeBroadcaster *b) override;
void mouseDown(const MouseEvent &e) override;
void mouseDrag(const MouseEvent &e) override;
void mouseUp(const MouseEvent &e) override;
void mouseDoubleClick(const MouseEvent &e) override;
void mouseExit(const MouseEvent &e) override;
void update();
void sliderValueChanged(Slider *s) override;
void paintOverChildren(Graphics &g) override;
void paint(Graphics &g);
void setSuffix(const String &suffix);
void setDisplayedIndex(int displayIndex);
void setDefaultValue(double defaultValue);
void setColourForSliders(int colourId, Colour c);
const SliderPackData* getData() const { return data; }
void resized() override;
void setValuesFromLine();
int getNumSliders();
void setFlashActive(bool setFlashActive);
void setShowValueOverlay(bool shouldShowValueOverlay);
void setStepSize(double stepSize);
private:
SliderPackData dummyData;
Array<WeakReference<Listener>> listeners;
String suffix;
double defaultValue;
Array<float> displayAlphas;
Line<float> rightClickLine;
bool currentlyDragged;
int currentlyDraggedSlider;
double currentlyDraggedSliderValue;
BiPolarSliderLookAndFeel laf;
WeakReference<SliderPackData> data;
OwnedArray<Slider> sliders;
};
} // namespace hise
#endif // SLIDERPACK_H_INCLUDED
| 23.050209 | 112 | 0.731712 | [
"model"
] |
32212014fbe91632e9bb80b5307725d16e758d1a | 1,600 | c | C | release/src-rt/linux/linux-2.6/arch/alpha/kernel/irq_srm.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src-rt/linux/linux-2.6/arch/alpha/kernel/irq_srm.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | arch/alpha/kernel/irq_srm.c | KylinskyChen/linuxCore_2.6.24 | 11e90b14386491cc80477d4015e0c8f673f6d020 | [
"MIT"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | /*
* Handle interrupts from the SRM, assuming no additional weirdness.
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/irq.h>
#include "proto.h"
#include "irq_impl.h"
/*
* Is the palcode SMP safe? In other words: can we call cserve_ena/dis
* at the same time in multiple CPUs? To be safe I added a spinlock
* but it can be removed trivially if the palcode is robust against smp.
*/
DEFINE_SPINLOCK(srm_irq_lock);
static inline void
srm_enable_irq(unsigned int irq)
{
spin_lock(&srm_irq_lock);
cserve_ena(irq - 16);
spin_unlock(&srm_irq_lock);
}
static void
srm_disable_irq(unsigned int irq)
{
spin_lock(&srm_irq_lock);
cserve_dis(irq - 16);
spin_unlock(&srm_irq_lock);
}
static unsigned int
srm_startup_irq(unsigned int irq)
{
srm_enable_irq(irq);
return 0;
}
static void
srm_end_irq(unsigned int irq)
{
if (!(irq_desc[irq].status & (IRQ_DISABLED|IRQ_INPROGRESS)))
srm_enable_irq(irq);
}
/* Handle interrupts from the SRM, assuming no additional weirdness. */
static struct hw_interrupt_type srm_irq_type = {
.typename = "SRM",
.startup = srm_startup_irq,
.shutdown = srm_disable_irq,
.enable = srm_enable_irq,
.disable = srm_disable_irq,
.ack = srm_disable_irq,
.end = srm_end_irq,
};
void __init
init_srm_irqs(long max, unsigned long ignore_mask)
{
long i;
for (i = 16; i < max; ++i) {
if (i < 64 && ((ignore_mask >> i) & 1))
continue;
irq_desc[i].status = IRQ_DISABLED | IRQ_LEVEL;
irq_desc[i].chip = &srm_irq_type;
}
}
void
srm_device_interrupt(unsigned long vector)
{
int irq = (vector - 0x800) >> 4;
handle_irq(irq);
}
| 20 | 72 | 0.715 | [
"vector"
] |
3221ad6d8558a84df709c1d5d794eb40fbfc5a3f | 4,534 | c | C | erts/etc/win32/msys_tools/vc/coffix.c | williamthome/otp | c4f24d6718ac56c431f0fccf240c5b15482792ed | [
"Apache-2.0"
] | 13 | 2018-12-01T15:19:46.000Z | 2022-02-02T10:20:43.000Z | erts/etc/win32/msys_tools/vc/coffix.c | williamthome/otp | c4f24d6718ac56c431f0fccf240c5b15482792ed | [
"Apache-2.0"
] | 11 | 2021-12-15T16:23:47.000Z | 2022-01-10T10:12:42.000Z | erts/etc/win32/msys_tools/vc/coffix.c | williamthome/otp | c4f24d6718ac56c431f0fccf240c5b15482792ed | [
"Apache-2.0"
] | 2 | 2019-04-02T11:59:09.000Z | 2019-04-02T12:18:07.000Z | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 1999-2021. 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.
*
* %CopyrightEnd%
*/
/*
** This mini tool fixes an incompatibility between
** Microsoft's tools, who dont like the virtual size being put in
** the physical address field, but rely on the raw size field for
** sizing the ".bss" section.
** This fixes some of the problems with linking gcc compiled objects
** together with MSVC dito.
**
** Courtesy DJ Delorie for describing the COFF file format on
** http://www.delorie.com/djgpp/doc/coff/
** The coff structures are fetched from Microsofts headers though.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <windows.h>
#include <winnt.h> /* Structure definitions for PE (COFF) */
static int dump_edit(char *filename, int edit);
static int v_printf(char *format, ...);
char *progname;
int verbose = 0;
int main(int argc, char **argv)
{
int findex = 1;
int edit = 0;
int ret;
progname = argv[0];
if (argc == 1) {
fprintf(stderr,"Format : %s [-e] [-v] <filename>\n", progname);
return 1;
}
for (findex = 1;
findex < argc && (*argv[findex] == '-' || *argv[findex] == '/');
++findex)
switch (argv[findex][1]) {
case 'e':
case 'E':
edit = 1;
break;
case 'v':
case 'V':
verbose = 1;
default:
fprintf(stderr, "%s: unknown option %s\n", progname, argv[findex]);
break;
}
if (findex == argc) {
fprintf(stderr,"%s: No filenames given.\n", progname);
return 1;
}
for(; findex < argc; ++findex)
if ((ret = dump_edit(argv[findex],edit)) != 0)
return ret;
return 0;
}
int dump_edit(char *filename, int edit)
{
FILE *f = fopen(filename, (edit) ? "r+b" : "rb");
IMAGE_FILE_HEADER filhdr;
IMAGE_SECTION_HEADER scnhdr;
int i;
if (f == NULL) {
fprintf(stderr, "%s: cannot open %s.\n", progname, filename);
return 1;
}
if (fread(&filhdr, sizeof(filhdr), 1, f) == 0) {
fprintf(stderr,"%s: Could not read COFF header from %s,"
" is this a PE (COFF) file?\n", progname, filename);
fclose(f);
return 1;
}
v_printf("File: %s\n", filename);
v_printf("Magic number: 0x%08x\n", filhdr.Machine);
v_printf("Number of sections: %d\n",filhdr.NumberOfSections);
if (fseek(f, (long) filhdr.SizeOfOptionalHeader, SEEK_CUR) != 0) {
fprintf(stderr,"%s: Could not read COFF optional header from %s,"
" is this a PE (COFF) file?\n", progname, filename);
fclose(f);
return 1;
}
for (i = 0; i < filhdr.NumberOfSections; ++i) {
if (fread(&scnhdr, sizeof(scnhdr), 1, f) == 0) {
fprintf(stderr,"%s: Could not read section header from %s,"
" is this a PE (COFF) file?\n", progname, filename);
fclose(f);
return 1;
}
v_printf("Section %s:\n", scnhdr.Name);
v_printf("Physical address: 0x%08x\n", scnhdr.Misc.PhysicalAddress);
v_printf("Size: 0x%08x\n", scnhdr.SizeOfRawData);
if (scnhdr.Misc.PhysicalAddress != 0 &&
scnhdr.SizeOfRawData == 0) {
printf("Section header %s in file %s will confuse MSC linker, "
"virtual size is 0x%08x and raw size is 0\n",
scnhdr.Name, filename, scnhdr.Misc.PhysicalAddress,
scnhdr.SizeOfRawData);
if (edit) {
scnhdr.SizeOfRawData = scnhdr.Misc.PhysicalAddress;
scnhdr.Misc.PhysicalAddress = 0;
if (fseek(f, (long) -((long)sizeof(scnhdr)), SEEK_CUR) != 0 ||
fwrite(&scnhdr, sizeof(scnhdr), 1, f) == 0) {
fprintf(stderr,"%s: could not edit file %s.\n",
progname, filename);
fclose(f);
return 1;
}
printf("Edited object, virtual size is now 0, and "
"raw size is 0x%08x.\n", scnhdr.SizeOfRawData);
} else {
printf("Specify option '-e' to correct the problem.\n");
}
}
}
fclose(f);
return 0;
}
static int v_printf(char *format, ...)
{
va_list ap;
int ret = 0;
if (verbose) {
va_start(ap, format);
ret = vfprintf(stdout, format, ap);
va_end(ap);
}
return ret;
}
| 27.815951 | 75 | 0.63498 | [
"object"
] |
3228a22ba1e6f7360e63d4174e3754f43498c62f | 2,469 | h | C | ADApp/pluginTests/AsynPortClientContainer.h | MichaelHuth/ADCore | b1b9d99646eb13ba3399e4f3fe7d568591fecab1 | [
"MIT"
] | null | null | null | ADApp/pluginTests/AsynPortClientContainer.h | MichaelHuth/ADCore | b1b9d99646eb13ba3399e4f3fe7d568591fecab1 | [
"MIT"
] | 1 | 2018-01-15T12:36:53.000Z | 2018-01-15T13:24:21.000Z | ADApp/pluginTests/AsynPortClientContainer.h | MichaelHuth/ADCore | b1b9d99646eb13ba3399e4f3fe7d568591fecab1 | [
"MIT"
] | null | null | null | /*
* AsynPortClientContainer.h
*
* Created on: 10 Mar 2015
* Author: gnx91527
*/
#ifndef IOCS_SIMDETECTORNOIOC_SIMDETECTORNOIOCAPP_SRC_AsynPortClientContainer_H_
#define IOCS_SIMDETECTORNOIOC_SIMDETECTORNOIOCAPP_SRC_AsynPortClientContainer_H_
#include <boost/shared_ptr.hpp>
#include <map>
#include <vector>
#include <epicsThread.h>
#include <asynPortClient.h>
#include "AsynException.h"
typedef std::map<std::string, boost::shared_ptr<asynInt32Client> > int32ClientMap;
typedef std::map<std::string, boost::shared_ptr<asynFloat64Client> > float64ClientMap;
typedef std::map<std::string, boost::shared_ptr<asynOctetClient> > octetClientMap;
class AsynPortClientContainer {
public:
static const int max_string_parameter_len = 1024;
AsynPortClientContainer(const std::string& port);
virtual void write(const std::string& paramName, int value, int address=0);
virtual void write(const std::string& paramName, double value, int address=0);
virtual unsigned long int write(const std::string& paramName, const std::string& value, int address=0);
virtual int readInt(const std::string& paramName, int address=0);
virtual double readDouble(const std::string& paramName, int address=0);
virtual std::string readString(const std::string& paramName, int address=0);
virtual void cleanup();
virtual ~AsynPortClientContainer();
protected:
std::string portName;
private:
std::vector<boost::shared_ptr<int32ClientMap> > int32Maps;
std::vector<boost::shared_ptr<float64ClientMap> > float64Maps;
std::vector<boost::shared_ptr<octetClientMap> > octetMaps;
boost::shared_ptr<int32ClientMap> getInt32Map(int address);
boost::shared_ptr<float64ClientMap> getFloat64Map(int address);
boost::shared_ptr<octetClientMap> getOctetMap(int address);
template<class T> boost::shared_ptr<T> processMap(std::vector<boost::shared_ptr<T> >& Maps, int address)
{
boost::shared_ptr<T> mapPtr;
// Check vector entry
if ((int)Maps.size() <= address) {
// Extend vector
Maps.resize(address + 1);
}
if (Maps[address].get() == NULL){
// Add map to vector
mapPtr = boost::shared_ptr<T>(new T());
Maps[address] = mapPtr;
} else {
// Get existing map
mapPtr = Maps[address];
}
return mapPtr;
}
};
#endif /* IOCS_SIMDETECTORNOIOC_SIMDETECTORNOIOCAPP_SRC_AsynPortClientContainer_H_ */
| 33.821918 | 108 | 0.711219 | [
"vector"
] |
322932852eb86d6f7c0dbc8d0fb90d94cbcfed55 | 5,083 | h | C | opensimAD-install/sdk/include/OpenSim/Common/Sine.h | Lars-DHondt-KUL/opensimAD | 144a09414a52ed4fa3c538580dc8d79ee5f56bfb | [
"Apache-2.0"
] | 12 | 2021-10-04T14:10:20.000Z | 2022-03-01T17:59:35.000Z | opensimAD-install/sdk/include/OpenSim/Common/Sine.h | Lars-DHondt-KUL/opensimAD | 144a09414a52ed4fa3c538580dc8d79ee5f56bfb | [
"Apache-2.0"
] | 2 | 2021-10-04T14:44:59.000Z | 2021-10-04T15:05:23.000Z | opensimAD-install/sdk/include/OpenSim/Common/Sine.h | Lars-DHondt-KUL/opensimAD | 144a09414a52ed4fa3c538580dc8d79ee5f56bfb | [
"Apache-2.0"
] | 1 | 2021-11-27T13:25:22.000Z | 2021-11-27T13:25:22.000Z | #ifndef OPENSIM_SINE_H_
#define OPENSIM_SINE_H_
/* -------------------------------------------------------------------------- *
* OpenSim: Sine.h *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ajay Seth *
* *
* 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. *
* -------------------------------------------------------------------------- */
// INCLUDES
#include <string>
#include "Function.h"
#include "FunctionAdapter.h"
namespace OpenSim {
//=============================================================================
//=============================================================================
/**
* A class for representing a Sine function.
*
* This class inherits from Function and can be used as input to
* any Component requiring a Function as input. Implements:
* f(x) = amplitude*sin(omega*x+phase)+offset;
*
* @author Ajay Seth
* @version 1.0
*/
class OSIMCOMMON_API Sine : public Function {
OpenSim_DECLARE_CONCRETE_OBJECT(Sine, Function);
protected:
//==============================================================================
// PROPERTIES
//==============================================================================
OpenSim_DECLARE_PROPERTY(amplitude, osim_double_adouble,
"The amplitude of the sinusoidal function.");
OpenSim_DECLARE_PROPERTY(omega, osim_double_adouble,
"The angular frequency (omega) in radians/sec.");
OpenSim_DECLARE_PROPERTY(phase, osim_double_adouble,
"The phase shift of the sinusoidal function.");
OpenSim_DECLARE_PROPERTY(offset, osim_double_adouble,
"The DC offset in the sinusoidal function.");
//=============================================================================
// METHODS
//=============================================================================
public:
//Default construct, copy and assignment
Sine() {
constructProperties();
}
// Convenience Constructor
Sine(osim_double_adouble amplitude, osim_double_adouble omega, osim_double_adouble phase, osim_double_adouble offset=0) : Sine()
{
set_amplitude(amplitude);
set_omega(omega);
set_phase(phase);
set_offset(offset);
}
virtual ~Sine() {};
//--------------------------------------------------------------------------
// EVALUATION
//--------------------------------------------------------------------------
osim_double_adouble calcValue(const SimTK::Vector& x) const override {
return get_amplitude()*sin(get_omega()*x[0] + get_phase())
+ get_offset();
}
osim_double_adouble calcDerivative(const std::vector<int>& derivComponents,
const SimTK::Vector& x) const override {
int n = (int)derivComponents.size();
return get_amplitude()*pow(get_omega(),n) *
sin(get_omega()*x[0] + get_phase() + n*SimTK::Pi/2);
}
SimTK::Function* createSimTKFunction() const override {
return new FunctionAdapter(*this);
}
int getArgumentSize() const override {return 1;}
int getMaxDerivativeOrder() const override {return 10;}
private:
void constructProperties() {
constructProperty_amplitude(1.0);
constructProperty_omega(1.0);
constructProperty_phase(0.0);
constructProperty_offset(0.0);
}
//=============================================================================
}; // END class Sine
//=============================================================================
//=============================================================================
} // end of namespace OpenSim
#endif // OPENSIM_SINE_H_
| 41.663934 | 132 | 0.47649 | [
"vector"
] |
322f31a7ee3cd3466d12835fb6cf489da9c5083d | 3,540 | h | C | Scripts/Template/Headers/org/apache/xpath/functions/FuncNormalizeSpace.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/org/apache/xpath/functions/FuncNormalizeSpace.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/org/apache/xpath/functions/FuncNormalizeSpace.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/antoniocortes/j2objcprj/relases/j2objc/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncNormalizeSpace.java
//
#include "../../../../J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_OrgApacheXpathFunctionsFuncNormalizeSpace")
#ifdef RESTRICT_OrgApacheXpathFunctionsFuncNormalizeSpace
#define INCLUDE_ALL_OrgApacheXpathFunctionsFuncNormalizeSpace 0
#else
#define INCLUDE_ALL_OrgApacheXpathFunctionsFuncNormalizeSpace 1
#endif
#undef RESTRICT_OrgApacheXpathFunctionsFuncNormalizeSpace
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif
#if !defined (OrgApacheXpathFunctionsFuncNormalizeSpace_) && (INCLUDE_ALL_OrgApacheXpathFunctionsFuncNormalizeSpace || defined(INCLUDE_OrgApacheXpathFunctionsFuncNormalizeSpace))
#define OrgApacheXpathFunctionsFuncNormalizeSpace_
#define RESTRICT_OrgApacheXpathFunctionsFunctionDef1Arg 1
#define INCLUDE_OrgApacheXpathFunctionsFunctionDef1Arg 1
#include "../../../../org/apache/xpath/functions/FunctionDef1Arg.h"
@class OrgApacheXpathObjectsXObject;
@class OrgApacheXpathXPathContext;
@protocol OrgXmlSaxContentHandler;
/*!
@brief Execute the normalize-space() function.
*/
@interface OrgApacheXpathFunctionsFuncNormalizeSpace : OrgApacheXpathFunctionsFunctionDef1Arg
@property (readonly, class) jlong serialVersionUID NS_SWIFT_NAME(serialVersionUID);
+ (jlong)serialVersionUID;
#pragma mark Public
- (instancetype __nonnull)init;
/*!
@brief Execute the function.The function must return
a valid object.
@param xctxt The current execution context.
@return A valid XObject.
@throw javax.xml.transform.TransformerException
*/
- (OrgApacheXpathObjectsXObject *)executeWithOrgApacheXpathXPathContext:(OrgApacheXpathXPathContext *)xctxt;
/*!
@brief Execute an expression in the XPath runtime context, and return the
result of the expression.
@param xctxt The XPath runtime context.
@return The result of the expression in the form of a <code>XObject</code>.
@throw javax.xml.transform.TransformerExceptionif a runtime exception
occurs.
*/
- (void)executeCharsToContentHandlerWithOrgApacheXpathXPathContext:(OrgApacheXpathXPathContext *)xctxt
withOrgXmlSaxContentHandler:(id<OrgXmlSaxContentHandler>)handler;
@end
J2OBJC_EMPTY_STATIC_INIT(OrgApacheXpathFunctionsFuncNormalizeSpace)
inline jlong OrgApacheXpathFunctionsFuncNormalizeSpace_get_serialVersionUID(void);
#define OrgApacheXpathFunctionsFuncNormalizeSpace_serialVersionUID -3377956872032190880LL
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathFunctionsFuncNormalizeSpace, serialVersionUID, jlong)
FOUNDATION_EXPORT void OrgApacheXpathFunctionsFuncNormalizeSpace_init(OrgApacheXpathFunctionsFuncNormalizeSpace *self);
FOUNDATION_EXPORT OrgApacheXpathFunctionsFuncNormalizeSpace *new_OrgApacheXpathFunctionsFuncNormalizeSpace_init(void) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT OrgApacheXpathFunctionsFuncNormalizeSpace *create_OrgApacheXpathFunctionsFuncNormalizeSpace_init(void);
J2OBJC_TYPE_LITERAL_HEADER(OrgApacheXpathFunctionsFuncNormalizeSpace)
#endif
#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_OrgApacheXpathFunctionsFuncNormalizeSpace")
| 38.064516 | 178 | 0.84322 | [
"object",
"transform"
] |
3233bb65f7e584d8f4f49b681a66dfebc54e37f8 | 3,506 | h | C | test/pc/e2e/test_peer_factory.h | pablito25sp/webrtc-src | d25c2ac74afc25f65d111771dbfabd6db25d2498 | [
"BSD-3-Clause"
] | 45 | 2020-11-25T06:17:12.000Z | 2022-03-26T03:49:51.000Z | test/pc/e2e/test_peer_factory.h | pablito25sp/webrtc-src | d25c2ac74afc25f65d111771dbfabd6db25d2498 | [
"BSD-3-Clause"
] | 31 | 2020-11-17T05:30:13.000Z | 2021-12-14T02:19:00.000Z | test/pc/e2e/test_peer_factory.h | pablito25sp/webrtc-src | d25c2ac74afc25f65d111771dbfabd6db25d2498 | [
"BSD-3-Clause"
] | 20 | 2020-11-17T06:24:14.000Z | 2022-03-10T07:08:53.000Z | /*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef TEST_PC_E2E_TEST_PEER_FACTORY_H_
#define TEST_PC_E2E_TEST_PEER_FACTORY_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "api/rtc_event_log/rtc_event_log_factory.h"
#include "api/test/peerconnection_quality_test_fixture.h"
#include "modules/audio_device/include/test_audio_device.h"
#include "rtc_base/task_queue.h"
#include "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h"
#include "test/pc/e2e/peer_configurer.h"
#include "test/pc/e2e/peer_connection_quality_test_params.h"
#include "test/pc/e2e/test_peer.h"
namespace webrtc {
namespace webrtc_pc_e2e {
struct RemotePeerAudioConfig {
explicit RemotePeerAudioConfig(
PeerConnectionE2EQualityTestFixture::AudioConfig config)
: sampling_frequency_in_hz(config.sampling_frequency_in_hz),
output_file_name(config.output_dump_file_name) {}
static absl::optional<RemotePeerAudioConfig> Create(
absl::optional<PeerConnectionE2EQualityTestFixture::AudioConfig> config);
int sampling_frequency_in_hz;
absl::optional<std::string> output_file_name;
};
class TestPeerFactory {
public:
// Setups all components, that should be provided to WebRTC
// PeerConnectionFactory and PeerConnection creation methods,
// also will setup dependencies, that are required for media analyzers
// injection.
//
// |signaling_thread| will be provided by test fixture implementation.
// |params| - describes current peer parameters, like current peer video
// streams and audio streams
static std::unique_ptr<TestPeer> CreateTestPeer(
std::unique_ptr<InjectableComponents> components,
std::unique_ptr<Params> params,
std::vector<PeerConfigurerImpl::VideoSource> video_sources,
std::unique_ptr<MockPeerConnectionObserver> observer,
VideoQualityAnalyzerInjectionHelper* video_analyzer_helper,
rtc::Thread* signaling_thread,
absl::optional<RemotePeerAudioConfig> remote_audio_config,
double bitrate_multiplier,
absl::optional<PeerConnectionE2EQualityTestFixture::EchoEmulationConfig>
echo_emulation_config,
rtc::TaskQueue* task_queue);
// Setups all components, that should be provided to WebRTC
// PeerConnectionFactory and PeerConnection creation methods,
// also will setup dependencies, that are required for media analyzers
// injection.
//
// |signaling_thread| will be provided by test fixture implementation.
static std::unique_ptr<TestPeer> CreateTestPeer(
std::unique_ptr<PeerConfigurerImpl> configurer,
std::unique_ptr<MockPeerConnectionObserver> observer,
VideoQualityAnalyzerInjectionHelper* video_analyzer_helper,
rtc::Thread* signaling_thread,
absl::optional<RemotePeerAudioConfig> remote_audio_config,
double bitrate_multiplier,
absl::optional<PeerConnectionE2EQualityTestFixture::EchoEmulationConfig>
echo_emulation_config,
rtc::TaskQueue* task_queue);
};
} // namespace webrtc_pc_e2e
} // namespace webrtc
#endif // TEST_PC_E2E_TEST_PEER_FACTORY_H_
| 39.393258 | 79 | 0.774672 | [
"vector"
] |
9a5865415c795cf15cf12aebb3859f518aa9746e | 2,708 | h | C | stdext/include/stdext/archive/Mem.h | Rahul18728/cerl | 8d90c03b2ffe397021bcb8c7198c713acf840bb4 | [
"MIT"
] | 443 | 2015-03-14T06:04:45.000Z | 2022-01-10T01:30:56.000Z | stdext/include/stdext/archive/Mem.h | Rahul18728/cerl | 8d90c03b2ffe397021bcb8c7198c713acf840bb4 | [
"MIT"
] | null | null | null | stdext/include/stdext/archive/Mem.h | Rahul18728/cerl | 8d90c03b2ffe397021bcb8c7198c713acf840bb4 | [
"MIT"
] | 125 | 2015-03-14T13:08:04.000Z | 2021-12-08T13:03:29.000Z | /* -------------------------------------------------------------------------
// WINX: a C++ template GUI library - MOST SIMPLE BUT EFFECTIVE
//
// This file is a part of the WINX Library.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.txt at this distribution. By using
// this software in any fashion, you are agreeing to be bound by the terms
// of this license. You must not remove this notice, or any other, from
// this software.
//
// Module: stdext/archive/Mem.h
// Creator: xushiwei
// Email: xushiweizh@gmail.com
// Date: 2006-11-29 21:07:06
//
// $Id: Mem.h,v 1.3 2007/01/10 09:36:12 xushiwei Exp $
// -----------------------------------------------------------------------*/
#ifndef STDEXT_ARCHIVE_MEM_H
#define STDEXT_ARCHIVE_MEM_H
#ifndef STDEXT_ARCHIVE_MEMARCHIVE_H
#include "MemArchive.h"
#endif
NS_STDEXT_BEGIN
// -------------------------------------------------------------------------
// class MemReader
typedef MemReadArchive<const char*> PointerReadArchive;
typedef PointerReadArchive MemReader;
// -------------------------------------------------------------------------
// class VectorReader/VectorWriter
typedef std::vector<char> CharVector;
typedef MemWriteArchive<CharVector> VectorWriteArchive;
typedef VectorWriteArchive VectorWriter;
typedef MemReadArchive<CharVector::const_iterator> VectorReadArchive;
typedef VectorReadArchive VectorReader;
// -------------------------------------------------------------------------
// class StringBuilderReader/StringBuilderWriter
typedef VectorWriter StringBuilderWriter;
typedef VectorReader StringBuilderReader;
// -------------------------------------------------------------------------
// class StlStringReader/StlStringWriter
typedef MemWriteArchive<std::string> StlStringWriteArchive;
typedef StlStringWriteArchive StlStringWriter;
typedef MemReadArchive<std::string::const_iterator> StlStringReadArchive;
typedef StlStringReadArchive StlStringReader;
// -------------------------------------------------------------------------
// class DequeReader/DequeWriter, TextPoolReader/TextPoolWriter
#ifdef STDEXT_DEQUE_H
typedef std::Deque<char> CharDeque;
typedef MemWriteArchive<CharDeque> DequeWriteArchive;
typedef DequeWriteArchive DequeWriter;
typedef MemReadArchive<CharDeque::const_iterator> DequeReadArchive;
typedef DequeReadArchive DequeReader;
typedef DequeWriter TextPoolWriter;
typedef DequeReader TextPoolReader;
#endif
NS_STDEXT_END
// -------------------------------------------------------------------------
// $Log: Mem.h,v $
#endif /* STDEXT_ARCHIVE_MEM_H */
| 32.238095 | 76 | 0.622969 | [
"vector"
] |
9a59e91ae865e38614045e685b1010e2cbb682f4 | 22,207 | h | C | Graphics/GraphicsEngineVulkan/include/VulkanUtilities/VulkanCommandBuffer.h | IngoChou/DiligentCore | df6a316b684e2f2214e0b987f735c3e20a1d3418 | [
"Apache-2.0"
] | 1 | 2020-01-22T01:38:42.000Z | 2020-01-22T01:38:42.000Z | Graphics/GraphicsEngineVulkan/include/VulkanUtilities/VulkanCommandBuffer.h | IngoChou/DiligentCore | df6a316b684e2f2214e0b987f735c3e20a1d3418 | [
"Apache-2.0"
] | null | null | null | Graphics/GraphicsEngineVulkan/include/VulkanUtilities/VulkanCommandBuffer.h | IngoChou/DiligentCore | df6a316b684e2f2214e0b987f735c3e20a1d3418 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 Diligent Graphics LLC
*
* 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
*
* 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 OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
#include "vulkan.h"
#include "DebugUtilities.h"
namespace VulkanUtilities
{
class VulkanCommandBuffer
{
public:
VulkanCommandBuffer(VkPipelineStageFlags EnabledGraphicsShaderStages) noexcept :
m_EnabledGraphicsShaderStages{EnabledGraphicsShaderStages}
{}
// clang-format off
VulkanCommandBuffer (const VulkanCommandBuffer&) = delete;
VulkanCommandBuffer ( VulkanCommandBuffer&&) = delete;
VulkanCommandBuffer& operator = (const VulkanCommandBuffer&) = delete;
VulkanCommandBuffer& operator = ( VulkanCommandBuffer&&) = delete;
// clang-format on
__forceinline void ClearColorImage(VkImage Image,
const VkClearColorValue& Color,
const VkImageSubresourceRange& Subresource)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass == VK_NULL_HANDLE, "vkCmdClearColorImage() must be called outside of render pass (17.1)");
VERIFY(Subresource.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT, "The aspectMask of all image subresource ranges must only include VK_IMAGE_ASPECT_COLOR_BIT (17.1)");
vkCmdClearColorImage(
m_VkCmdBuffer,
Image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // must be VK_IMAGE_LAYOUT_GENERAL or VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
&Color,
1,
&Subresource);
}
__forceinline void ClearDepthStencilImage(VkImage Image,
const VkClearDepthStencilValue& DepthStencil,
const VkImageSubresourceRange& Subresource)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass == VK_NULL_HANDLE, "vkCmdClearDepthStencilImage() must be called outside of render pass (17.1)");
// clang-format off
VERIFY((Subresource.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0 &&
(Subresource.aspectMask & ~(VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) == 0,
"The aspectMask of all image subresource ranges must only include VK_IMAGE_ASPECT_DEPTH_BIT or VK_IMAGE_ASPECT_STENCIL_BIT(17.1)");
// clang-format on
vkCmdClearDepthStencilImage(
m_VkCmdBuffer,
Image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // must be VK_IMAGE_LAYOUT_GENERAL or VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
&DepthStencil,
1,
&Subresource);
}
__forceinline void ClearAttachment(const VkClearAttachment& Attachment, const VkClearRect& ClearRect)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass != VK_NULL_HANDLE, "vkCmdClearAttachments() must be called inside render pass (17.2)");
vkCmdClearAttachments(
m_VkCmdBuffer,
1,
&Attachment,
1,
&ClearRect // The rectangular region specified by each element of pRects must be
// contained within the render area of the current render pass instance
);
}
__forceinline void Draw(uint32_t VertexCount, uint32_t InstanceCount, uint32_t FirstVertex, uint32_t FirstInstance)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass != VK_NULL_HANDLE, "vkCmdDraw() must be called inside render pass (19.3)");
VERIFY(m_State.GraphicsPipeline != VK_NULL_HANDLE, "No graphics pipeline bound");
vkCmdDraw(m_VkCmdBuffer, VertexCount, InstanceCount, FirstVertex, FirstInstance);
}
__forceinline void DrawIndexed(uint32_t IndexCount, uint32_t InstanceCount, uint32_t FirstIndex, int32_t VertexOffset, uint32_t FirstInstance)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass != VK_NULL_HANDLE, "vkCmdDrawIndexed() must be called inside render pass (19.3)");
VERIFY(m_State.GraphicsPipeline != VK_NULL_HANDLE, "No graphics pipeline bound");
VERIFY(m_State.IndexBuffer != VK_NULL_HANDLE, "No index buffer bound");
vkCmdDrawIndexed(m_VkCmdBuffer, IndexCount, InstanceCount, FirstIndex, VertexOffset, FirstInstance);
}
__forceinline void DrawIndirect(VkBuffer Buffer, VkDeviceSize Offset, uint32_t DrawCount, uint32_t Stride)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass != VK_NULL_HANDLE, "vkCmdDrawIndirect() must be called inside render pass (19.3)");
VERIFY(m_State.GraphicsPipeline != VK_NULL_HANDLE, "No graphics pipeline bound");
vkCmdDrawIndirect(m_VkCmdBuffer, Buffer, Offset, DrawCount, Stride);
}
__forceinline void DrawIndexedIndirect(VkBuffer Buffer, VkDeviceSize Offset, uint32_t DrawCount, uint32_t Stride)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass != VK_NULL_HANDLE, "vkCmdDrawIndirect() must be called inside render pass (19.3)");
VERIFY(m_State.GraphicsPipeline != VK_NULL_HANDLE, "No graphics pipeline bound");
VERIFY(m_State.IndexBuffer != VK_NULL_HANDLE, "No index buffer bound");
vkCmdDrawIndexedIndirect(m_VkCmdBuffer, Buffer, Offset, DrawCount, Stride);
}
__forceinline void Dispatch(uint32_t GroupCountX, uint32_t GroupCountY, uint32_t GroupCountZ)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass == VK_NULL_HANDLE, "vkCmdDispatch() must be called outside of render pass (27)");
VERIFY(m_State.ComputePipeline != VK_NULL_HANDLE, "No compute pipeline bound");
vkCmdDispatch(m_VkCmdBuffer, GroupCountX, GroupCountY, GroupCountZ);
}
__forceinline void DispatchIndirect(VkBuffer Buffer, VkDeviceSize Offset)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass == VK_NULL_HANDLE, "vkCmdDispatchIndirect() must be called outside of render pass (27)");
VERIFY(m_State.ComputePipeline != VK_NULL_HANDLE, "No compute pipeline bound");
vkCmdDispatchIndirect(m_VkCmdBuffer, Buffer, Offset);
}
__forceinline void BeginRenderPass(VkRenderPass RenderPass, VkFramebuffer Framebuffer, uint32_t FramebufferWidth, uint32_t FramebufferHeight)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
VERIFY(m_State.RenderPass == VK_NULL_HANDLE, "Current pass has not been ended");
if (m_State.RenderPass != RenderPass || m_State.Framebuffer != Framebuffer)
{
VkRenderPassBeginInfo BeginInfo;
BeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
BeginInfo.pNext = nullptr;
BeginInfo.renderPass = RenderPass;
BeginInfo.framebuffer = Framebuffer;
// The render area MUST be contained within the framebuffer dimensions (7.4)
BeginInfo.renderArea = {{0, 0}, {FramebufferWidth, FramebufferHeight}};
BeginInfo.clearValueCount = 0;
BeginInfo.pClearValues = nullptr; // an array of VkClearValue structures that contains clear values for
// each attachment, if the attachment uses a loadOp value of VK_ATTACHMENT_LOAD_OP_CLEAR
// or if the attachment has a depth/stencil format and uses a stencilLoadOp value of
// VK_ATTACHMENT_LOAD_OP_CLEAR. The array is indexed by attachment number. Only elements
// corresponding to cleared attachments are used. Other elements of pClearValues are
// ignored (7.4)
vkCmdBeginRenderPass(m_VkCmdBuffer, &BeginInfo,
VK_SUBPASS_CONTENTS_INLINE // the contents of the subpass will be recorded inline in the
// primary command buffer, and secondary command buffers must not
// be executed within the subpass
);
m_State.RenderPass = RenderPass;
m_State.Framebuffer = Framebuffer;
m_State.FramebufferWidth = FramebufferWidth;
m_State.FramebufferHeight = FramebufferHeight;
}
}
__forceinline void EndRenderPass()
{
VERIFY(m_State.RenderPass != VK_NULL_HANDLE, "Render pass has not been started");
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkCmdEndRenderPass(m_VkCmdBuffer);
m_State.RenderPass = VK_NULL_HANDLE;
m_State.Framebuffer = VK_NULL_HANDLE;
m_State.FramebufferWidth = 0;
m_State.FramebufferHeight = 0;
}
__forceinline void EndCommandBuffer()
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkEndCommandBuffer(m_VkCmdBuffer);
}
__forceinline void Reset()
{
m_VkCmdBuffer = VK_NULL_HANDLE;
m_State = StateCache{};
}
__forceinline void BindComputePipeline(VkPipeline ComputePipeline)
{
// 9.8
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.ComputePipeline != ComputePipeline)
{
vkCmdBindPipeline(m_VkCmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, ComputePipeline);
m_State.ComputePipeline = ComputePipeline;
}
}
__forceinline void BindGraphicsPipeline(VkPipeline GraphicsPipeline)
{
// 9.8
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.GraphicsPipeline != GraphicsPipeline)
{
vkCmdBindPipeline(m_VkCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, GraphicsPipeline);
m_State.GraphicsPipeline = GraphicsPipeline;
}
}
__forceinline void SetViewports(uint32_t FirstViewport, uint32_t ViewportCount, const VkViewport* pViewports)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkCmdSetViewport(m_VkCmdBuffer, FirstViewport, ViewportCount, pViewports);
}
__forceinline void SetScissorRects(uint32_t FirstScissor, uint32_t ScissorCount, const VkRect2D* pScissors)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkCmdSetScissor(m_VkCmdBuffer, FirstScissor, ScissorCount, pScissors);
}
__forceinline void SetStencilReference(uint32_t Reference)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkCmdSetStencilReference(m_VkCmdBuffer, VK_STENCIL_FRONT_AND_BACK, Reference);
}
__forceinline void SetBlendConstants(const float BlendConstants[4])
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkCmdSetBlendConstants(m_VkCmdBuffer, BlendConstants);
}
__forceinline void BindIndexBuffer(VkBuffer Buffer, VkDeviceSize Offset, VkIndexType IndexType)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
// clang-format off
if (m_State.IndexBuffer != Buffer ||
m_State.IndexBufferOffset != Offset ||
m_State.IndexType != IndexType)
{
// clang-format on
vkCmdBindIndexBuffer(m_VkCmdBuffer, Buffer, Offset, IndexType);
m_State.IndexBuffer = Buffer;
m_State.IndexBufferOffset = Offset;
m_State.IndexType = IndexType;
}
}
__forceinline void BindVertexBuffers(uint32_t firstBinding, uint32_t bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkCmdBindVertexBuffers(m_VkCmdBuffer, firstBinding, bindingCount, pBuffers, pOffsets);
}
static void TransitionImageLayout(VkCommandBuffer CmdBuffer,
VkImage Image,
VkImageLayout OldLayout,
VkImageLayout NewLayout,
const VkImageSubresourceRange& SubresRange,
VkPipelineStageFlags EnabledGraphicsShaderStages,
VkPipelineStageFlags SrcStages = 0,
VkPipelineStageFlags DestStages = 0);
__forceinline void TransitionImageLayout(VkImage Image,
VkImageLayout OldLayout,
VkImageLayout NewLayout,
const VkImageSubresourceRange& SubresRange,
VkPipelineStageFlags SrcStages = 0,
VkPipelineStageFlags DestStages = 0)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Image layout transitions within a render pass execute
// dependencies between attachments
EndRenderPass();
}
TransitionImageLayout(m_VkCmdBuffer, Image, OldLayout, NewLayout, SubresRange, m_EnabledGraphicsShaderStages, SrcStages, DestStages);
}
static void BufferMemoryBarrier(VkCommandBuffer CmdBuffer,
VkBuffer Buffer,
VkAccessFlags srcAccessMask,
VkAccessFlags dstAccessMask,
VkPipelineStageFlags EnabledGraphicsShaderStages,
VkPipelineStageFlags SrcStages = 0,
VkPipelineStageFlags DestStages = 0);
__forceinline void BufferMemoryBarrier(VkBuffer Buffer,
VkAccessFlags srcAccessMask,
VkAccessFlags dstAccessMask,
VkPipelineStageFlags SrcStages = 0,
VkPipelineStageFlags DestStages = 0)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Image layout transitions within a render pass execute
// dependencies between attachments
EndRenderPass();
}
BufferMemoryBarrier(m_VkCmdBuffer, Buffer, srcAccessMask, dstAccessMask, m_EnabledGraphicsShaderStages, SrcStages, DestStages);
}
__forceinline void BindDescriptorSets(VkPipelineBindPoint pipelineBindPoint,
VkPipelineLayout layout,
uint32_t firstSet,
uint32_t descriptorSetCount,
const VkDescriptorSet* pDescriptorSets,
uint32_t dynamicOffsetCount = 0,
const uint32_t* pDynamicOffsets = nullptr)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
vkCmdBindDescriptorSets(m_VkCmdBuffer, pipelineBindPoint, layout, firstSet, descriptorSetCount, pDescriptorSets, dynamicOffsetCount, pDynamicOffsets);
}
__forceinline void CopyBuffer(VkBuffer srcBuffer,
VkBuffer dstBuffer,
uint32_t regionCount,
const VkBufferCopy* pRegions)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Copy buffer operation must be performed outside of render pass.
EndRenderPass();
}
vkCmdCopyBuffer(m_VkCmdBuffer, srcBuffer, dstBuffer, regionCount, pRegions);
}
__forceinline void CopyImage(VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageCopy* pRegions)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Copy operations must be performed outside of render pass.
EndRenderPass();
}
vkCmdCopyImage(m_VkCmdBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions);
}
__forceinline void CopyBufferToImage(VkBuffer srcBuffer,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkBufferImageCopy* pRegions)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Copy operations must be performed outside of render pass.
EndRenderPass();
}
vkCmdCopyBufferToImage(m_VkCmdBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
}
__forceinline void CopyImageToBuffer(VkImage srcImage,
VkImageLayout srcImageLayout,
VkBuffer dstBuffer,
uint32_t regionCount,
const VkBufferImageCopy* pRegions)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Copy operations must be performed outside of render pass.
EndRenderPass();
}
vkCmdCopyImageToBuffer(m_VkCmdBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
}
__forceinline void BlitImage(VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageBlit* pRegions,
VkFilter filter)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Blit must be performed outside of render pass.
EndRenderPass();
}
vkCmdBlitImage(m_VkCmdBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter);
}
__forceinline void ResolveImage(VkImage srcImage,
VkImageLayout srcImageLayout,
VkImage dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const VkImageResolve* pRegions)
{
VERIFY_EXPR(m_VkCmdBuffer != VK_NULL_HANDLE);
if (m_State.RenderPass != VK_NULL_HANDLE)
{
// Resolve must be performed outside of render pass.
EndRenderPass();
}
vkCmdResolveImage(m_VkCmdBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions);
}
void FlushBarriers();
__forceinline void SetVkCmdBuffer(VkCommandBuffer VkCmdBuffer)
{
m_VkCmdBuffer = VkCmdBuffer;
}
VkCommandBuffer GetVkCmdBuffer() const { return m_VkCmdBuffer; }
struct StateCache
{
VkRenderPass RenderPass = VK_NULL_HANDLE;
VkFramebuffer Framebuffer = VK_NULL_HANDLE;
VkPipeline GraphicsPipeline = VK_NULL_HANDLE;
VkPipeline ComputePipeline = VK_NULL_HANDLE;
VkBuffer IndexBuffer = VK_NULL_HANDLE;
VkDeviceSize IndexBufferOffset = 0;
VkIndexType IndexType = VK_INDEX_TYPE_MAX_ENUM;
uint32_t FramebufferWidth = 0;
uint32_t FramebufferHeight = 0;
};
const StateCache& GetState() const { return m_State; }
private:
StateCache m_State;
VkCommandBuffer m_VkCmdBuffer = VK_NULL_HANDLE;
const VkPipelineStageFlags m_EnabledGraphicsShaderStages;
};
} // namespace VulkanUtilities
| 47.248936 | 169 | 0.603008 | [
"render"
] |
9a5b757fbd2f623ae0b932d58e83d02eddd86992 | 15,142 | c | C | fs/orangefs/xattr.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | fs/orangefs/xattr.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 1 | 2021-01-27T01:29:47.000Z | 2021-01-27T01:29:47.000Z | fs/orangefs/xattr.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | // SPDX-License-Identifier: GPL-2.0
/*
* (C) 2001 Clemson University and The University of Chicago
* Copyright 2018 Omnibond Systems, L.L.C.
*
* See COPYING in top-level directory.
*/
/*
* Linux VFS extended attribute operations.
*/
#include "protocol.h"
#include "orangefs-kernel.h"
#include "orangefs-bufmap.h"
#include <linux/posix_acl_xattr.h>
#include <linux/xattr.h>
#include <linux/hashtable.h>
#define SYSTEM_ORANGEFS_KEY "system.pvfs2."
#define SYSTEM_ORANGEFS_KEY_LEN 13
/*
* this function returns
* 0 if the key corresponding to name is not meant to be printed as part
* of a listxattr.
* 1 if the key corresponding to name is meant to be returned as part of
* a listxattr.
* The ones that start SYSTEM_ORANGEFS_KEY are the ones to avoid printing.
*/
static int is_reserved_key(const char *key, size_t size)
{
if (size < SYSTEM_ORANGEFS_KEY_LEN)
return 1;
return strncmp(key, SYSTEM_ORANGEFS_KEY, SYSTEM_ORANGEFS_KEY_LEN) ? 1 : 0;
}
static inline int convert_to_internal_xattr_flags(int setxattr_flags)
{
int internal_flag = 0;
if (setxattr_flags & XATTR_REPLACE) {
/* Attribute must exist! */
internal_flag = ORANGEFS_XATTR_REPLACE;
} else if (setxattr_flags & XATTR_CREATE) {
/* Attribute must not exist */
internal_flag = ORANGEFS_XATTR_CREATE;
}
return internal_flag;
}
static unsigned int xattr_key(const char *key)
{
unsigned int i = 0;
while (key)
i += *key++;
return i % 16;
}
static struct orangefs_cached_xattr *find_cached_xattr(struct inode *inode,
const char *key)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
struct orangefs_cached_xattr *cx;
struct hlist_head *h;
struct hlist_node *tmp;
h = &orangefs_inode->xattr_cache[xattr_key(key)];
if (hlist_empty(h))
return NULL;
hlist_for_each_entry_safe(cx, tmp, h, node) {
/* if (!time_before(jiffies, cx->timeout)) {
hlist_del(&cx->node);
kfree(cx);
continue;
}*/
if (!strcmp(cx->key, key))
return cx;
}
return NULL;
}
/*
* Tries to get a specified key's attributes of a given
* file into a user-specified buffer. Note that the getxattr
* interface allows for the users to probe the size of an
* extended attribute by passing in a value of 0 to size.
* Thus our return value is always the size of the attribute
* unless the key does not exist for the file and/or if
* there were errors in fetching the attribute value.
*/
ssize_t orangefs_inode_getxattr(struct inode *inode, const char *name,
void *buffer, size_t size)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
struct orangefs_kernel_op_s *new_op = NULL;
struct orangefs_cached_xattr *cx;
ssize_t ret = -ENOMEM;
ssize_t length = 0;
int fsuid;
int fsgid;
gossip_debug(GOSSIP_XATTR_DEBUG,
"%s: name %s, buffer_size %zd\n",
__func__, name, size);
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (strlen(name) >= ORANGEFS_MAX_XATTR_NAMELEN)
return -EINVAL;
fsuid = from_kuid(&init_user_ns, current_fsuid());
fsgid = from_kgid(&init_user_ns, current_fsgid());
gossip_debug(GOSSIP_XATTR_DEBUG,
"getxattr on inode %pU, name %s "
"(uid %o, gid %o)\n",
get_khandle_from_ino(inode),
name,
fsuid,
fsgid);
down_read(&orangefs_inode->xattr_sem);
cx = find_cached_xattr(inode, name);
if (cx && time_before(jiffies, cx->timeout)) {
if (cx->length == -1) {
ret = -ENODATA;
goto out_unlock;
} else {
if (size == 0) {
ret = cx->length;
goto out_unlock;
}
if (cx->length > size) {
ret = -ERANGE;
goto out_unlock;
}
memcpy(buffer, cx->val, cx->length);
memset(buffer + cx->length, 0, size - cx->length);
ret = cx->length;
goto out_unlock;
}
}
new_op = op_alloc(ORANGEFS_VFS_OP_GETXATTR);
if (!new_op)
goto out_unlock;
new_op->upcall.req.getxattr.refn = orangefs_inode->refn;
strcpy(new_op->upcall.req.getxattr.key, name);
/*
* NOTE: Although keys are meant to be NULL terminated textual
* strings, I am going to explicitly pass the length just in case
* we change this later on...
*/
new_op->upcall.req.getxattr.key_sz = strlen(name) + 1;
ret = service_operation(new_op, "orangefs_inode_getxattr",
get_interruptible_flag(inode));
if (ret != 0) {
if (ret == -ENOENT) {
ret = -ENODATA;
gossip_debug(GOSSIP_XATTR_DEBUG,
"orangefs_inode_getxattr: inode %pU key %s"
" does not exist!\n",
get_khandle_from_ino(inode),
(char *)new_op->upcall.req.getxattr.key);
cx = kmalloc(sizeof *cx, GFP_KERNEL);
if (cx) {
strcpy(cx->key, name);
cx->length = -1;
cx->timeout = jiffies +
orangefs_getattr_timeout_msecs*HZ/1000;
hash_add(orangefs_inode->xattr_cache, &cx->node,
xattr_key(cx->key));
}
}
goto out_release_op;
}
/*
* Length returned includes null terminator.
*/
length = new_op->downcall.resp.getxattr.val_sz;
/*
* Just return the length of the queried attribute.
*/
if (size == 0) {
ret = length;
goto out_release_op;
}
/*
* Check to see if key length is > provided buffer size.
*/
if (length > size) {
ret = -ERANGE;
goto out_release_op;
}
memcpy(buffer, new_op->downcall.resp.getxattr.val, length);
memset(buffer + length, 0, size - length);
gossip_debug(GOSSIP_XATTR_DEBUG,
"orangefs_inode_getxattr: inode %pU "
"key %s key_sz %d, val_len %d\n",
get_khandle_from_ino(inode),
(char *)new_op->
upcall.req.getxattr.key,
(int)new_op->
upcall.req.getxattr.key_sz,
(int)ret);
ret = length;
if (cx) {
strcpy(cx->key, name);
memcpy(cx->val, buffer, length);
cx->length = length;
cx->timeout = jiffies + HZ;
} else {
cx = kmalloc(sizeof *cx, GFP_KERNEL);
if (cx) {
strcpy(cx->key, name);
memcpy(cx->val, buffer, length);
cx->length = length;
cx->timeout = jiffies + HZ;
hash_add(orangefs_inode->xattr_cache, &cx->node,
xattr_key(cx->key));
}
}
out_release_op:
op_release(new_op);
out_unlock:
up_read(&orangefs_inode->xattr_sem);
return ret;
}
static int orangefs_inode_removexattr(struct inode *inode, const char *name,
int flags)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
struct orangefs_kernel_op_s *new_op = NULL;
struct orangefs_cached_xattr *cx;
struct hlist_head *h;
struct hlist_node *tmp;
int ret = -ENOMEM;
if (strlen(name) >= ORANGEFS_MAX_XATTR_NAMELEN)
return -EINVAL;
down_write(&orangefs_inode->xattr_sem);
new_op = op_alloc(ORANGEFS_VFS_OP_REMOVEXATTR);
if (!new_op)
goto out_unlock;
new_op->upcall.req.removexattr.refn = orangefs_inode->refn;
/*
* NOTE: Although keys are meant to be NULL terminated
* textual strings, I am going to explicitly pass the
* length just in case we change this later on...
*/
strcpy(new_op->upcall.req.removexattr.key, name);
new_op->upcall.req.removexattr.key_sz = strlen(name) + 1;
gossip_debug(GOSSIP_XATTR_DEBUG,
"orangefs_inode_removexattr: key %s, key_sz %d\n",
(char *)new_op->upcall.req.removexattr.key,
(int)new_op->upcall.req.removexattr.key_sz);
ret = service_operation(new_op,
"orangefs_inode_removexattr",
get_interruptible_flag(inode));
if (ret == -ENOENT) {
/*
* Request to replace a non-existent attribute is an error.
*/
if (flags & XATTR_REPLACE)
ret = -ENODATA;
else
ret = 0;
}
gossip_debug(GOSSIP_XATTR_DEBUG,
"orangefs_inode_removexattr: returning %d\n", ret);
op_release(new_op);
h = &orangefs_inode->xattr_cache[xattr_key(name)];
hlist_for_each_entry_safe(cx, tmp, h, node) {
if (!strcmp(cx->key, name)) {
hlist_del(&cx->node);
kfree(cx);
break;
}
}
out_unlock:
up_write(&orangefs_inode->xattr_sem);
return ret;
}
/*
* Tries to set an attribute for a given key on a file.
*
* Returns a -ve number on error and 0 on success. Key is text, but value
* can be binary!
*/
int orangefs_inode_setxattr(struct inode *inode, const char *name,
const void *value, size_t size, int flags)
{
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
struct orangefs_kernel_op_s *new_op;
int internal_flag = 0;
struct orangefs_cached_xattr *cx;
struct hlist_head *h;
struct hlist_node *tmp;
int ret = -ENOMEM;
gossip_debug(GOSSIP_XATTR_DEBUG,
"%s: name %s, buffer_size %zd\n",
__func__, name, size);
if (size > ORANGEFS_MAX_XATTR_VALUELEN)
return -EINVAL;
if (strlen(name) >= ORANGEFS_MAX_XATTR_NAMELEN)
return -EINVAL;
internal_flag = convert_to_internal_xattr_flags(flags);
/* This is equivalent to a removexattr */
if (size == 0 && !value) {
gossip_debug(GOSSIP_XATTR_DEBUG,
"removing xattr (%s)\n",
name);
return orangefs_inode_removexattr(inode, name, flags);
}
gossip_debug(GOSSIP_XATTR_DEBUG,
"setxattr on inode %pU, name %s\n",
get_khandle_from_ino(inode),
name);
down_write(&orangefs_inode->xattr_sem);
new_op = op_alloc(ORANGEFS_VFS_OP_SETXATTR);
if (!new_op)
goto out_unlock;
new_op->upcall.req.setxattr.refn = orangefs_inode->refn;
new_op->upcall.req.setxattr.flags = internal_flag;
/*
* NOTE: Although keys are meant to be NULL terminated textual
* strings, I am going to explicitly pass the length just in
* case we change this later on...
*/
strcpy(new_op->upcall.req.setxattr.keyval.key, name);
new_op->upcall.req.setxattr.keyval.key_sz = strlen(name) + 1;
memcpy(new_op->upcall.req.setxattr.keyval.val, value, size);
new_op->upcall.req.setxattr.keyval.val_sz = size;
gossip_debug(GOSSIP_XATTR_DEBUG,
"orangefs_inode_setxattr: key %s, key_sz %d "
" value size %zd\n",
(char *)new_op->upcall.req.setxattr.keyval.key,
(int)new_op->upcall.req.setxattr.keyval.key_sz,
size);
ret = service_operation(new_op,
"orangefs_inode_setxattr",
get_interruptible_flag(inode));
gossip_debug(GOSSIP_XATTR_DEBUG,
"orangefs_inode_setxattr: returning %d\n",
ret);
/* when request is serviced properly, free req op struct */
op_release(new_op);
h = &orangefs_inode->xattr_cache[xattr_key(name)];
hlist_for_each_entry_safe(cx, tmp, h, node) {
if (!strcmp(cx->key, name)) {
hlist_del(&cx->node);
kfree(cx);
break;
}
}
out_unlock:
up_write(&orangefs_inode->xattr_sem);
return ret;
}
/*
* Tries to get a specified object's keys into a user-specified buffer of a
* given size. Note that like the previous instances of xattr routines, this
* also allows you to pass in a NULL pointer and 0 size to probe the size for
* subsequent memory allocations. Thus our return value is always the size of
* all the keys unless there were errors in fetching the keys!
*/
ssize_t orangefs_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
struct inode *inode = dentry->d_inode;
struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode);
struct orangefs_kernel_op_s *new_op;
__u64 token = ORANGEFS_ITERATE_START;
ssize_t ret = -ENOMEM;
ssize_t total = 0;
int count_keys = 0;
int key_size;
int i = 0;
int returned_count = 0;
if (size > 0 && !buffer) {
gossip_err("%s: bogus NULL pointers\n", __func__);
return -EINVAL;
}
down_read(&orangefs_inode->xattr_sem);
new_op = op_alloc(ORANGEFS_VFS_OP_LISTXATTR);
if (!new_op)
goto out_unlock;
if (buffer && size > 0)
memset(buffer, 0, size);
try_again:
key_size = 0;
new_op->upcall.req.listxattr.refn = orangefs_inode->refn;
new_op->upcall.req.listxattr.token = token;
new_op->upcall.req.listxattr.requested_count =
(size == 0) ? 0 : ORANGEFS_MAX_XATTR_LISTLEN;
ret = service_operation(new_op, __func__,
get_interruptible_flag(inode));
if (ret != 0)
goto done;
if (size == 0) {
/*
* This is a bit of a big upper limit, but I did not want to
* spend too much time getting this correct, since users end
* up allocating memory rather than us...
*/
total = new_op->downcall.resp.listxattr.returned_count *
ORANGEFS_MAX_XATTR_NAMELEN;
goto done;
}
returned_count = new_op->downcall.resp.listxattr.returned_count;
if (returned_count < 0 ||
returned_count > ORANGEFS_MAX_XATTR_LISTLEN) {
gossip_err("%s: impossible value for returned_count:%d:\n",
__func__,
returned_count);
ret = -EIO;
goto done;
}
/*
* Check to see how much can be fit in the buffer. Fit only whole keys.
*/
for (i = 0; i < returned_count; i++) {
if (new_op->downcall.resp.listxattr.lengths[i] < 0 ||
new_op->downcall.resp.listxattr.lengths[i] >
ORANGEFS_MAX_XATTR_NAMELEN) {
gossip_err("%s: impossible value for lengths[%d]\n",
__func__,
new_op->downcall.resp.listxattr.lengths[i]);
ret = -EIO;
goto done;
}
if (total + new_op->downcall.resp.listxattr.lengths[i] > size)
goto done;
/*
* Since many dumb programs try to setxattr() on our reserved
* xattrs this is a feeble attempt at defeating those by not
* listing them in the output of listxattr.. sigh
*/
if (is_reserved_key(new_op->downcall.resp.listxattr.key +
key_size,
new_op->downcall.resp.
listxattr.lengths[i])) {
gossip_debug(GOSSIP_XATTR_DEBUG, "Copying key %d -> %s\n",
i, new_op->downcall.resp.listxattr.key +
key_size);
memcpy(buffer + total,
new_op->downcall.resp.listxattr.key + key_size,
new_op->downcall.resp.listxattr.lengths[i]);
total += new_op->downcall.resp.listxattr.lengths[i];
count_keys++;
} else {
gossip_debug(GOSSIP_XATTR_DEBUG, "[RESERVED] key %d -> %s\n",
i, new_op->downcall.resp.listxattr.key +
key_size);
}
key_size += new_op->downcall.resp.listxattr.lengths[i];
}
/*
* Since the buffer was large enough, we might have to continue
* fetching more keys!
*/
token = new_op->downcall.resp.listxattr.token;
if (token != ORANGEFS_ITERATE_END)
goto try_again;
done:
gossip_debug(GOSSIP_XATTR_DEBUG, "%s: returning %d"
" [size of buffer %ld] (filled in %d keys)\n",
__func__,
ret ? (int)ret : (int)total,
(long)size,
count_keys);
op_release(new_op);
if (ret == 0)
ret = total;
out_unlock:
up_read(&orangefs_inode->xattr_sem);
return ret;
}
static int orangefs_xattr_set_default(const struct xattr_handler *handler,
struct user_namespace *mnt_userns,
struct dentry *unused,
struct inode *inode,
const char *name,
const void *buffer,
size_t size,
int flags)
{
return orangefs_inode_setxattr(inode, name, buffer, size, flags);
}
static int orangefs_xattr_get_default(const struct xattr_handler *handler,
struct dentry *unused,
struct inode *inode,
const char *name,
void *buffer,
size_t size)
{
return orangefs_inode_getxattr(inode, name, buffer, size);
}
static const struct xattr_handler orangefs_xattr_default_handler = {
.prefix = "", /* match any name => handlers called with full name */
.get = orangefs_xattr_get_default,
.set = orangefs_xattr_set_default,
};
const struct xattr_handler *orangefs_xattr_handlers[] = {
&posix_acl_access_xattr_handler,
&posix_acl_default_xattr_handler,
&orangefs_xattr_default_handler,
NULL
};
| 26.895204 | 77 | 0.689341 | [
"object"
] |
9a60e4d3db57c601b034e133fa7d6ae7606d58d4 | 6,674 | c | C | contrib/libs/clapack/claesy.c | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | contrib/libs/clapack/claesy.c | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | ExternalCode/lapack/SRC/claesy.c | daniel-anavaino/tinkercell | 7896a7f809a0373ab3c848d25e3691d10a648437 | [
"BSD-3-Clause"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | /* claesy.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static complex c_b1 = {1.f,0.f};
static integer c__2 = 2;
/* Subroutine */ int claesy_(complex *a, complex *b, complex *c__, complex *
rt1, complex *rt2, complex *evscal, complex *cs1, complex *sn1)
{
/* System generated locals */
real r__1, r__2;
complex q__1, q__2, q__3, q__4, q__5, q__6, q__7;
/* Builtin functions */
double c_abs(complex *);
void pow_ci(complex *, complex *, integer *), c_sqrt(complex *, complex *)
, c_div(complex *, complex *, complex *);
/* Local variables */
complex s, t;
real z__;
complex tmp;
real babs, tabs, evnorm;
/* -- LAPACK auxiliary routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* CLAESY computes the eigendecomposition of a 2-by-2 symmetric matrix */
/* ( ( A, B );( B, C ) ) */
/* provided the norm of the matrix of eigenvectors is larger than */
/* some threshold value. */
/* RT1 is the eigenvalue of larger absolute value, and RT2 of */
/* smaller absolute value. If the eigenvectors are computed, then */
/* on return ( CS1, SN1 ) is the unit eigenvector for RT1, hence */
/* [ CS1 SN1 ] . [ A B ] . [ CS1 -SN1 ] = [ RT1 0 ] */
/* [ -SN1 CS1 ] [ B C ] [ SN1 CS1 ] [ 0 RT2 ] */
/* Arguments */
/* ========= */
/* A (input) COMPLEX */
/* The ( 1, 1 ) element of input matrix. */
/* B (input) COMPLEX */
/* The ( 1, 2 ) element of input matrix. The ( 2, 1 ) element */
/* is also given by B, since the 2-by-2 matrix is symmetric. */
/* C (input) COMPLEX */
/* The ( 2, 2 ) element of input matrix. */
/* RT1 (output) COMPLEX */
/* The eigenvalue of larger modulus. */
/* RT2 (output) COMPLEX */
/* The eigenvalue of smaller modulus. */
/* EVSCAL (output) COMPLEX */
/* The complex value by which the eigenvector matrix was scaled */
/* to make it orthonormal. If EVSCAL is zero, the eigenvectors */
/* were not computed. This means one of two things: the 2-by-2 */
/* matrix could not be diagonalized, or the norm of the matrix */
/* of eigenvectors before scaling was larger than the threshold */
/* value THRESH (set below). */
/* CS1 (output) COMPLEX */
/* SN1 (output) COMPLEX */
/* If EVSCAL .NE. 0, ( CS1, SN1 ) is the unit right eigenvector */
/* for RT1. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Special case: The matrix is actually diagonal. */
/* To avoid divide by zero later, we treat this case separately. */
if (c_abs(b) == 0.f) {
rt1->r = a->r, rt1->i = a->i;
rt2->r = c__->r, rt2->i = c__->i;
if (c_abs(rt1) < c_abs(rt2)) {
tmp.r = rt1->r, tmp.i = rt1->i;
rt1->r = rt2->r, rt1->i = rt2->i;
rt2->r = tmp.r, rt2->i = tmp.i;
cs1->r = 0.f, cs1->i = 0.f;
sn1->r = 1.f, sn1->i = 0.f;
} else {
cs1->r = 1.f, cs1->i = 0.f;
sn1->r = 0.f, sn1->i = 0.f;
}
} else {
/* Compute the eigenvalues and eigenvectors. */
/* The characteristic equation is */
/* lambda **2 - (A+C) lambda + (A*C - B*B) */
/* and we solve it using the quadratic formula. */
q__2.r = a->r + c__->r, q__2.i = a->i + c__->i;
q__1.r = q__2.r * .5f, q__1.i = q__2.i * .5f;
s.r = q__1.r, s.i = q__1.i;
q__2.r = a->r - c__->r, q__2.i = a->i - c__->i;
q__1.r = q__2.r * .5f, q__1.i = q__2.i * .5f;
t.r = q__1.r, t.i = q__1.i;
/* Take the square root carefully to avoid over/under flow. */
babs = c_abs(b);
tabs = c_abs(&t);
z__ = dmax(babs,tabs);
if (z__ > 0.f) {
q__5.r = t.r / z__, q__5.i = t.i / z__;
pow_ci(&q__4, &q__5, &c__2);
q__7.r = b->r / z__, q__7.i = b->i / z__;
pow_ci(&q__6, &q__7, &c__2);
q__3.r = q__4.r + q__6.r, q__3.i = q__4.i + q__6.i;
c_sqrt(&q__2, &q__3);
q__1.r = z__ * q__2.r, q__1.i = z__ * q__2.i;
t.r = q__1.r, t.i = q__1.i;
}
/* Compute the two eigenvalues. RT1 and RT2 are exchanged */
/* if necessary so that RT1 will have the greater magnitude. */
q__1.r = s.r + t.r, q__1.i = s.i + t.i;
rt1->r = q__1.r, rt1->i = q__1.i;
q__1.r = s.r - t.r, q__1.i = s.i - t.i;
rt2->r = q__1.r, rt2->i = q__1.i;
if (c_abs(rt1) < c_abs(rt2)) {
tmp.r = rt1->r, tmp.i = rt1->i;
rt1->r = rt2->r, rt1->i = rt2->i;
rt2->r = tmp.r, rt2->i = tmp.i;
}
/* Choose CS1 = 1 and SN1 to satisfy the first equation, then */
/* scale the components of this eigenvector so that the matrix */
/* of eigenvectors X satisfies X * X' = I . (No scaling is */
/* done if the norm of the eigenvalue matrix is less than THRESH.) */
q__2.r = rt1->r - a->r, q__2.i = rt1->i - a->i;
c_div(&q__1, &q__2, b);
sn1->r = q__1.r, sn1->i = q__1.i;
tabs = c_abs(sn1);
if (tabs > 1.f) {
/* Computing 2nd power */
r__2 = 1.f / tabs;
r__1 = r__2 * r__2;
q__5.r = sn1->r / tabs, q__5.i = sn1->i / tabs;
pow_ci(&q__4, &q__5, &c__2);
q__3.r = r__1 + q__4.r, q__3.i = q__4.i;
c_sqrt(&q__2, &q__3);
q__1.r = tabs * q__2.r, q__1.i = tabs * q__2.i;
t.r = q__1.r, t.i = q__1.i;
} else {
q__3.r = sn1->r * sn1->r - sn1->i * sn1->i, q__3.i = sn1->r *
sn1->i + sn1->i * sn1->r;
q__2.r = q__3.r + 1.f, q__2.i = q__3.i + 0.f;
c_sqrt(&q__1, &q__2);
t.r = q__1.r, t.i = q__1.i;
}
evnorm = c_abs(&t);
if (evnorm >= .1f) {
c_div(&q__1, &c_b1, &t);
evscal->r = q__1.r, evscal->i = q__1.i;
cs1->r = evscal->r, cs1->i = evscal->i;
q__1.r = sn1->r * evscal->r - sn1->i * evscal->i, q__1.i = sn1->r
* evscal->i + sn1->i * evscal->r;
sn1->r = q__1.r, sn1->i = q__1.i;
} else {
evscal->r = 0.f, evscal->i = 0.f;
}
}
return 0;
/* End of CLAESY */
} /* claesy_ */
| 32.241546 | 78 | 0.531016 | [
"object"
] |
9a63d81a85ea28960cbd8ef1a2ab3efb310e4225 | 1,018 | h | C | src/github/client.h | pine/BestDocumenter | ce0497c62a6147b37fbd82e8fb0222f35fd45730 | [
"BSD-2-Clause"
] | null | null | null | src/github/client.h | pine/BestDocumenter | ce0497c62a6147b37fbd82e8fb0222f35fd45730 | [
"BSD-2-Clause"
] | null | null | null | src/github/client.h | pine/BestDocumenter | ce0497c62a6147b37fbd82e8fb0222f35fd45730 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <memory>
#include <vector>
#include <picojson.h>
#include "../http/client.h"
#include "../http/rfc5988.h"
#include "response/github_commit.h"
#include "response/util.h"
namespace github {
class Client {
public:
static const char* ENDPOINT;
Client(std::shared_ptr<http::Client> http);
~Client();
void setAccessToken(const std::string& accessToken);
response::GitHubCommitArrayPtr fetchReposCommits(
const std::string& owner,
const std::string& repo,
std::string* err,
const http::GetParams* opts = nullptr
);
response::GitHubCommitPtr fetchReposCommit(
const std::string& owner,
const std::string& repo,
const std::string& sha,
std::string* err
);
private:
std::shared_ptr<http::Client> http_;
std::string getNextUrl(http::HeaderMap& header);
};
}
| 24.238095 | 60 | 0.565815 | [
"vector"
] |
9a6a523d7d99ce7a21f499e6767d54250cca2763 | 3,399 | h | C | cob_sick_s300/common/include/cob_sick_s300/ScannerSickS300.h | ipa-fxm/cob_driver | 9b2928486058bc650a4b25305a8d842498504c3c | [
"Apache-2.0"
] | 1 | 2020-01-27T14:08:14.000Z | 2020-01-27T14:08:14.000Z | cob_sick_s300/common/include/cob_sick_s300/ScannerSickS300.h | inomuh/agvpc_ros | e7ad0b3dd7f63f5aea5ecc3137815f12c3c8f201 | [
"Apache-2.0"
] | null | null | null | cob_sick_s300/common/include/cob_sick_s300/ScannerSickS300.h | inomuh/agvpc_ros | e7ad0b3dd7f63f5aea5ecc3137815f12c3c8f201 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
*
* 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 SCANNERSICKS300_INCLUDEDEF_H
#define SCANNERSICKS300_INCLUDEDEF_H
//-----------------------------------------------
// base classes
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <cob_sick_s300/SerialIO.h>
#include <cob_sick_s300/TelegramS300.h>
/**
* Driver class for the laser scanner SICK S300 Professional.
* This driver only supports use with 500KBaud in cont. mode
*
* if the scanner is in standby, the measurements are 0x4004 according to the Sick Support
*/
class ScannerSickS300
{
public:
// set of parameters which are specific to the SickS300
struct ParamType
{
int range_field; //measurement range (1 to 5) --> usually 1 (default)
double dScale; // scaling of the scan (multiply with to get scan in meters)
double dStartAngle; // scan start angle
double dStopAngle; // scan stop angle
};
// storage container for received scanner data
struct ScanPolarType
{
double dr; // distance //r;
double da; // angle //a;
double di; // intensity; //bool bGlare;
};
enum
{
SCANNER_S300_READ_BUF_SIZE = 10000,
READ_BUF_SIZE = 10000,
WRITE_BUF_SIZE = 10000
};
// Constructor
ScannerSickS300();
// Destructor
~ScannerSickS300();
/**
* Opens serial port.
* @param pcPort used "COMx" or "/dev/tty1"
* @param iBaudRate baud rate
* @param iScanId the scanner id in the data header (7 by default)
*/
bool open(const char* pcPort, int iBaudRate, int iScanId);
// not implemented
void resetStartup();
// not implmented
void startScanner();
// not implemented
void stopScanner();
//sick_lms.Uninitialize();
// whether the scanner is currently in Standby or not
bool isInStandby() {return m_bInStandby;}
void purgeScanBuf();
bool getScan(std::vector<double> &vdDistanceM, std::vector<double> &vdAngleRAD, std::vector<double> &vdIntensityAU, unsigned int &iTimestamp, unsigned int &iTimeNow, const bool debug);
void setRangeField(const int field, const ParamType ¶m) {m_Params[field] = param;}
private:
// Constants
static const double c_dPi;
// Parameters
typedef std::map<int, ParamType> PARAM_MAP;
PARAM_MAP m_Params;
double m_dBaudMult;
// Variables
unsigned char m_ReadBuf[READ_BUF_SIZE+10];
unsigned char m_ReadBuf2[READ_BUF_SIZE+10];
unsigned int m_uiSumReadBytes;
std::vector<int> m_viScanRaw;
int m_iPosReadBuf2;
static unsigned char m_iScanId;
int m_actualBufferSize;
bool m_bInStandby;
// Components
SerialIO m_SerialIO;
TelegramParser tp_;
// Functions
void convertScanToPolar(const PARAM_MAP::const_iterator param, std::vector<int> viScanRaw,
std::vector<ScanPolarType>& vecScanPolar);
};
//-----------------------------------------------
#endif
| 25.556391 | 185 | 0.715505 | [
"vector"
] |
9a6d9b05fbb330c1d8dd61c990a3d7de8c16ab80 | 35,035 | h | C | include/psmove_tracker.h | psmoveservice/psmoveapi | 683757ca2f5f9af84de9d8b83347873f5beaf562 | [
"BSD-2-Clause"
] | 2 | 2020-02-25T19:09:17.000Z | 2020-05-01T22:30:09.000Z | include/psmove_tracker.h | psmoveservice/psmoveapi | 683757ca2f5f9af84de9d8b83347873f5beaf562 | [
"BSD-2-Clause"
] | null | null | null | include/psmove_tracker.h | psmoveservice/psmoveapi | 683757ca2f5f9af84de9d8b83347873f5beaf562 | [
"BSD-2-Clause"
] | null | null | null | /**
* PS Move API - An interface for the PS Move Motion Controller
* Copyright (c) 2012 Benjamin Venditti <benjamin.venditti@gmail.com>
* Copyright (c) 2012 Thomas Perl <m@thp.io>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
**/
#ifndef PSMOVE_TRACKER_H
#define PSMOVE_TRACKER_H
#include "psmove.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Defines the range of x/y values for the position getting, etc.. */
#define PSMOVE_TRACKER_DEFAULT_WIDTH 640
#define PSMOVE_TRACKER_DEFAULT_HEIGHT 480
#define PSMOVE_TRACKER_DEFAULT_FPS 60
/* Maximum number of controllers that can be tracked at once */
#define PSMOVE_TRACKER_MAX_CONTROLLERS 5
/* Name of the environment variable used to pick a camera */
#define PSMOVE_TRACKER_CAMERA_ENV "PSMOVE_TRACKER_CAMERA"
/* Name of the environment variable used to choose a pre-recorded video */
#define PSMOVE_TRACKER_FILENAME_ENV "PSMOVE_TRACKER_FILENAME"
/* Name of the environment variable used to set the biggest ROI size */
#define PSMOVE_TRACKER_ROI_SIZE_ENV "PSMOVE_TRACKER_ROI_SIZE"
/* Name of the environment variable used to set a fixed tracker color */
#define PSMOVE_TRACKER_COLOR_ENV "PSMOVE_TRACKER_COLOR"
/* Name of the environment variables for the camera image size */
#define PSMOVE_TRACKER_WIDTH_ENV "PSMOVE_TRACKER_WIDTH"
#define PSMOVE_TRACKER_HEIGHT_ENV "PSMOVE_TRACKER_HEIGHT"
typedef struct {
void *data;
int width;
int height;
} PSMoveTrackerRGBImage; /*!< Structure for storing RGB image data */
/* Opaque data structure, defined only in psmove_tracker.c */
#ifndef SWIG
struct _PSMoveTracker;
typedef struct _PSMoveTracker PSMoveTracker; /*!< Handle to a Tracker object.
Obtained via psmove_tracker_new() */
#endif
/*! Status of the tracker */
enum PSMoveTracker_Status {
Tracker_NOT_CALIBRATED, /*!< Controller not registered with tracker */
Tracker_CALIBRATION_ERROR, /*!< Calibration failed (check lighting, visibility) */
Tracker_CALIBRATED, /*!< Color calibration successful, not currently tracking */
Tracker_TRACKING, /*!< Calibrated and successfully tracked in the camera */
};
/*! Exposure modes */
enum PSMoveTracker_Exposure {
Exposure_LOW, /*!< Very low exposure: Good tracking, no environment visible */
Exposure_MEDIUM, /*!< Middle ground: Good tracking, environment visible */
Exposure_HIGH, /*!< High exposure: Fair tracking, but good environment */
Exposure_INVALID, /*!< Invalid exposure value (for returning failures) */
};
/*! Smoothing algorithm used on position */
enum PSMoveTracker_Smoothing_Type {
Smoothing_None, // Don't use any smoothing
Smoothing_LowPass, // A basic low pass filter (default)
Smoothing_Kalman, // A more expensive Kalman filter
};
/*! Known camera types. Used for calculating focal length when calibration not present. */
enum PSMoveTracker_Camera_type {
PSMove_Camera_PS3EYE_BLUEDOT,
PSMove_Camera_PS3EYE_REDDOT,
PSMove_Camera_Unknown
};
/*! Known camera types. Used for calculating focal length when calibration not present. */
enum PSMoveTracker_ErrorCode {
PSMove_Camera_Error_None,
PSMove_Camera_Not_Found,
PSMove_Camera_USB_Open_Failure,
PSMove_Camera_Query_Frame_Failure,
};
struct _PSMoveTrackerSmoothingSettings {
// Low Pass Filter Options
int filter_do_2d_xy; /* [1] specifies to use a adaptive x/y smoothing on pixel location */
int filter_do_2d_r; /* [1] specifies to use a adaptive radius smoothing on 2d blob */
enum PSMoveTracker_Smoothing_Type filter_3d_type;
// Kalman Filter Options
float acceleration_variance;
PSMove_3AxisTransform measurement_covariance;
};
typedef struct _PSMoveTrackerSmoothingSettings PSMoveTrackerSmoothingSettings;
/* A structure to retain the tracker settings. Typically these do not change after init & calib.*/
typedef struct {
/* Camera Controls*/
int camera_frame_width; /* [0=auto] */
int camera_frame_height; /* [0=auto] */
int camera_frame_rate; /* [0=auto] */
enum PSMove_Bool camera_auto_gain; /* [PSMove_False] */
int camera_gain; /* [0] [0,0xFFFF] */
enum PSMove_Bool camera_auto_white_balance; /* [PSMove_False] */
int camera_exposure; /* [(255 * 15) / 0xFFFF] [0,0xFFFF] */
int camera_brightness; /* [0] [0,0xFFFF] */
enum PSMove_Bool camera_mirror; /* [PSMove_False] mirror camera image horizontally */
enum PSMoveTracker_Camera_type camera_type; /* [PSMove_Camera_PS3EYE_BLUEDOT] camera type. Used for focal length when OpenCV calib missing */
/* Settings for camera calibration process */
enum PSMoveTracker_Exposure exposure_mode; /* [Exposure_LOW] exposure mode for setting target luminance */
int calibration_blink_delay; /* [200] number of milliseconds to wait between a blink */
int calibration_diff_t; /* [20] during calibration, all grey values in the diff image below this value are set to black */
int calibration_min_size; /* [50] minimum size of the estimated glowing sphere during calibration process (in pixel) */
int calibration_max_distance; /* [30] maximum displacement of the separate found blobs */
int calibration_size_std; /* [10] maximum standard deviation (in %) of the glowing spheres found during calibration process */
int color_mapping_max_age; /* [2*60*60] Only re-use color mappings "younger" than this time in seconds */
float dimming_factor; /* [1.f] dimming factor used on LED RGB values */
/* Settings for OpenCV image processing for sphere detection */
int color_hue_filter_range; /* [20] +- range of Hue window of the hsv-colorfilter */
int color_saturation_filter_range; /* [85] +- range of Sat window of the hsv-colorfilter */
int color_value_filter_range; /* [85] +- range of Value window of the hsv-colorfilter */
/* Settings for tracker algorithms */
int use_fitEllipse; /* [0] estimate circle from blob; [1] use fitEllipse */
float color_adaption_quality_t; /* [35] maximal distance (calculated by 'psmove_tracker_hsvcolor_diff') between the first estimated color and the newly estimated */
float color_update_rate; /* [1] every x seconds adapt to the color, 0 means no adaption */
// size of "search" tiles when tracking is lost
int search_tile_width; /* [0=auto] width of a single tile */
int search_tile_height; /* height of a single tile */
int search_tiles_horizontal; /* number of search tiles per row */
int search_tiles_count; /* number of search tiles */
/* THP-specific tracker threshold checks */
int roi_adjust_fps_t; /* [160] the minimum fps to be reached, if a better roi-center adjusment is to be perfomred */
// if tracker thresholds not met, sphere is deemed not to be found
float tracker_quality_t1; /* [0.3f] minimum ratio of number of pixels in blob vs pixel of estimated circle. */
float tracker_quality_t2; /* [0.7f] maximum allowed change of the radius in percent, compared to the last estimated radius */
float tracker_quality_t3; /* [4.7f] minimum radius */
// if color thresholds not met, color is not adapted
float color_update_quality_t1; /* [0.8] minimum ratio of number of pixels in blob vs pixel of estimated circle. */
float color_update_quality_t2; /* [0.2] maximum allowed change of the radius in percent, compared to the last estimated radius */
float color_update_quality_t3; /* [6.f] minimum radius */
enum PSMove_Bool color_save_colormapping; /* [PSMove_True] whether or not to save the result of the color calibration to disk. */
int color_list_start_ind; /* [0] The index in [magenta, cyan, yellow, red, green/blue] to start searching for available color. */
/* CBB-specific tracker parameters */
float xorigin_cm; /* [0.f] x-distance to subtract from calculated position */
float yorigin_cm; /* [0.f] y-distance to subtract from calculated position */
float zorigin_cm; /* [0.f] z-distance to subtract from calculated position */
} PSMoveTrackerSettings; /*!< Structure for storing tracker settings */
/**
* \brief Initializes a tracker settings with default values
*
* If you want to initialize a camera with custom settings,
* it's recommended you initialize the settings struct with this first
*
**/
ADDAPI void
ADDCALL psmove_tracker_settings_set_default(PSMoveTrackerSettings *settings);
/**
* \brief Copies current tracker settings from tracker into settings.
*
**/
ADDAPI void
ADDCALL psmove_tracker_get_settings(PSMoveTracker *tracker, PSMoveTrackerSettings *settings);
/**
* \brief Copies settings into tracker settings.
*
**/
ADDAPI void
ADDCALL psmove_tracker_set_settings(PSMoveTracker *tracker, PSMoveTrackerSettings *settings);
/**
* \brief Create a new PS Move Tracker instance and open the camera
*
* This will select the best camera for tracking (this means that if
* a PSEye is found, it will be used, otherwise the first available
* camera will be used as fallback).
*
* Uses default settings
*
* \return A new \ref PSMoveTracker instance or \c NULL on error
**/
ADDAPI PSMoveTracker *
ADDCALL psmove_tracker_new();
/**
* \brief Create a new PS Move Tracker instance and open the camera
*
* This will select the best camera for tracking (this means that if
* a PSEye is found, it will be used, otherwise the first available
* camera will be used as fallback).
*
* \param settings Tracker and camera settings to use
*
* \return A new \ref PSMoveTracker instance or \c NULL on error
**/
ADDAPI PSMoveTracker *
ADDCALL psmove_tracker_new_with_settings(PSMoveTrackerSettings *settings);
/**
* \brief Create a new PS Move Tracker instance with a specific camera
*
* This function can be used when multiple cameras are available to
* force the use of a specific camera.
*
* Usually it's better to use psmove_tracker_new() and let the library
* choose the best camera, unless you have a good reason not to.
*
* \param camera Zero-based index of the camera to use
*
* \return A new \ref PSMoveTracker instance or \c NULL on error
**/
ADDAPI PSMoveTracker *
ADDCALL psmove_tracker_new_with_camera(int camera);
/**
* \brief Create a new PS Move Tracker instance with a specific camera
*
* This function can be used when multiple cameras are available to
* force the use of a specific camera.
*
* Usually it's better to use psmove_tracker_new() and let the library
* choose the best camera, unless you have a good reason not to.
*
* \param camera Zero-based index of the camera to use
* \param settings Tracker and camera settings to use
*
* \return A new \ref PSMoveTracker instance or \c NULL on error
**/
ADDAPI PSMoveTracker *
ADDCALL psmove_tracker_new_with_camera_and_settings(int camera, PSMoveTrackerSettings *settings);
/**
* \brief Get the last error posted by the tracker when the tracker initialized
*
* \return A \ref PSMoveTracker_ErrorCode result code
**/
ADDAPI enum PSMoveTracker_ErrorCode
ADDCALL psmove_tracker_get_last_error();
/**
* \brief Instructs the PSMoveTracker to load its distortion settings from file.
*
* \param tracker A valid \ref PSMoveTracker handle
**/
ADDAPI void
ADDCALL psmove_tracker_load_distortion(PSMoveTracker *tracker);
/**
* \brief Instructs the PSMoveTracker to set its distortion to 0.
*
* \param tracker A valid \ref PSMoveTracker handle
**/
ADDAPI void
ADDCALL psmove_tracker_reset_distortion(PSMoveTracker *tracker);
/**
* \brief Configure if the LEDs of a controller should be auto-updated
*
* If auto-update is enabled (the default), the tracker will set and
* update the LEDs of the controller automatically. If not, the user
* must set the LEDs of the controller and update them regularly. In
* that case, the user can use psmove_tracker_get_color() to determine
* the color that the controller's LEDs have to be set to.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
* \param auto_update_leds \ref PSMove_True to auto-update LEDs from
* the tracker, \ref PSMove_False if the user
* will take care of updating the LEDs
**/
ADDAPI void
ADDCALL psmove_tracker_set_auto_update_leds(PSMoveTracker *tracker, PSMove *move,
enum PSMove_Bool auto_update_leds);
/**
* \brief Check if the LEDs of a controller are updated automatically
*
* This is the getter function for psmove_tracker_set_auto_update_leds().
* See there for details on what auto-updating LEDs means.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
*
* \return \ref PSMove_True if the controller's LEDs are set to be
* updated automatically, \ref PSMove_False otherwise
**/
ADDAPI enum PSMove_Bool
ADDCALL psmove_tracker_get_auto_update_leds(PSMoveTracker *tracker, PSMove *move);
/**
* \brief Set the LED dimming value for all controller
*
* Usually it's not necessary to call this function, as the dimming
* is automatically determined when the first controller is enabled.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param dimming A value in the range from 0 (LEDs switched off) to
* 1 (full LED intensity)
**/
ADDAPI void
ADDCALL psmove_tracker_set_dimming(PSMoveTracker *tracker, float dimming);
/**
* \brief Get the LED dimming value for all controllers
*
* See psmove_tracker_set_dimming() for details.
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \return The dimming value for the LEDs
**/
ADDAPI float
ADDCALL psmove_tracker_get_dimming(PSMoveTracker *tracker);
/**
* \brief Set the desired camera exposure mode
*
* This function sets the desired exposure mode. This should be
* called before controllers are added to the tracker, so that the
* dimming for the controllers can be determined for the specific
* exposure setting.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param exposure One of the \ref PSMoveTracker_Exposure values
**/
ADDAPI void
ADDCALL psmove_tracker_set_exposure(PSMoveTracker *tracker, enum PSMoveTracker_Exposure exposure);
/**
* \brief Get the desired camera exposure mode
*
* See psmove_tracker_set_exposure() for details.
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \return One of the \ref PSMoveTracker_Exposure values
**/
ADDAPI enum PSMoveTracker_Exposure
ADDCALL psmove_tracker_get_exposure(PSMoveTracker *tracker);
/**
* \brief Set the desired camera focal length.
*
* This function sets the desired camera focal length. Only use this if you
* have NOT calibrated the camera (with OpenCV checkerboard utility)
* and if you really know what you are doing.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param focal_length The (float) focal length in pixels to be set.
**/
ADDAPI void
ADDCALL psmove_tracker_set_focal_length(PSMoveTracker *tracker, float focal_length);
/**
* \brief Get the camera's focal_length (in pixels)
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \param float* focal_length_out A pointer to the output value
**/
ADDAPI int
ADDCALL psmove_tracker_get_focal_length(PSMoveTracker *tracker, float* focal_length_out);
/**
* \brief Set the smoothing filter settings.
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \param smoothing_settings A valid \ref PSMoveTrackerSmoothingSettings handle
**/
ADDAPI void
ADDCALL psmove_tracker_set_smoothing_settings(PSMoveTracker *tracker, PSMoveTrackerSmoothingSettings *smoothing_settings);
/**
* \brief Copy the tracker's smoothing filter settings to smoothing_settings.
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \param smoothing_settings A valid \ref PSMoveTrackerSmoothingSettings handle
**/
ADDAPI void
ADDCALL psmove_tracker_get_smoothing_settings(PSMoveTracker *tracker, PSMoveTrackerSmoothingSettings *smoothing_settings);
/**
* \brief Initializes a tracker smoothing settings with default values
*
* These values are overridden if the smoothing settings calibration file exists
**/
ADDAPI void
ADDCALL psmove_tracker_smoothing_settings_set_default(PSMoveTrackerSmoothingSettings *smoothing_settings);
/**
* \brief Save the given smoothing settings to disk
*
* These values when loaded, take precedence over the defaults.
*
* \return A new PSMove_True on success, PSMove_False on IO error
**/
ADDAPI enum PSMove_Bool
ADDCALL psmove_tracker_save_smoothing_settings(PSMoveTrackerSmoothingSettings *smoothing_settings);
/**
* \brief Load the smoothing settings from disk
*
* These values are take precedence over the defaults.
*
* \return A new PSMove_True on success, PSMove_False on IO error**/
ADDAPI enum PSMove_Bool
ADDCALL psmove_tracker_load_smoothing_settings(PSMoveTrackerSmoothingSettings *out_smoothing_settings);
/**
* \brief Set the positional smoothing algorithm to use.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param smoothing_type The smoothing algorithm to use (see \ref PSMoveTracker_Smoothing_Type).
**/
ADDAPI void
ADDCALL psmove_tracker_set_smoothing_type(PSMoveTracker *tracker, enum PSMoveTracker_Smoothing_Type smoothing_type);
/**
* \brief Set the smoothing parameters for the basic low pass filter.
*
* This function enables (1) or disables (0) smoothing for xy and z dimensions.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param filter_lowpass_do_xy int 0 or 1
* \param filter_lowpass_do_z int 0 or 1
**/
ADDAPI void
ADDCALL psmove_tracker_set_smoothing_2d(PSMoveTracker *tracker, int filter_lowpass_do_xy, int filter_lowpass_do_z);
/**
* \brief Enable or disable camera image deinterlacing (line doubling)
*
* Enables or disables camera image deinterlacing for this tracker.
* You usually only want to enable deinterlacing if your camera source
* provides interlaced images (e.g. 1080i). The interlacing will be
* removed by doubling every other line. By default, deinterlacing is
* disabled.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param enabled \ref PSMove_True to enable deinterlacing,
* \ref PSMove_False to disable deinterlacing (default)
**/
ADDAPI void
ADDCALL psmove_tracker_enable_deinterlace(PSMoveTracker *tracker,
enum PSMove_Bool enabled);
/**
* \brief Enable or disable horizontal camera image mirroring
*
* Enables or disables horizontal mirroring of the camera image. The
* mirroring setting will affect the X coordinates of the controller
* positions tracked, as well as the output image. In addition, the
* sensor fusion module will mirror the orientation information if
* mirroring is set here. By default, mirroring is disabled.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param enabled \ref PSMove_True to mirror the image horizontally,
* \ref PSMove_False to leave the image as-is (default)
**/
ADDAPI void
ADDCALL psmove_tracker_set_mirror(PSMoveTracker *tracker,
enum PSMove_Bool enabled);
/**
* \brief Query the current camera image mirroring state
*
* See psmove_tracker_set_mirror() for details.
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \return \ref PSMove_True if mirroring is enabled,
* \ref PSMove_False if mirroring is disabled
**/
ADDAPI enum PSMove_Bool
ADDCALL psmove_tracker_get_mirror(PSMoveTracker *tracker);
/**
* \brief Enable tracking of a motion controller
*
* Calling this function will register the controller with the
* tracker, and start blinking calibration. The user should hold
* the motion controller in front of the camera and wait for the
* calibration to finish.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
*
* \return \ref Tracker_CALIBRATED if calibration succeeded
* \return \ref Tracker_CALIBRATION_ERROR if calibration failed
**/
ADDAPI enum PSMoveTracker_Status
ADDCALL psmove_tracker_enable(PSMoveTracker *tracker, PSMove *move);
/**
* \brief Enable tracking with a custom sphere color
*
* This function does basically the same as psmove_tracker_enable(),
* but forces the sphere color to a pre-determined value.
*
* Using this function might give worse tracking results, because
* the color might not be optimal for a given lighting condition.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
* \param r The red intensity of the desired color (0..255)
* \param g The green intensity of the desired color (0..255)
* \param b The blue intensity of the desired color (0..255)
*
* \return \ref Tracker_CALIBRATED if calibration succeeded
* \return \ref Tracker_CALIBRATION_ERROR if calibration failed
**/
ADDAPI enum PSMoveTracker_Status
ADDCALL psmove_tracker_enable_with_color(PSMoveTracker *tracker, PSMove *move,
unsigned char r, unsigned char g, unsigned char b);
/**
* \brief Disable tracking of a motion controller
*
* If the \ref PSMove instance was never enabled, this function
* does nothing. Otherwise it removes the instance from the
* tracker and stops tracking the controller.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
**/
ADDAPI void
ADDCALL psmove_tracker_disable(PSMoveTracker *tracker, PSMove *move);
/**
* \brief Get the desired sphere color of a motion controller
*
* Get the sphere color of the controller as it is set using
* psmove_update_leds(). This is not the color as the sphere
* appears in the camera - for that, see
* psmove_tracker_get_camera_color().
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A Valid \ref PSmove handle
* \param r Pointer to store the red component of the color
* \param g Pointer to store the green component of the color
* \param g Pointer to store the blue component of the color
*
* \return Nonzero if the color was successfully returned, zero if
* if the controller is not enabled of calibration has not
* completed yet.
**/
ADDAPI int
ADDCALL psmove_tracker_get_color(PSMoveTracker *tracker, PSMove *move,
unsigned char *r, unsigned char *g, unsigned char *b);
/**
* \brief Get the sphere color of a controller in the camera image
*
* Get the sphere color of the controller as it currently
* appears in the camera image. This is not the color that is
* set using psmove_update_leds() - for that, see
* psmove_tracker_get_color().
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A Valid \ref PSmove handle
* \param r Pointer to store the red component of the color
* \param g Pointer to store the green component of the color
* \param g Pointer to store the blue component of the color
*
* \return Nonzero if the color was successfully returned, zero if
* if the controller is not enabled of calibration has not
* completed yet.
**/
ADDAPI int
ADDCALL psmove_tracker_get_camera_color(PSMoveTracker *tracker, PSMove *move,
unsigned char *r, unsigned char *g, unsigned char *b);
/**
* \brief Set the sphere color of a controller in the camera image
*
* This function should only be used in special situations - it is
* usually not required to manually set the sphere color as it appears
* in the camera image, as this color is determined at runtime during
* blinking calibration. For some use cases, it might be useful to
* set the color manually (e.g. when the user should be able to select
* the color in the camera image after lighting changes).
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
* \param r The red component of the color (0..255)
* \param g The green component of the color (0..255)
* \param b The blue component of the color (0..255)
*
* \return Nonzero if the color was successfully set, zero if
* if the controller is not enabled of calibration has not
* completed yet.
**/
ADDAPI int
ADDCALL psmove_tracker_set_camera_color(PSMoveTracker *tracker, PSMove *move,
unsigned char r, unsigned char g, unsigned char b);
/**
* \brief Set the sphere color to the next colour in the list of default colours.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
*
* \return Nonzero if the color was successfully cycled, zero if
* if the controller is not enabled or calibration has not
* completed yet.
**/
ADDAPI int
ADDCALL psmove_tracker_cycle_color(PSMoveTracker *tracker, PSMove *move);
/**
* \brief Set the sphere color to a default colour in the list.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
* \param req_ind The indice of the requested color
*
* \return Nonzero if the color was successfully set, zero if
* if the controller is not enabled or calibration has not
* completed yet.
**/
ADDAPI int
ADDCALL psmove_tracker_use_color_at_index(PSMoveTracker *tracker, PSMove *move, int req_ind);
/**
* \brief Query the tracking status of a motion controller
*
* This function returns the current tracking status (or calibration
* status if the controller is not calibrated yet) of a controller.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
*
* \return One of the \ref PSMoveTracker_Status values
**/
ADDAPI enum PSMoveTracker_Status
ADDCALL psmove_tracker_get_status(PSMoveTracker *tracker, PSMove *move);
/**
* \brief Retrieve the next image from the camera
*
* This function should be called once per main loop iteration (even
* if multiple controllers are tracked), and will grab the next camera
* image from the camera input device.
*
* This function must be called before psmove_tracker_update().
*
* \param tracker A valid \ref PSMoveTracker handle
**/
ADDAPI void
ADDCALL psmove_tracker_update_image(PSMoveTracker *tracker);
/**
* \brief Process incoming data and update tracking information
*
* This function tracks one or all motion controllers in the camera
* image, and updates tracking information such as pixel position,
* 3D position, and camera color.
*
* This function must be called after psmove_tracker_update_image().
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle (to update a single controller)
* or \c NULL to update all enabled controllers at once
*
* \return Nonzero if tracking was successful, zero otherwise
**/
ADDAPI int
ADDCALL psmove_tracker_update(PSMoveTracker *tracker, PSMove *move);
/**
* \brief Draw debugging information onto the current camera image
*
* This function has to be called after psmove_tracker_update(), and
* will annotate the camera image with sphere positions and other
* information. The camera image will be modified in place, so no
* call to psmove_tracker_update() should be carried out before the
* next call to psmove_tracker_update_image().
*
* This function is used for demonstration and debugging purposes, in
* production environments you usually do not want to use it.
*
* \param tracker A valid \ref PSMoveTracker handle
*/
ADDAPI void
ADDCALL psmove_tracker_annotate(PSMoveTracker* tracker);
/**
* \brief Get the current camera image as backend-specific pointer
*
* This function returns a pointer to the backend-specific camera
* image. Right now, the only backend supported is OpenCV, so the
* return value will always be a pointer to an IplImage structure.
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \return A pointer to the camera image (currently always an IplImage)
* - the caller MUST NOT modify or free the returned object.
**/
ADDAPI void*
ADDCALL psmove_tracker_get_frame(PSMoveTracker *tracker);
/**
* \brief Get the current camera image as 24-bit RGB data blob
*
* This function converts the internal camera image to a tightly-packed
* 24-bit RGB image. The \ref PSMoveTrackerRGBImage structure is used
* to return the image data pointer as well as the width and height of
* the camera imaged. The size of the image data is 3 * width * height.
*
* The returned pixel data pointer points to tracker-internal data, and must
* not be freed. The returned RGB data will only be valid as long as the
* tracker exists.
*
* \param tracker A valid \ref PSMoveTracker handle
*
* \return A \ref PSMoveTrackerRGBImage describing the RGB data and size.
* The RGB data is owned by the tracker, and must not be freed by
* the caller. The return value is valid only for the lifetime of
* the tracker object.
**/
ADDAPI PSMoveTrackerRGBImage
ADDCALL psmove_tracker_get_image(PSMoveTracker *tracker);
/**
* \brief Get the current position and radius of a tracked controller
*
* This function obtains the position and radius of a controller in the
* camera image.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
* \param x A pointer to store the X part of the position, or \c NULL
* \param y A pointer to store the Y part of the position, or \c NULL
* \param radius A pointer to store the controller radius, or \C NULL
*
* \return The age of the sensor reading in milliseconds, or -1 on error
**/
ADDAPI int
ADDCALL psmove_tracker_get_position(PSMoveTracker *tracker,
PSMove *move, float *x, float *y, float *radius);
/**
* \brief Get the current 3D location of a tracked controller
*
* This function obtains the location of a controller in the
* world in cm.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
* \param xcm A pointer to store the X part of the location, or \c NULL
* \param ycm A pointer to store the Y part of the location, or \c NULL
* \param zcm A pointer to store the Z part of the location, or \c NULL
*
* \return The age of the sensor reading in milliseconds, or -1 on error
**/
ADDAPI int
ADDCALL psmove_tracker_get_location(PSMoveTracker *tracker,
PSMove *move, float *xcm, float *ycm, float *zcm);
/**
* \brief Rest the location offsets to the current location
*
* \param tracker A valid \ref PSMoveTracker handle
* \param move A valid \ref PSMove handle
*
**/
ADDAPI void
ADDCALL psmove_tracker_reset_location(PSMoveTracker *tracker, PSMove *move);
/**
* \brief Get the camera image size for the tracker
*
* This function can be used to obtain the real camera image size used
* by the tracker. This is useful to convert the absolute position and
* radius values to values relative to the image size if a camera is
* used for which the size is now known. By default, the PS Eye camera
* is used with an image size of 640x480.
*
* \param tracker A valid \ref PSMoveTracker handle
* \param width A pointer to store the width of the camera image
* \param height A pointer to store the height of the camera image
**/
ADDAPI void
ADDCALL psmove_tracker_get_size(PSMoveTracker *tracker,
int *width, int *height);
/**
* \brief Calculate the physical distance (in cm) of the controller
*
* Given the radius of the controller in the image (in pixels), this function
* calculates the physical distance of the controller from the camera (in cm).
*
* By default, this function's parameters are set up for the PS Eye camera in
* wide angle view. You can set different parameters using the function
* psmove_tracker_set_distance_parameters().
*
* \param tracker A valid \ref PSMoveTracker handle
* \param radius The radius for which the distance should be calculated, the
* radius is returned by psmove_tracker_get_position()
**/
ADDAPI float
ADDCALL psmove_tracker_distance_from_radius(PSMoveTracker *tracker,
float radius);
/**
* \brief Set the parameters for the distance mapping function
*
* This function sets the parameters for the Pearson VII distribution
* function that's used to map radius values to distance values in
* psmove_tracker_distance_from_radius(). By default, the parameters are
* set up so that they work well for a PS Eye camera in wide angle mode.
*
* The function is defined as in: http://fityk.nieto.pl/model.html
*
* distance = height / ((1+((radius-center)/hwhm)^2 * (2^(1/shape)-1)) ^ shape)
*
* \param tracker A valid \ref PSMoveTracker handle
* \param height The height parameter of the Pearson VII distribution
* \param center The center parameter of the Pearson VII distribution
* \param hwhm The hwhm parameter of the Pearson VII distribution
* \param shape The shape parameter of the Pearson VII distribution
**/
ADDAPI void
ADDCALL psmove_tracker_set_distance_parameters(PSMoveTracker *tracker,
float height, float center, float hwhm, float shape);
/**
* \brief Destroy an existing tracker instance and free allocated resources
*
* This will shut down the tracker, clean up all state information for
* tracked controller as well as close the camera device. Return values
* for functions returning data pointing to internal tracker data structures
* will become invalid after this function call.
*
* \param tracker A valid \ref PSMoveTracker handle
**/
ADDAPI void
ADDCALL psmove_tracker_free(PSMoveTracker *tracker);
#ifdef __cplusplus
}
#endif
#endif
| 39.365169 | 181 | 0.735465 | [
"object",
"shape",
"model",
"3d"
] |
9a70850a444f987a363547eb009170005e0c4895 | 8,765 | h | C | src/gpu/ops/GrQuadPerEdgeAA.h | jonhpark7966/skia | 39d16248f5a7d1692cec49847052cf3a5b420ff1 | [
"BSD-3-Clause"
] | null | null | null | src/gpu/ops/GrQuadPerEdgeAA.h | jonhpark7966/skia | 39d16248f5a7d1692cec49847052cf3a5b420ff1 | [
"BSD-3-Clause"
] | null | null | null | src/gpu/ops/GrQuadPerEdgeAA.h | jonhpark7966/skia | 39d16248f5a7d1692cec49847052cf3a5b420ff1 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrQuadPerEdgeAA_DEFINED
#define GrQuadPerEdgeAA_DEFINED
#include "GrColor.h"
#include "GrPrimitiveProcessor.h"
#include "GrSamplerState.h"
#include "GrTypesPriv.h"
#include "glsl/GrGLSLPrimitiveProcessor.h"
#include "SkPoint.h"
#include "SkPoint3.h"
class GrGLSLColorSpaceXformHelper;
class GrPerspQuad;
class GrQuadPerEdgeAA {
public:
enum class Domain : bool { kNo = false, kYes = true };
// The vertex template provides a clean way of specifying the layout and components of a vertex
// for a per-edge aa quad. However, because there are so many permutations possible, the struct
// is defined this way to take away all layout control from the compiler and make
// sure that it matches what we need to send to the GPU.
//
// It is expected that most code using these vertices will only need to call the templated
// Tessellate() function with an appropriately sized vertex buffer and not need to modify or
// read the fields of a particular vertex.
template <int PosDim, typename C, int LocalPosDim, Domain D, GrAA AA>
struct Vertex {
using Color = C;
static constexpr GrAA kAA = AA;
static constexpr Domain kDomain = D;
static constexpr size_t kPositionDim = PosDim;
static constexpr size_t kLocalPositionDim = LocalPosDim;
static constexpr size_t kPositionOffset = 0;
static constexpr size_t kPositionSize = PosDim * sizeof(float);
static constexpr size_t kColorOffset = kPositionOffset + kPositionSize;
static constexpr size_t kColorSize = sizeof(Color);
static constexpr size_t kLocalPositionOffset = kColorOffset + kColorSize;
static constexpr size_t kLocalPositionSize = LocalPosDim * sizeof(float);
static constexpr size_t kDomainOffset = kLocalPositionOffset + kLocalPositionSize;
static constexpr size_t kDomainSize = D == Domain::kYes ? sizeof(SkRect) : 0;
static constexpr size_t kAAOffset = kDomainOffset + kDomainSize;
static constexpr size_t kAASize = AA == GrAA::kYes ? 4 * sizeof(SkPoint3) : 0;
static constexpr size_t kVertexSize = kAAOffset + kAASize;
// Make sure sizeof(Vertex<...>) == kVertexSize
char fData[kVertexSize];
};
// Utility class that manages the attribute state necessary to render a particular batch of
// quads. It is similar to a geometry processor but is meant to be included in a has-a
// relationship by specialized GP's that provide further functionality on top of the per-edge AA
// coverage.
//
// For performance reasons, this uses fixed names for the attribute variables; since it defines
// the majority of attributes a GP will likely need, this shouldn't be too limiting.
//
// In terms of responsibilities, the actual geometry processor must still call emitTransforms(),
// using the localCoords() attribute as the 4th argument; it must set the transform data helper
// to use the identity matrix; it must manage the color space transform for the quad's paint
// color; it should include getKey() in the geometry processor's key builder; and it should
// return these managed attributes from its onVertexAttribute() function.
class GPAttributes {
public:
using Attribute = GrPrimitiveProcessor::Attribute;
GPAttributes(int posDim, int localDim, bool hasColor, GrAAType aa, Domain domain);
const Attribute& positions() const { return fPositions; }
const Attribute& colors() const { return fColors; }
const Attribute& localCoords() const { return fLocalCoords; }
const Attribute& domain() const { return fDomain; }
const Attribute& edges(int i) const { return fAAEdges[i]; }
bool hasVertexColors() const { return fColors.isInitialized(); }
bool usesCoverageAA() const { return fAAEdges[0].isInitialized(); }
bool hasLocalCoords() const { return fLocalCoords.isInitialized(); }
bool hasDomain() const { return fDomain.isInitialized(); }
bool needsPerspectiveInterpolation() const;
int vertexAttributeCount() const;
uint32_t getKey() const;
// Functions to be called at appropriate times in a processor's onEmitCode() block. These
// are separated into discrete pieces so that they can be interleaved with the rest of the
// processor's shader code as needed. The functions take char* arguments for the names of
// variables the emitted code must declare, so that the calling GP can ensure there's no
// naming conflicts with their own code.
void emitColor(GrGLSLPrimitiveProcessor::EmitArgs& args,
GrGLSLColorSpaceXformHelper* colorSpaceXformHelper,
const char* colorVarName) const;
// localCoordName will be declared as a float2, with any domain applied after any
// perspective division is performed.
//
// Note: this should only be used if the local coordinates need to be passed separately
// from the standard coord transform process that is used by FPs.
// FIXME: This can go in two directions from here, if GrTextureOp stops needing per-quad
// domains it can be removed and GrTextureOp rewritten to use coord transforms. Or
// emitTransform() in the primitive builder can be updated to have a notion of domain for
// local coords, and all domain-needing code (blurs, filters, etc.) can switch to that magic
void emitExplicitLocalCoords(GrGLSLPrimitiveProcessor::EmitArgs& args,
const char* localCoordName, const char* domainVarName) const;
void emitCoverage(GrGLSLPrimitiveProcessor::EmitArgs& args, const char* edgeDistName) const;
private:
Attribute fPositions; // named "position" in SkSL
Attribute fColors; // named "color" in SkSL
Attribute fLocalCoords; // named "localCoord" in SkSL
Attribute fDomain; // named "domain" in SkSL
Attribute fAAEdges[4]; // named "aaEdgeX" for X = 0,1,2,3
};
// Tessellate the given quad specification into the vertices buffer. If the specific vertex
// type does not use color, local positions, domain, etc. then the passed in values used for
// that field will be ignored.
template<typename V>
static void Tessellate(V* vertices, const GrPerspQuad& deviceQuad, typename V::Color color,
const GrPerspQuad& srcQuad, const SkRect& domain, GrQuadAAFlags aa) {
static_assert(sizeof(V) == V::kVertexSize, "Incorrect vertex size");
static constexpr bool useCoverageAA = V::kAA == GrAA::kYes;
float localStorage[4 * (V::kPositionDim + V::kLocalPositionDim + (useCoverageAA ? 3 : 0))];
TessellateImpl(vertices, V::kVertexSize, localStorage,
deviceQuad, V::kPositionDim, V::kPositionOffset, V::kPositionSize,
&color, V::kColorOffset, V::kColorSize,
srcQuad, V::kLocalPositionDim, V::kLocalPositionOffset, V::kLocalPositionSize,
&domain, V::kDomainOffset, V::kDomainSize,
aa, V::kAAOffset, V::kAASize);
}
private:
// Don't let the "namespace" class be instantiated
GrQuadPerEdgeAA();
// Internal implementation that can handle all vertex template variations without being
// replicated by the template in order to keep code size down.
//
// This uses the field sizes to determine if particular data needs to be computed. The arguments
// are arranged so that the data and field specification match the field declaration order of
// the vertex type (pos, color, localPos, domain, aa).
//
// localStorage must be have a length > 4 * (devDimCt + srcDimCt + (aa ? 3 : 0)) and is assumed
// to be a pointer to a local variable in the wrapping template's stack. This is done instead of
// always allocating 36 floats in this function (36 is maximum needed). The minimum needed for a
// non-AA 2D quad with no local coordinates is just 8.
static void TessellateImpl(void* vertices, size_t vertexSize, float* localStorage,
const GrPerspQuad& deviceQuad, int posDim, size_t posOffset, size_t posSize,
const void* color, size_t colorOffset, size_t colorSize,
const GrPerspQuad& srcQuad, int srcDim, size_t srcOffset, size_t srcSize,
const void* domain, size_t domainOffset, size_t domainSize,
GrQuadAAFlags aaFlags, size_t aaOffset, size_t aaSize);
};
#endif // GrQuadPerEdgeAA_DEFINED
| 50.373563 | 100 | 0.692983 | [
"geometry",
"render",
"transform"
] |
9a7263ee30a7dcb1113f96f781ab0f1f0575325b | 4,588 | h | C | packages/zoltan/src/include/zoltan_dd_cpp.h | tokusanya/seacas | 54d9c3b68508ca96e3db1fd00c5d84a810fb330b | [
"Zlib",
"NetCDF",
"MIT",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | null | null | null | packages/zoltan/src/include/zoltan_dd_cpp.h | tokusanya/seacas | 54d9c3b68508ca96e3db1fd00c5d84a810fb330b | [
"Zlib",
"NetCDF",
"MIT",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | null | null | null | packages/zoltan/src/include/zoltan_dd_cpp.h | tokusanya/seacas | 54d9c3b68508ca96e3db1fd00c5d84a810fb330b | [
"Zlib",
"NetCDF",
"MIT",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | null | null | null | /*
* @HEADER
*
* ***********************************************************************
*
* Zoltan Toolkit for Load-balancing, Partitioning, Ordering and Coloring
* Copyright 2012 Sandia Corporation
*
* Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
* the U.S. Government retains certain rights in this software.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Corporation nor the names of the
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
* 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.
*
* Questions? Contact Karen Devine kddevin@sandia.gov
* Erik Boman egboman@sandia.gov
*
* ***********************************************************************
*
* @HEADER
*/
// ************************************************************************
//
// C++ wrappers for Zoltan's Distributed Directory utility
//
// Two styles of initialization:
//
// C++ style: Zoltan_DD dd(comm, num_gid, num_lid, len1, len2, debug);
//
// C style: Zoltan_DD dd;
// dd.Create(comm, num_gid, num_lid, len1, len2, debug);
//
// ************************************************************************
#ifndef ZOLTAN_DD_CPP_H_
#define ZOLTAN_DD_CPP_H_
#include "zoltan_dd.h"
class Zoltan_DD {
public:
Zoltan_DD(const MPI_Comm &comm, const int &num_gid, const int &num_lid,
const int &user_length, const int &table_length, const int &debug_level)
{
Zoltan_DD_Create (&this->DD, comm, num_gid,
num_lid, user_length, table_length, debug_level);
}
Zoltan_DD()
{
this->DD = NULL;
// Creator of this object must call Zoltan_DD::Create to finish
// initialization.
}
int Create(const MPI_Comm &comm, const int &num_gid, const int &num_lid,
const int &user_length_in_chars, const int &table_length, const int &debug_level)
{
if (this->DD)
{
Zoltan_DD_Destroy(&this->DD);
this->DD = NULL;
}
int rc = Zoltan_DD_Create (&this->DD, comm, num_gid,
num_lid, user_length_in_chars, table_length, debug_level);
return rc;
}
~Zoltan_DD()
{
Zoltan_DD_Destroy (&this->DD) ;
}
Zoltan_DD (const Zoltan_DD &dd) // Copy constructor
{
this->DD = Zoltan_DD_Copy(dd.DD);
}
Zoltan_DD & operator= (const Zoltan_DD &dd) // Copy operator
{
Zoltan_DD_Copy_To(&this->DD, dd.DD);
return *this;
}
int Update (ZOLTAN_ID_PTR gid, ZOLTAN_ID_PTR lid,
char *user, int *partition, const int &count)
{
return Zoltan_DD_Update (this->DD, gid, lid, user, partition, count) ;
}
int Find (ZOLTAN_ID_PTR gid, ZOLTAN_ID_PTR lid, char *data,
int *partition, const int &count, int *owner) const
{
return Zoltan_DD_Find (this->DD, gid, lid, data, partition, count, owner);
}
int Remove (ZOLTAN_ID_PTR gid, const int &count)
{
return Zoltan_DD_Remove (this->DD, gid, count);
}
int Set_Hash_Fn (unsigned int (*hash) (ZOLTAN_ID_PTR, int, unsigned int))
{
return Zoltan_DD_Set_Hash_Fn (this->DD, hash);
}
void Stats () const
{
Zoltan_DD_Stats (this->DD) ;
}
int Print () const
{
return Zoltan_DD_Print (this->DD) ;
}
private:
Zoltan_DD_Directory *DD;
};
#endif
| 29.792208 | 86 | 0.639712 | [
"object"
] |
9a737456cb5651bad2e7fe379f2cd9250a9247f2 | 18,129 | c | C | model/franchisereferalincome_request_compound.c | eZmaxinc/eZmax-SDK-c | 355145bda84cbd548159163391ef09d1ef3c204d | [
"curl",
"MIT"
] | null | null | null | model/franchisereferalincome_request_compound.c | eZmaxinc/eZmax-SDK-c | 355145bda84cbd548159163391ef09d1ef3c204d | [
"curl",
"MIT"
] | null | null | null | model/franchisereferalincome_request_compound.c | eZmaxinc/eZmax-SDK-c | 355145bda84cbd548159163391ef09d1ef3c204d | [
"curl",
"MIT"
] | null | null | null | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "franchisereferalincome_request_compound.h"
franchisereferalincome_request_compound_t *franchisereferalincome_request_compound_create(
address_request_t *obj_address,
list_t *a_obj_contact,
int fki_franchisebroker_id,
int fki_franchisereferalincomeprogram_id,
int fki_period_id,
char *d_franchisereferalincome_loan,
char *d_franchisereferalincome_franchiseamount,
char *d_franchisereferalincome_franchisoramount,
char *d_franchisereferalincome_agentamount,
char *dt_franchisereferalincome_disbursed,
char *t_franchisereferalincome_comment,
int fki_franchiseoffice_id,
char *s_franchisereferalincome_remoteid
) {
franchisereferalincome_request_compound_t *franchisereferalincome_request_compound_local_var = malloc(sizeof(franchisereferalincome_request_compound_t));
if (!franchisereferalincome_request_compound_local_var) {
return NULL;
}
franchisereferalincome_request_compound_local_var->obj_address = obj_address;
franchisereferalincome_request_compound_local_var->a_obj_contact = a_obj_contact;
franchisereferalincome_request_compound_local_var->fki_franchisebroker_id = fki_franchisebroker_id;
franchisereferalincome_request_compound_local_var->fki_franchisereferalincomeprogram_id = fki_franchisereferalincomeprogram_id;
franchisereferalincome_request_compound_local_var->fki_period_id = fki_period_id;
franchisereferalincome_request_compound_local_var->d_franchisereferalincome_loan = d_franchisereferalincome_loan;
franchisereferalincome_request_compound_local_var->d_franchisereferalincome_franchiseamount = d_franchisereferalincome_franchiseamount;
franchisereferalincome_request_compound_local_var->d_franchisereferalincome_franchisoramount = d_franchisereferalincome_franchisoramount;
franchisereferalincome_request_compound_local_var->d_franchisereferalincome_agentamount = d_franchisereferalincome_agentamount;
franchisereferalincome_request_compound_local_var->dt_franchisereferalincome_disbursed = dt_franchisereferalincome_disbursed;
franchisereferalincome_request_compound_local_var->t_franchisereferalincome_comment = t_franchisereferalincome_comment;
franchisereferalincome_request_compound_local_var->fki_franchiseoffice_id = fki_franchiseoffice_id;
franchisereferalincome_request_compound_local_var->s_franchisereferalincome_remoteid = s_franchisereferalincome_remoteid;
return franchisereferalincome_request_compound_local_var;
}
void franchisereferalincome_request_compound_free(franchisereferalincome_request_compound_t *franchisereferalincome_request_compound) {
if(NULL == franchisereferalincome_request_compound){
return ;
}
listEntry_t *listEntry;
if (franchisereferalincome_request_compound->obj_address) {
address_request_free(franchisereferalincome_request_compound->obj_address);
franchisereferalincome_request_compound->obj_address = NULL;
}
if (franchisereferalincome_request_compound->a_obj_contact) {
list_ForEach(listEntry, franchisereferalincome_request_compound->a_obj_contact) {
contact_request_compound_free(listEntry->data);
}
list_free(franchisereferalincome_request_compound->a_obj_contact);
franchisereferalincome_request_compound->a_obj_contact = NULL;
}
if (franchisereferalincome_request_compound->d_franchisereferalincome_loan) {
free(franchisereferalincome_request_compound->d_franchisereferalincome_loan);
franchisereferalincome_request_compound->d_franchisereferalincome_loan = NULL;
}
if (franchisereferalincome_request_compound->d_franchisereferalincome_franchiseamount) {
free(franchisereferalincome_request_compound->d_franchisereferalincome_franchiseamount);
franchisereferalincome_request_compound->d_franchisereferalincome_franchiseamount = NULL;
}
if (franchisereferalincome_request_compound->d_franchisereferalincome_franchisoramount) {
free(franchisereferalincome_request_compound->d_franchisereferalincome_franchisoramount);
franchisereferalincome_request_compound->d_franchisereferalincome_franchisoramount = NULL;
}
if (franchisereferalincome_request_compound->d_franchisereferalincome_agentamount) {
free(franchisereferalincome_request_compound->d_franchisereferalincome_agentamount);
franchisereferalincome_request_compound->d_franchisereferalincome_agentamount = NULL;
}
if (franchisereferalincome_request_compound->dt_franchisereferalincome_disbursed) {
free(franchisereferalincome_request_compound->dt_franchisereferalincome_disbursed);
franchisereferalincome_request_compound->dt_franchisereferalincome_disbursed = NULL;
}
if (franchisereferalincome_request_compound->t_franchisereferalincome_comment) {
free(franchisereferalincome_request_compound->t_franchisereferalincome_comment);
franchisereferalincome_request_compound->t_franchisereferalincome_comment = NULL;
}
if (franchisereferalincome_request_compound->s_franchisereferalincome_remoteid) {
free(franchisereferalincome_request_compound->s_franchisereferalincome_remoteid);
franchisereferalincome_request_compound->s_franchisereferalincome_remoteid = NULL;
}
free(franchisereferalincome_request_compound);
}
cJSON *franchisereferalincome_request_compound_convertToJSON(franchisereferalincome_request_compound_t *franchisereferalincome_request_compound) {
cJSON *item = cJSON_CreateObject();
// franchisereferalincome_request_compound->obj_address
if (!franchisereferalincome_request_compound->obj_address) {
goto fail;
}
cJSON *obj_address_local_JSON = address_request_convertToJSON(franchisereferalincome_request_compound->obj_address);
if(obj_address_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "objAddress", obj_address_local_JSON);
if(item->child == NULL) {
goto fail;
}
// franchisereferalincome_request_compound->a_obj_contact
if (!franchisereferalincome_request_compound->a_obj_contact) {
goto fail;
}
cJSON *a_obj_contact = cJSON_AddArrayToObject(item, "a_objContact");
if(a_obj_contact == NULL) {
goto fail; //nonprimitive container
}
listEntry_t *a_obj_contactListEntry;
if (franchisereferalincome_request_compound->a_obj_contact) {
list_ForEach(a_obj_contactListEntry, franchisereferalincome_request_compound->a_obj_contact) {
cJSON *itemLocal = contact_request_compound_convertToJSON(a_obj_contactListEntry->data);
if(itemLocal == NULL) {
goto fail;
}
cJSON_AddItemToArray(a_obj_contact, itemLocal);
}
}
// franchisereferalincome_request_compound->fki_franchisebroker_id
if (!franchisereferalincome_request_compound->fki_franchisebroker_id) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "fkiFranchisebrokerID", franchisereferalincome_request_compound->fki_franchisebroker_id) == NULL) {
goto fail; //Numeric
}
// franchisereferalincome_request_compound->fki_franchisereferalincomeprogram_id
if (!franchisereferalincome_request_compound->fki_franchisereferalincomeprogram_id) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "fkiFranchisereferalincomeprogramID", franchisereferalincome_request_compound->fki_franchisereferalincomeprogram_id) == NULL) {
goto fail; //Numeric
}
// franchisereferalincome_request_compound->fki_period_id
if (!franchisereferalincome_request_compound->fki_period_id) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "fkiPeriodID", franchisereferalincome_request_compound->fki_period_id) == NULL) {
goto fail; //Numeric
}
// franchisereferalincome_request_compound->d_franchisereferalincome_loan
if (!franchisereferalincome_request_compound->d_franchisereferalincome_loan) {
goto fail;
}
if(cJSON_AddStringToObject(item, "dFranchisereferalincomeLoan", franchisereferalincome_request_compound->d_franchisereferalincome_loan) == NULL) {
goto fail; //String
}
// franchisereferalincome_request_compound->d_franchisereferalincome_franchiseamount
if (!franchisereferalincome_request_compound->d_franchisereferalincome_franchiseamount) {
goto fail;
}
if(cJSON_AddStringToObject(item, "dFranchisereferalincomeFranchiseamount", franchisereferalincome_request_compound->d_franchisereferalincome_franchiseamount) == NULL) {
goto fail; //String
}
// franchisereferalincome_request_compound->d_franchisereferalincome_franchisoramount
if (!franchisereferalincome_request_compound->d_franchisereferalincome_franchisoramount) {
goto fail;
}
if(cJSON_AddStringToObject(item, "dFranchisereferalincomeFranchisoramount", franchisereferalincome_request_compound->d_franchisereferalincome_franchisoramount) == NULL) {
goto fail; //String
}
// franchisereferalincome_request_compound->d_franchisereferalincome_agentamount
if (!franchisereferalincome_request_compound->d_franchisereferalincome_agentamount) {
goto fail;
}
if(cJSON_AddStringToObject(item, "dFranchisereferalincomeAgentamount", franchisereferalincome_request_compound->d_franchisereferalincome_agentamount) == NULL) {
goto fail; //String
}
// franchisereferalincome_request_compound->dt_franchisereferalincome_disbursed
if (!franchisereferalincome_request_compound->dt_franchisereferalincome_disbursed) {
goto fail;
}
if(cJSON_AddStringToObject(item, "dtFranchisereferalincomeDisbursed", franchisereferalincome_request_compound->dt_franchisereferalincome_disbursed) == NULL) {
goto fail; //String
}
// franchisereferalincome_request_compound->t_franchisereferalincome_comment
if (!franchisereferalincome_request_compound->t_franchisereferalincome_comment) {
goto fail;
}
if(cJSON_AddStringToObject(item, "tFranchisereferalincomeComment", franchisereferalincome_request_compound->t_franchisereferalincome_comment) == NULL) {
goto fail; //String
}
// franchisereferalincome_request_compound->fki_franchiseoffice_id
if (!franchisereferalincome_request_compound->fki_franchiseoffice_id) {
goto fail;
}
if(cJSON_AddNumberToObject(item, "fkiFranchiseofficeID", franchisereferalincome_request_compound->fki_franchiseoffice_id) == NULL) {
goto fail; //Numeric
}
// franchisereferalincome_request_compound->s_franchisereferalincome_remoteid
if (!franchisereferalincome_request_compound->s_franchisereferalincome_remoteid) {
goto fail;
}
if(cJSON_AddStringToObject(item, "sFranchisereferalincomeRemoteid", franchisereferalincome_request_compound->s_franchisereferalincome_remoteid) == NULL) {
goto fail; //String
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
franchisereferalincome_request_compound_t *franchisereferalincome_request_compound_parseFromJSON(cJSON *franchisereferalincome_request_compoundJSON){
franchisereferalincome_request_compound_t *franchisereferalincome_request_compound_local_var = NULL;
// define the local variable for franchisereferalincome_request_compound->obj_address
address_request_t *obj_address_local_nonprim = NULL;
// franchisereferalincome_request_compound->obj_address
cJSON *obj_address = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "objAddress");
if (!obj_address) {
goto end;
}
obj_address_local_nonprim = address_request_parseFromJSON(obj_address); //nonprimitive
// franchisereferalincome_request_compound->a_obj_contact
cJSON *a_obj_contact = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "a_objContact");
if (!a_obj_contact) {
goto end;
}
list_t *a_obj_contactList;
cJSON *a_obj_contact_local_nonprimitive;
if(!cJSON_IsArray(a_obj_contact)){
goto end; //nonprimitive container
}
a_obj_contactList = list_create();
cJSON_ArrayForEach(a_obj_contact_local_nonprimitive,a_obj_contact )
{
if(!cJSON_IsObject(a_obj_contact_local_nonprimitive)){
goto end;
}
contact_request_compound_t *a_obj_contactItem = contact_request_compound_parseFromJSON(a_obj_contact_local_nonprimitive);
list_addElement(a_obj_contactList, a_obj_contactItem);
}
// franchisereferalincome_request_compound->fki_franchisebroker_id
cJSON *fki_franchisebroker_id = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "fkiFranchisebrokerID");
if (!fki_franchisebroker_id) {
goto end;
}
if(!cJSON_IsNumber(fki_franchisebroker_id))
{
goto end; //Numeric
}
// franchisereferalincome_request_compound->fki_franchisereferalincomeprogram_id
cJSON *fki_franchisereferalincomeprogram_id = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "fkiFranchisereferalincomeprogramID");
if (!fki_franchisereferalincomeprogram_id) {
goto end;
}
if(!cJSON_IsNumber(fki_franchisereferalincomeprogram_id))
{
goto end; //Numeric
}
// franchisereferalincome_request_compound->fki_period_id
cJSON *fki_period_id = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "fkiPeriodID");
if (!fki_period_id) {
goto end;
}
if(!cJSON_IsNumber(fki_period_id))
{
goto end; //Numeric
}
// franchisereferalincome_request_compound->d_franchisereferalincome_loan
cJSON *d_franchisereferalincome_loan = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "dFranchisereferalincomeLoan");
if (!d_franchisereferalincome_loan) {
goto end;
}
if(!cJSON_IsString(d_franchisereferalincome_loan))
{
goto end; //String
}
// franchisereferalincome_request_compound->d_franchisereferalincome_franchiseamount
cJSON *d_franchisereferalincome_franchiseamount = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "dFranchisereferalincomeFranchiseamount");
if (!d_franchisereferalincome_franchiseamount) {
goto end;
}
if(!cJSON_IsString(d_franchisereferalincome_franchiseamount))
{
goto end; //String
}
// franchisereferalincome_request_compound->d_franchisereferalincome_franchisoramount
cJSON *d_franchisereferalincome_franchisoramount = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "dFranchisereferalincomeFranchisoramount");
if (!d_franchisereferalincome_franchisoramount) {
goto end;
}
if(!cJSON_IsString(d_franchisereferalincome_franchisoramount))
{
goto end; //String
}
// franchisereferalincome_request_compound->d_franchisereferalincome_agentamount
cJSON *d_franchisereferalincome_agentamount = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "dFranchisereferalincomeAgentamount");
if (!d_franchisereferalincome_agentamount) {
goto end;
}
if(!cJSON_IsString(d_franchisereferalincome_agentamount))
{
goto end; //String
}
// franchisereferalincome_request_compound->dt_franchisereferalincome_disbursed
cJSON *dt_franchisereferalincome_disbursed = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "dtFranchisereferalincomeDisbursed");
if (!dt_franchisereferalincome_disbursed) {
goto end;
}
if(!cJSON_IsString(dt_franchisereferalincome_disbursed))
{
goto end; //String
}
// franchisereferalincome_request_compound->t_franchisereferalincome_comment
cJSON *t_franchisereferalincome_comment = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "tFranchisereferalincomeComment");
if (!t_franchisereferalincome_comment) {
goto end;
}
if(!cJSON_IsString(t_franchisereferalincome_comment))
{
goto end; //String
}
// franchisereferalincome_request_compound->fki_franchiseoffice_id
cJSON *fki_franchiseoffice_id = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "fkiFranchiseofficeID");
if (!fki_franchiseoffice_id) {
goto end;
}
if(!cJSON_IsNumber(fki_franchiseoffice_id))
{
goto end; //Numeric
}
// franchisereferalincome_request_compound->s_franchisereferalincome_remoteid
cJSON *s_franchisereferalincome_remoteid = cJSON_GetObjectItemCaseSensitive(franchisereferalincome_request_compoundJSON, "sFranchisereferalincomeRemoteid");
if (!s_franchisereferalincome_remoteid) {
goto end;
}
if(!cJSON_IsString(s_franchisereferalincome_remoteid))
{
goto end; //String
}
franchisereferalincome_request_compound_local_var = franchisereferalincome_request_compound_create (
obj_address_local_nonprim,
a_obj_contactList,
fki_franchisebroker_id->valuedouble,
fki_franchisereferalincomeprogram_id->valuedouble,
fki_period_id->valuedouble,
strdup(d_franchisereferalincome_loan->valuestring),
strdup(d_franchisereferalincome_franchiseamount->valuestring),
strdup(d_franchisereferalincome_franchisoramount->valuestring),
strdup(d_franchisereferalincome_agentamount->valuestring),
strdup(dt_franchisereferalincome_disbursed->valuestring),
strdup(t_franchisereferalincome_comment->valuestring),
fki_franchiseoffice_id->valuedouble,
strdup(s_franchisereferalincome_remoteid->valuestring)
);
return franchisereferalincome_request_compound_local_var;
end:
if (obj_address_local_nonprim) {
address_request_free(obj_address_local_nonprim);
obj_address_local_nonprim = NULL;
}
return NULL;
}
| 40.466518 | 176 | 0.789233 | [
"model"
] |
9a7f4ccdeef23dfd538c4379c66aec4a45777deb | 11,059 | h | C | lib/bgfx/src/shader_spirv.h | RichardRanft/Torque6 | db6cd08f18f4917e0c6557b2766fb40d8e2bee39 | [
"MIT"
] | 312 | 2015-02-17T15:07:28.000Z | 2022-03-12T07:09:56.000Z | src/shader_spirv.h | PyryM/bgfx | 0f5f0eaed6c7d19b8f740bd4fd131b393a4418d4 | [
"BSD-2-Clause"
] | 23 | 2015-03-30T14:47:37.000Z | 2020-11-02T00:00:24.000Z | src/shader_spirv.h | PyryM/bgfx | 0f5f0eaed6c7d19b8f740bd4fd131b393a4418d4 | [
"BSD-2-Clause"
] | 73 | 2015-02-17T15:07:30.000Z | 2021-10-02T03:11:59.000Z | /*
* Copyright 2011-2016 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#ifndef BGFX_SHADER_SPIRV_H
#define BGFX_SHADER_SPIRV_H
#include <bx/readerwriter.h>
BX_ERROR_RESULT(BGFX_SHADER_SPIRV_INVALID_HEADER, BX_MAKEFOURCC('S', 'H', 0, 1) );
BX_ERROR_RESULT(BGFX_SHADER_SPIRV_INVALID_INSTRUCTION, BX_MAKEFOURCC('S', 'H', 0, 2) );
#define SPV_CHUNK_HEADER BX_MAKEFOURCC(0x03, 0x02, 0x23, 0x07)
namespace bgfx
{
// Reference: https://www.khronos.org/registry/spir-v/specs/1.0/SPIRV.html
struct SpvOpcode
{
enum Enum
{
Nop,
Undef,
SourceContinued,
Source,
SourceExtension,
Name,
MemberName,
String,
Line,
Invalid9,
Extension,
ExtInstImport,
ExtInst,
Invalid13,
MemoryModel,
EntryPoint,
ExecutionMode,
Capability,
Invalid18,
TypeVoid,
TypeBool,
TypeInt,
TypeFloat,
TypeVector,
TypeMatrix,
TypeImage,
TypeSampler,
TypeSampledImage,
TypeArray,
TypeRuntimeArray,
TypeStruct,
TypeOpaque,
TypePointer,
TypeFunction,
TypeEvent,
TypeDeviceEvent,
TypeReserveId,
TypeQueue,
TypePipe,
TypeForwardPointer,
Invalid40,
ConstantTrue,
ConstantFalse,
Constant,
ConstantComposite,
ConstantSampler,
ConstantNull,
Invalid47,
SpecConstantTrue,
SpecConstantFalse,
SpecConstant,
SpecConstantComposite,
SpecConstantOp,
Invalid53,
Function,
FunctionParameter,
FunctionEnd,
FunctionCall,
Invalid58,
Variable,
ImageTexelPointer,
Load,
Store,
CopyMemory,
CopyMemorySized,
AccessChain,
InBoundsAccessChain,
PtrAccessChain,
ArrayLength,
GenericPtrMemSemantics,
InBoundsPtrAccessChain,
Decorate,
MemberDecorate,
DecorationGroup,
GroupDecorate,
GroupMemberDecorate,
Invalid76,
VectorExtractDynamic,
VectorInsertDynamic,
VectorShuffle,
CompositeConstruct,
CompositeExtract,
CompositeInsert,
CopyObject,
Transpose,
Invalid85,
SampledImage,
ImageSampleImplicitLod,
ImageSampleExplicitLod,
ImageSampleDrefImplicitLod,
ImageSampleDrefExplicitLod,
ImageSampleProjImplicitLod,
ImageSampleProjExplicitLod,
ImageSampleProjDrefImplicitLod,
ImageSampleProjDrefExplicitLod,
ImageFetch,
ImageGather,
ImageDrefGather,
ImageRead,
ImageWrite,
Image,
ImageQueryFormat,
ImageQueryOrder,
ImageQuerySizeLod,
ImageQuerySize,
ImageQueryLod,
ImageQueryLevels,
ImageQuerySamples,
Invalid108,
ConvertFToU,
ConvertFToS,
ConvertSToF,
ConvertUToF,
UConvert,
SConvert,
FConvert,
QuantizeToF16,
ConvertPtrToU,
SatConvertSToU,
SatConvertUToS,
ConvertUToPtr,
PtrCastToGeneric,
GenericCastToPtr,
GenericCastToPtrExplicit,
Bitcast,
Invalid125,
SNegate,
FNegate,
IAdd,
FAdd,
ISub,
FSub,
IMul,
FMul,
UDiv,
SDiv,
FDiv,
UMod,
SRem,
SMod,
FRem,
FMod,
VectorTimesScalar,
MatrixTimesScalar,
VectorTimesMatrix,
MatrixTimesVector,
MatrixTimesMatrix,
OuterProduct,
Dot,
IAddCarry,
ISubBorrow,
UMulExtended,
SMulExtended,
Invalid153,
Any,
All,
IsNan,
IsInf,
IsFinite,
IsNormal,
SignBitSet,
LessOrGreater,
Ordered,
Unordered,
LogicalEqual,
LogicalNotEqual,
LogicalOr,
LogicalAnd,
LogicalNot,
Select,
IEqual,
INotEqual,
UGreaterThan,
SGreaterThan,
UGreaterThanEqual,
SGreaterThanEqual,
ULessThan,
SLessThan,
ULessThanEqual,
SLessThanEqual,
FOrdEqual,
FUnordEqual,
FOrdNotEqual,
FUnordNotEqual,
FOrdLessThan,
FUnordLessThan,
FOrdGreaterThan,
FUnordGreaterThan,
FOrdLessThanEqual,
FUnordLessThanEqual,
FOrdGreaterThanEqual,
FUnordGreaterThanEqual,
Invalid192,
Invalid193,
ShiftRightLogical,
ShiftRightArithmetic,
ShiftLeftLogical,
BitwiseOr,
BitwiseXor,
BitwiseAnd,
Not,
BitFieldInsert,
BitFieldSExtract,
BitFieldUExtract,
BitReverse,
BitCount,
Invalid206,
DPdx,
DPdy,
Fwidth,
DPdxFine,
DPdyFine,
FwidthFine,
DPdxCoarse,
DPdyCoarse,
FwidthCoarse,
Invalid216,
Invalid217,
EmitVertex,
EndPrimitive,
EmitStreamVertex,
EndStreamPrimitive,
Invalid222,
Invalid223,
ControlBarrier,
MemoryBarrier,
Invalid226,
AtomicLoad,
AtomicStore,
AtomicExchange,
AtomicCompareExchange,
AtomicCompareExchangeWeak,
AtomicIIncrement,
AtomicIDecrement,
AtomicIAdd,
AtomicISub,
AtomicSMin,
AtomicUMin,
AtomicSMax,
AtomicUMax,
AtomicAnd,
AtomicOr,
AtomicXor,
Invalid243,
Invalid244,
Phi,
LoopMerge,
SelectionMerge,
Label,
Branch,
BranchConditional,
Switch,
Kill,
Return,
ReturnValue,
Unreachable,
LifetimeStart,
LifetimeStop,
Invalid258,
GroupAsyncCopy,
GroupWaitEvents,
GroupAll,
GroupAny,
GroupBroadcast,
GroupIAdd,
GroupFAdd,
GroupFMin,
GroupUMin,
GroupSMin,
GroupFMax,
GroupUMax,
GroupSMax,
Invalid272,
Invalid273,
ReadPipe,
WritePipe,
ReservedReadPipe,
ReservedWritePipe,
ReserveReadPipePackets,
ReserveWritePipePackets,
CommitReadPipe,
CommitWritePipe,
IsValidReserveId,
GetNumPipePackets,
GetMaxPipePackets,
GroupReserveReadPipePackets,
GroupReserveWritePipePackets,
GroupCommitReadPipe,
GroupCommitWritePipe,
Invalid289,
Invalid290,
EnqueueMarker,
EnqueueKernel,
GetKernelNDrangeSubGroupCount,
GetKernelNDrangeMaxSubGroupSize,
GetKernelWorkGroupSize,
GetKernelPreferredWorkGroupSizeMultiple,
RetainEvent,
ReleaseEvent,
CreateUserEvent,
IsValidEvent,
SetUserEventStatus,
CaptureEventProfilingInfo,
GetDefaultQueue,
BuildNDRange,
ImageSparseSampleImplicitLod,
ImageSparseSampleExplicitLod,
ImageSparseSampleDrefImplicitLod,
ImageSparseSampleDrefExplicitLod,
ImageSparseSampleProjImplicitLod,
ImageSparseSampleProjExplicitLod,
ImageSparseSampleProjDrefImplicitLod,
ImageSparseSampleProjDrefExplicitLod,
ImageSparseFetch,
ImageSparseGather,
ImageSparseDrefGather,
ImageSparseTexelsResident,
NoLine,
AtomicFlagTestAndSet,
AtomicFlagClear,
ImageSparseRead,
Count
};
};
const char* getName(SpvOpcode::Enum _opcode);
struct SpvBuiltin
{
enum Enum
{
Position,
PointSize,
ClipDistance,
CullDistance,
VertexId,
InstanceId,
PrimitiveId,
InvocationId,
Layer,
ViewportIndex,
TessLevelOuter,
TessLevelInner,
TessCoord,
PatchVertices,
FragCoord,
PointCoord,
FrontFacing,
SampleId,
SamplePosition,
SampleMask,
FragDepth,
HelperInvocation,
NumWorkgroups,
WorkgroupSize,
WorkgroupId,
LocalInvocationId,
GlobalInvocationId,
LocalInvocationIndex,
WorkDim,
GlobalSize,
EnqueuedWorkgroupSize,
GlobalOffset,
GlobalLinearId,
SubgroupSize,
SubgroupMaxSize,
NumSubgroups,
NumEnqueuedSubgroups,
SubgroupId,
SubgroupLocalInvocationId,
VertexIndex,
InstanceIndex,
Count
};
};
const char* getName(SpvBuiltin::Enum _enum);
struct SpvExecutionModel
{
enum Enum
{
Vertex,
TessellationControl,
TessellationEvaluation,
Geometry,
Fragment,
GLCompute,
Kernel,
Count
};
};
struct SpvAddressingModel
{
enum Enum
{
Logical,
Physical32,
Physical64,
Count
};
};
struct SpvMemoryModel
{
enum Enum
{
Simple,
GLSL450,
OpenCL,
Count
};
};
struct SpvStorageClass
{
enum Enum
{
UniformConstant,
Input,
Uniform,
Output,
Workgroup,
CrossWorkgroup,
Private,
Function,
Generic,
PushConstant,
AtomicCounter,
Image,
Count
};
};
const char* getName(SpvStorageClass::Enum _enum);
struct SpvResourceDim
{
enum Enum
{
Texture1D,
Texture2D,
Texture3D,
TextureCube,
TextureRect,
Buffer,
SubpassData,
};
};
struct SpvDecoration
{
enum Enum
{
RelaxedPrecision,
SpecId,
Block,
BufferBlock,
RowMajor,
ColMajor,
ArrayStride,
MatrixStride,
GLSLShared,
GLSLPacked,
CPacked,
BuiltIn,
Unknown12,
NoPerspective,
Flat,
Patch,
Centroid,
Sample,
Invariant,
Restrict,
Aliased,
Volatile,
Constant,
Coherent,
NonWritable,
NonReadable,
Uniform,
Unknown27,
SaturatedConversion,
Stream,
Location,
Component,
Index,
Binding,
DescriptorSet,
Offset,
XfbBuffer,
XfbStride,
FuncParamAttr,
FPRoundingMode,
FPFastMathMode,
LinkageAttributes,
NoContraction,
InputAttachmentIndex,
Alignment,
Count
};
};
const char* getName(SpvDecoration::Enum _enum);
struct SpvOperand
{
SpvOperand() { /* not pod */ }
enum Enum
{
AccessQualifier,
AddressingModel,
Base,
Capability,
Component,
ComponentType,
Composite,
Condition,
Coordinate,
Decoration,
Dim,
Dref,
ElementType,
ExecutionModel,
Function,
FunctionControl,
Id,
IdRep,
ImageFormat,
ImageOperands,
LinkageType,
LiteralNumber,
LiteralRep,
LiteralString,
Matrix,
MemoryAccess,
MemoryModel,
Object,
Pointer,
SampledType,
SampledImage,
SamplerAddressingMode,
SamplerFilterMode,
Scalar,
SourceLanguage,
StorageClass,
StructureType,
Vector,
Count
};
Enum type;
uint32_t data;
stl::string literalString;
};
struct SpvInstruction
{
SpvInstruction() { /* not pod */ }
SpvOpcode::Enum opcode;
uint16_t length;
uint16_t numOperands;
uint32_t type;
uint32_t result;
bool hasType;
bool hasResult;
SpvOperand operand[8];
};
int32_t read(bx::ReaderI* _reader, SpvInstruction& _instruction, bx::Error* _err);
int32_t write(bx::WriterI* _writer, const SpvInstruction& _instruction, bx::Error* _err);
int32_t toString(char* _out, int32_t _size, const SpvInstruction& _instruction);
struct SpvShader
{
SpvShader() { /* not pod */ }
stl::vector<uint8_t> byteCode;
};
int32_t read(bx::ReaderSeekerI* _reader, SpvShader& _shader, bx::Error* _err);
int32_t write(bx::WriterI* _writer, const SpvShader& _shader, bx::Error* _err);
typedef bool (*SpvParseFn)(uint32_t _offset, const SpvInstruction& _instruction, void* _userData);
void parse(const SpvShader& _src, SpvParseFn _fn, void* _userData, bx::Error* _err = NULL);
typedef void (*SpvFilterFn)(SpvInstruction& _instruction, void* _userData);
void filter(SpvShader& _dst, const SpvShader& _src, SpvFilterFn _fn, void* _userData, bx::Error* _err = NULL);
struct SpirV
{
SpirV() { /* not pod */ }
struct Header
{
uint32_t magic;
uint32_t version;
uint32_t generator;
uint32_t bound;
uint32_t schema;
};
Header header;
SpvShader shader;
};
int32_t read(bx::ReaderSeekerI* _reader, SpirV& _spirv, bx::Error* _err);
int32_t write(bx::WriterSeekerI* _writer, const SpirV& _spirv, bx::Error* _err);
} // namespace bgfx
#endif // BGFX_SHADER_SPIRV_H
| 17.013846 | 111 | 0.701239 | [
"geometry",
"object",
"vector"
] |
9a817ca9811275df4449095d00d5dab8abea8062 | 5,721 | c | C | src/main.c | lbia/MinecraftClone | 34210ae98eeb34544e5503409cadd2b0004d92b9 | [
"Unlicense"
] | null | null | null | src/main.c | lbia/MinecraftClone | 34210ae98eeb34544e5503409cadd2b0004d92b9 | [
"Unlicense"
] | null | null | null | src/main.c | lbia/MinecraftClone | 34210ae98eeb34544e5503409cadd2b0004d92b9 | [
"Unlicense"
] | null | null | null | #include "GL/glew.h"
#include "GLFW/glfw3.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "camera.h"
#include "cube.h"
#include "gameState.h"
#include "global.h"
#include "program.h"
#include "renderer.h"
#include "window.h"
#include "cglm/cglm.h"
int main() {
GameState *state = malloc(sizeof(GameState));
GLFWwindow *window;
window = initializeWindow("Mine", state, true);
float dataVertexBuffer[] = QUADRATO;
unsigned int dataIndici[] = INDICES_QUADRATO;
VertexArray vaGui;
initializeVertexArray(&vaGui);
VertexBuffer vbGui;
initializeVertexBuffer(&vbGui);
sendDataVertexBuffer(&vbGui, dataVertexBuffer, 6 * 4 * sizeof(float), true);
VertexBufferLayout layoutGui;
initializeVertexBufferLayout(&layoutGui);
pushElementToVertexBufferLayout(&layoutGui, GL_FLOAT, 3, GL_FALSE);
pushElementToVertexBufferLayout(&layoutGui, GL_FLOAT, 2, GL_FALSE);
pushElementToVertexBufferLayout(&layoutGui, GL_FLOAT, 1, GL_FALSE);
addBufferToVertexArray(&vaGui, &vbGui, &layoutGui);
IndexBuffer ibGui;
initializeIndexBuffer(&ibGui);
sendDataIndexBuffer(&ibGui, dataIndici, SIZE_INDICI_QUADRATO, false);
VertexArray va;
initializeVertexArray(&va);
VertexBuffer vb;
initializeVertexBuffer(&vb);
// sendDataVertexBuffer(&vb, cubo, 6 * 6 * 4 * sizeof(float), true);
VertexBufferLayout layout;
initializeVertexBufferLayout(&layout);
pushElementToVertexBufferLayout(&layout, GL_FLOAT, 3, GL_FALSE);
pushElementToVertexBufferLayout(&layout, GL_FLOAT, 2, GL_FALSE);
pushElementToVertexBufferLayout(&layout, GL_FLOAT, 1, GL_FALSE);
// normals
pushElementToVertexBufferLayout(&layout, GL_FLOAT, 3, GL_FALSE);
addBufferToVertexArray(&va, &vb, &layout);
IndexBuffer ib;
initializeIndexBuffer(&ib);
// sendDataIndexBuffer(&ib, indicesCubo, SIZE_INDICI_CUBO, true);
Shader shader;
// initializeShaderOnePath(&shader, "res/shaders/basic.shader");
initializeShaderTwoPaths(&shader, "res/shaders/blockVertex.shader",
"res/shaders/blockFragment.shader");
Shader shaderGui;
initializeShaderTwoPaths(&shaderGui, "res/shaders/basicVertex.shader",
"res/shaders/basicFragment.shader");
Program worldProgram;
Program guiProgram;
guiProgram.vb = &vbGui;
guiProgram.va = &vaGui;
guiProgram.ib = &ibGui;
guiProgram.shader = &shaderGui;
worldProgram.vb = &vb;
worldProgram.va = &va;
worldProgram.ib = &ib;
worldProgram.shader = &shader;
mat4 proj, view, model;
bindShader(&shader);
setShaderUniform1i(&shader, "u_BlockTop", 0);
setShaderUniform1i(&shader, "u_BlockSide", 1);
setShaderUniform1i(&shader, "u_BlockBottom", 2);
float colorBase[4] = {1, 1, 1, 1};
// setShaderUniformVec4(&shader, "u_TexColor", colorBase);
float lightBase[3] = {1, 1, 1};
setShaderUniformVec3(&shader, "u_LightColor", lightBase);
float lightPosition[3] = {0, 1000, 0};
setShaderUniformVec3(&shader, "u_LightPosition", lightPosition);
glm_perspective(glm_rad(50), (float)WIDTH / (float)HEIGHT, 0.1f,
VIEW_BLOCKS * 2, proj);
setShaderUniformMat4f(&shader, "u_Proj", &proj);
glm_mat4_identity(model);
setShaderUniformMat4f(&shader, "u_Model", &model);
bindShader(&shaderGui);
setShaderUniform1i(&shaderGui, "u_MouseBianco", 0);
glm_ortho(-SCALA_ORTHO, SCALA_ORTHO, -SCALA_ORTHO, SCALA_ORTHO, -1, 1,
proj);
setShaderUniformMat4f(&shaderGui, "u_Proj", &proj);
setShaderUniformMat4f(&shaderGui, "u_Model", &model);
bindVertexArray(&va);
bindIndexBuffer(&ib);
initGameState(state);
state->programWorld = &worldProgram;
Player *player = state->player;
float time = 0;
float timeUpdate = 0;
int frameRender = 0;
int frameUpdate = 0;
float delta = 0.0f;
float previousFrame = glfwGetTime();
unsigned int contaFrame = 0;
unsigned int printFrame = 10;
printf("\n");
while (!glfwWindowShouldClose(window)) {
processInput(window);
float currentFrame = glfwGetTime();
delta = currentFrame - previousFrame;
previousFrame = currentFrame;
time += delta;
frameRender++;
if (time >= 1.0f) {
contaFrame++;
if (contaFrame >= printFrame) {
printf("FPS: %d\n", frameRender);
contaFrame = 0;
}
// printf("%d\n", frameUpdate);
time = 0;
frameRender = 0;
frameUpdate = 0;
}
timeUpdate += delta;
// if (timeUpdate >= MAX_TIME_UPDATE){
if (timeUpdate >= 0) {
timeUpdate = 0;
frameUpdate++;
state->deltaTime = currentFrame - state->lastFrame;
state->lastFrame = currentFrame;
updateGameState(state);
}
// updateGameState(state);
clear();
bindShader(&shader);
getCameraViewMatrix(player->camera, player->shift, view);
setShaderUniformMat4f(&shader, "u_View", &view);
drawWordlChunkView(&worldProgram, state);
// drawWordlChunk(&va, &vb, &ib, &shader, state);
drawGui(&guiProgram, state);
glfwSwapBuffers(window);
glfwPollEvents();
}
while (state->threadEsecuzione)
;
destroyGameState(state);
free(state);
destroyVertexBuffer(&vb);
destroyIndexBuffer(&ib);
destroyVertexBufferLayout(&layout);
destroyVertexArray(&va);
destoyShader(&shader);
destoyShader(&shaderGui);
glfwTerminate();
return 0;
}
| 29.188776 | 80 | 0.646565 | [
"model"
] |
9a88f547a7225c716bc87de462c2621b23bede5c | 4,735 | h | C | Pods/Headers/Public/Facebook-iOS-SDK/FBSDKShareKit/FBSDKGameRequestContent.h | BookSelves/Bookselves | 8ff46722f010df6fe05e7b13cbac4dae45aea87c | [
"MIT"
] | 3 | 2015-04-29T01:16:55.000Z | 2018-01-22T03:10:33.000Z | Pods/Headers/Public/Facebook-iOS-SDK/FBSDKShareKit/FBSDKGameRequestContent.h | BookSelves/Bookselves | 8ff46722f010df6fe05e7b13cbac4dae45aea87c | [
"MIT"
] | null | null | null | Pods/Headers/Public/Facebook-iOS-SDK/FBSDKShareKit/FBSDKGameRequestContent.h | BookSelves/Bookselves | 8ff46722f010df6fe05e7b13cbac4dae45aea87c | [
"MIT"
] | 1 | 2018-08-12T09:38:27.000Z | 2018-08-12T09:38:27.000Z | // Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <FBSDKCoreKit/FBSDKCopying.h>
/*!
@typedef NS_ENUM(NSUInteger, FBSDKGameRequestActionType)
@abstract Additional context about the nature of the request.
*/
typedef NS_ENUM(NSUInteger, FBSDKGameRequestActionType)
{
/*! No action type */
FBSDKGameRequestActionTypeNone = 0,
/*! Send action type: The user is sending an object to the friends. */
FBSDKGameRequestActionTypeSend,
/*! Ask For action type: The user is asking for an object from friends. */
FBSDKGameRequestActionTypeAskFor,
/*! Turn action type: It is the turn of the friends to play against the user in a match. (no object) */
FBSDKGameRequestActionTypeTurn,
};
/*!
@typedef NS_ENUM(NSUInteger, FBSDKGameRequestFilters)
@abstract Filter for who can be displayed in the multi-friend selector.
*/
typedef NS_ENUM(NSUInteger, FBSDKGameRequestFilter)
{
/*! No filter, all friends can be displayed. */
FBSDKGameRequestFilterNone = 0,
/*! Friends using the app can be displayed. */
FBSDKGameRequestFilterAppUsers,
/*! Friends not using the app can be displayed. */
FBSDKGameRequestFilterAppNonUsers,
};
/*!
@abstract A model for a game request.
*/
@interface FBSDKGameRequestContent : NSObject <FBSDKCopying, NSSecureCoding>
/*!
@abstract Used when defining additional context about the nature of the request.
@discussion The parameter 'objectID' is required if the action type is either
'FBSDKGameRequestSendActionType' or 'FBSDKGameRequestAskForActionType'.
@seealso objectID
*/
@property (nonatomic, assign) FBSDKGameRequestActionType actionType;
/*!
@abstract Compares the receiver to another game request content.
@param content The other content
@return YES if the receiver's values are equal to the other content's values; otherwise NO
*/
- (BOOL)isEqualToGameRequestContent:(FBSDKGameRequestContent *)content;
/*!
@abstract Additional freeform data you may pass for tracking. This will be stored as part of
the request objects created. The maximum length is 255 characters.
*/
@property (nonatomic, copy) NSString *data;
/*!
@abstract This controls the set of friends someone sees if a multi-friend selector is shown.
It is FBSDKGameRequestNoFilter by default, meaning that all friends can be shown.
If specify as FBSDKGameRequestAppUsersFilter, only friends who use the app will be shown.
On the other hands, use FBSDKGameRequestAppNonUsersFilter to filter only friends who do not use the app.
@discussion The parameter name is preserved to be consistent with the counter part on desktop.
*/
@property (nonatomic, assign) FBSDKGameRequestFilter filters;
/*!
@abstract A plain-text message to be sent as part of the request. This text will surface in the App Center view
of the request, but not on the notification jewel. Required parameter.
*/
@property (nonatomic, copy) NSString *message;
/*!
@abstract The Open Graph object ID of the object being sent.
@seealso actionType
*/
@property (nonatomic, copy) NSString *objectID;
/*!
@abstract An array of user IDs, usernames or invite tokens (NSString) of people to send request.
@discussion These may or may not be a friend of the sender. If this is specified by the app,
the sender will not have a choice of recipients. If not, the sender will see a multi-friend selector
*/
@property (nonatomic, copy) NSArray *to;
/*!
@abstract An array of user IDs that will be included in the dialog as the first suggested friends.
Cannot be used together with filters.
*/
@property (nonatomic, copy) NSArray *suggestions;
/*!
@abstract The title for the dialog.
*/
@property (nonatomic, copy) NSString *title;
@end
| 39.789916 | 112 | 0.766843 | [
"object",
"model"
] |
9a946e843f6a018d40010bd0204e8d48c5e8dd1b | 3,380 | h | C | Gem/Code/Source/RHI/InputAssemblyExampleComponent.h | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | 15 | 2021-07-07T02:16:06.000Z | 2022-03-22T07:39:06.000Z | Gem/Code/Source/RHI/InputAssemblyExampleComponent.h | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | 66 | 2021-07-07T00:01:05.000Z | 2022-03-28T06:37:41.000Z | Gem/Code/Source/RHI/InputAssemblyExampleComponent.h | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | 13 | 2021-07-06T18:21:33.000Z | 2022-01-04T18:29:18.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <Atom/RHI/DrawItem.h>
#include <Atom/RHI/ScopeProducer.h>
#include <Atom/RHI/RHISystemInterface.h>
#include <Atom/RPI.Public/Shader/Shader.h>
#include <Atom/RPI.Public/Shader/ShaderResourceGroup.h>
#include <AzCore/Component/Component.h>
#include <AzCore/Component/TickBus.h>
#include <RHI/BasicRHIComponent.h>
namespace AtomSampleViewer
{
//! This samples shows how to handle vertex buffer generation on a compute shader and how
//! to properly declare shader inputs.
//! There's 2 scopes in this sample, one runs a compute shader that is in charge of generating and animating the
//! vertices of a 2D hexagon. The second scope is in charge of drawing the previously generated hexagon vertex buffer.
class InputAssemblyExampleComponent final
: public BasicRHIComponent
, public AZ::TickBus::Handler
{
public:
AZ_COMPONENT(InputAssemblyExampleComponent, "{1F061564-DB4A-4B68-B361-0B427B3CA5B5}", AZ::Component);
AZ_DISABLE_COPY(InputAssemblyExampleComponent);
static void Reflect(AZ::ReflectContext* context);
InputAssemblyExampleComponent();
~InputAssemblyExampleComponent() = default;
protected:
// We have only float4 vertex positions as data.
using BufferData = AZStd::array<AZStd::array<float, 4>, 6>;
int m_numThreadsX = 1;
int m_numThreadsY = 1;
int m_numThreadsZ = 1;
// AZ::Component
void Activate() override;
void Deactivate() override;
void FrameBeginInternal(AZ::RHI::FrameGraphBuilder& frameGraphBuilder) override;
// TickBus::Handler
void OnTick(float deltaTime, AZ::ScriptTimePoint time) override;
void CreateInputAssemblyLayout();
void CreateBuffers();
void LoadComputeShader();
void LoadRasterShader();
void CreateComputeScope();
void CreateRasterScope();
// -------------------------------------------------
// Input Assembly buffer and its Streams/Index Views
// -------------------------------------------------
AZ::RHI::StreamBufferView m_streamBufferView[2];
AZ::RHI::InputStreamLayout m_inputStreamLayout;
AZ::RHI::Ptr<AZ::RHI::BufferPool> m_inputAssemblyBufferPool;
AZ::RHI::Ptr<AZ::RHI::Buffer> m_inputAssemblyBuffer;
// ----------------------
// Pipeline state and SRG
// ----------------------
// Dispatch pipeline
AZ::RHI::ConstPtr<AZ::RHI::PipelineState> m_dispatchPipelineState;
AZ::Data::Instance<AZ::RPI::ShaderResourceGroup> m_dispatchSRG[2];
AZ::RHI::ShaderInputConstantIndex m_dispatchTimeConstantIndex;
AZ::RHI::ShaderInputBufferIndex m_dispatchIABufferIndex;
// Draw pipeline
AZ::RHI::ConstPtr<AZ::RHI::PipelineState> m_drawPipelineState;
AZ::RHI::ShaderInputConstantIndex m_drawMatrixIndex;
AZ::RHI::ShaderInputConstantIndex m_drawColorIndex;
AZ::Data::Instance<AZ::RPI::ShaderResourceGroup> m_drawSRG[2];
// This is used to animate the hexagon.
float m_time = 0.0f;
};
}
| 35.957447 | 122 | 0.654734 | [
"3d"
] |
9a9944f9529b6b59a45a785f9972d67f6178ebfd | 16,554 | h | C | IO/Parallel/vtkMultiBlockPLOT3DReader.h | michaelchanwahyan/vtk-8.1.2 | 243225b750443f76dcb119c1bb8e72d41e505bc0 | [
"BSD-3-Clause"
] | 2 | 2017-12-08T07:50:51.000Z | 2018-07-22T19:12:56.000Z | IO/Parallel/vtkMultiBlockPLOT3DReader.h | michaelchanwahyan/vtk-8.1.2 | 243225b750443f76dcb119c1bb8e72d41e505bc0 | [
"BSD-3-Clause"
] | 1 | 2019-06-03T17:04:59.000Z | 2019-06-05T15:13:28.000Z | IO/Parallel/vtkMultiBlockPLOT3DReader.h | michaelchanwahyan/vtk-8.1.2 | 243225b750443f76dcb119c1bb8e72d41e505bc0 | [
"BSD-3-Clause"
] | 1 | 2020-07-20T06:43:49.000Z | 2020-07-20T06:43:49.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkMultiBlockPLOT3DReader.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* @class vtkMultiBlockPLOT3DReader
* @brief read PLOT3D data files
*
* vtkMultiBlockPLOT3DReader is a reader object that reads PLOT3D formatted
* files and generates structured grid(s) on output. PLOT3D is a computer
* graphics program designed to visualize the grids and solutions of
* computational fluid dynamics. This reader also supports the variant
* of the PLOT3D format used by NASA's OVERFLOW CFD software, including
* full support for all Q variables. Please see the "PLOT3D User's Manual"
* available from NASA Ames Research Center, Moffett Field CA.
*
* PLOT3D files consist of a grid file (also known as XYZ file), an
* optional solution file (also known as a Q file), and an optional function
* file that contains user created data (currently unsupported). The Q file
* contains solution information as follows: the four parameters free stream
* mach number (Fsmach), angle of attack (Alpha), Reynolds number (Re), and
* total integration time (Time). This information is stored in an array
* called Properties in the FieldData of each output (tuple 0: fsmach, tuple 1:
* alpha, tuple 2: re, tuple 3: time). In addition, the solution file contains
* the flow density (scalar), flow momentum (vector), and flow energy (scalar).
*
* Note that this reader does not support time series data which is usually
* stored as a series of Q and optionally XYZ files. If you want to read such
* a file series, use vtkPlot3DMetaReader.
*
* The reader can generate additional scalars and vectors (or "functions")
* from this information. To use vtkMultiBlockPLOT3DReader, you must specify the
* particular function number for the scalar and vector you want to visualize.
* This implementation of the reader provides the following functions. The
* scalar functions are:
* -1 - don't read or compute any scalars
* 100 - density
* 110 - pressure
* 111 - pressure coefficient (requires Overflow file with Gamma)
* 112 - mach number (requires Overflow file with Gamma)
* 113 - sounds speed (requires Overflow file with Gamma)
* 120 - temperature
* 130 - enthalpy
* 140 - internal energy
* 144 - kinetic energy
* 153 - velocity magnitude
* 163 - stagnation energy
* 170 - entropy
* 184 - swirl
* 211 - vorticity magnitude
*
* The vector functions are:
* -1 - don't read or compute any vectors
* 200 - velocity
* 201 - vorticity
* 202 - momentum
* 210 - pressure gradient.
* 212 - strain rate
*
* (Other functions are described in the PLOT3D spec, but only those listed are
* implemented here.) Note that by default, this reader creates the density
* scalar (100), stagnation energy (163) and momentum vector (202) as output.
* (These are just read in from the solution file.) Please note that the validity
* of computation is a function of this class's gas constants (R, Gamma) and the
* equations used. They may not be suitable for your computational domain.
*
* Additionally, you can read other data and associate it as a vtkDataArray
* into the output's point attribute data. Use the method AddFunction()
* to list all the functions that you'd like to read. AddFunction() accepts
* an integer parameter that defines the function number.
*
* @sa
* vtkMultiBlockDataSet vtkStructuredGrid vtkPlot3DMetaReader
*/
#ifndef vtkMultiBlockPLOT3DReader_h
#define vtkMultiBlockPLOT3DReader_h
#include <vector> // For holding function-names
#include "vtkIOParallelModule.h" // For export macro
#include "vtkMultiBlockDataSetAlgorithm.h"
class vtkDataArray;
class vtkDataSetAttributes;
class vtkIntArray;
class vtkMultiBlockPLOT3DReaderRecord;
class vtkMultiProcessController;
class vtkStructuredGrid;
class vtkUnsignedCharArray;
struct vtkMultiBlockPLOT3DReaderInternals;
namespace Functors
{
class ComputeFunctor;
class ComputeTemperatureFunctor;
class ComputePressureFunctor;
class ComputePressureCoefficientFunctor;
class ComputeMachNumberFunctor;
class ComputeSoundSpeedFunctor;
class ComputeEnthalpyFunctor;
class ComputeKinecticEnergyFunctor;
class ComputeVelocityMagnitudeFunctor;
class ComputeEntropyFunctor;
class ComputeSwirlFunctor;
class ComputeVelocityFunctor;
class ComputeVorticityMagnitudeFunctor;
class ComputePressureGradientFunctor;
class ComputeVorticityFunctor;
class ComputeStrainRateFunctor;
}
class VTKIOPARALLEL_EXPORT vtkMultiBlockPLOT3DReader : public vtkMultiBlockDataSetAlgorithm
{
friend class Functors::ComputeFunctor;
friend class Functors::ComputeTemperatureFunctor;
friend class Functors::ComputePressureFunctor;
friend class Functors::ComputePressureCoefficientFunctor;
friend class Functors::ComputeMachNumberFunctor;
friend class Functors::ComputeSoundSpeedFunctor;
friend class Functors::ComputeEnthalpyFunctor;
friend class Functors::ComputeKinecticEnergyFunctor;
friend class Functors::ComputeVelocityMagnitudeFunctor;
friend class Functors::ComputeEntropyFunctor;
friend class Functors::ComputeSwirlFunctor;
friend class Functors::ComputeVelocityFunctor;
friend class Functors::ComputeVorticityMagnitudeFunctor;
friend class Functors::ComputePressureGradientFunctor;
friend class Functors::ComputeVorticityFunctor;
friend class Functors::ComputeStrainRateFunctor;
public:
static vtkMultiBlockPLOT3DReader *New();
vtkTypeMacro(vtkMultiBlockPLOT3DReader,vtkMultiBlockDataSetAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent) override;
//@{
/**
* Set/Get the PLOT3D geometry filename.
*/
void SetFileName(const char* name) { this->SetXYZFileName(name); }
const char* GetFileName() { return this->GetXYZFileName(); }
virtual void SetXYZFileName( const char* );
vtkGetStringMacro(XYZFileName);
//@}
//@{
/**
* Set/Get the PLOT3D solution filename.
*/
vtkSetStringMacro(QFileName);
vtkGetStringMacro(QFileName);
//@}
//@{
/**
* Set/Get the PLOT3D function filename.
*/
vtkSetStringMacro(FunctionFileName);
vtkGetStringMacro(FunctionFileName);
//@}
//@{
/**
* When this option is turned on, the reader will try to figure
* out the values of various options such as byte order, byte
* count etc. automatically. This options works only for binary
* files. When it is turned on, the reader should be able to read
* most Plot3D files automatically. The default is OFF for backwards
* compatibility reasons. For binary files, it is strongly recommended
* that you turn on AutoDetectFormat and leave the other file format
* related options untouched.
*/
vtkSetMacro(AutoDetectFormat, int);
vtkGetMacro(AutoDetectFormat, int);
vtkBooleanMacro(AutoDetectFormat, int);
//@}
//@{
/**
* Is the file to be read written in binary format (as opposed
* to ascii).
*/
vtkSetMacro(BinaryFile, int);
vtkGetMacro(BinaryFile, int);
vtkBooleanMacro(BinaryFile, int);
//@}
//@{
/**
* Does the file to be read contain information about number of
* grids. In some PLOT3D files, the first value contains the number
* of grids (even if there is only 1). If reading such a file,
* set this to true.
*/
vtkSetMacro(MultiGrid, int);
vtkGetMacro(MultiGrid, int);
vtkBooleanMacro(MultiGrid, int);
//@}
//@{
/**
* Were the arrays written with leading and trailing byte counts ?
* Usually, files written by a fortran program will contain these
* byte counts whereas the ones written by C/C++ won't.
*/
vtkSetMacro(HasByteCount, int);
vtkGetMacro(HasByteCount, int);
vtkBooleanMacro(HasByteCount, int);
//@}
//@{
/**
* Is there iblanking (point visibility) information in the file.
* If there is iblanking arrays, these will be read and assigned
* to the PointVisibility array of the output.
*/
vtkSetMacro(IBlanking, int);
vtkGetMacro(IBlanking, int);
vtkBooleanMacro(IBlanking, int);
//@}
//@{
/**
* If only two-dimensional data was written to the file,
* turn this on.
*/
vtkSetMacro(TwoDimensionalGeometry, int);
vtkGetMacro(TwoDimensionalGeometry, int);
vtkBooleanMacro(TwoDimensionalGeometry, int);
//@}
//@{
/**
* Is this file in double precision or single precision.
* This only matters for binary files.
* Default is single.
*/
vtkSetMacro(DoublePrecision, int);
vtkGetMacro(DoublePrecision, int);
vtkBooleanMacro(DoublePrecision, int);
//@}
//@{
/**
* Try to read a binary file even if the file length seems to be
* inconsistent with the header information. Use this with caution,
* if the file length is not the same as calculated from the header.
* either the file is corrupt or the settings are wrong.
*/
vtkSetMacro(ForceRead, int);
vtkGetMacro(ForceRead, int);
vtkBooleanMacro(ForceRead, int);
//@}
//@{
/**
* Set the byte order of the file (remember, more Unix workstations
* write big endian whereas PCs write little endian). Default is
* big endian (since most older PLOT3D files were written by
* workstations).
*/
void SetByteOrderToBigEndian();
void SetByteOrderToLittleEndian();
vtkSetMacro(ByteOrder, int);
vtkGetMacro(ByteOrder, int);
const char *GetByteOrderAsString();
//@}
//@{
/**
* Set/Get the gas constant. Default is 1.0.
*/
vtkSetMacro(R,double);
vtkGetMacro(R,double);
//@}
//@{
/**
* Set/Get the ratio of specific heats. Default is 1.4.
*/
vtkSetMacro(Gamma,double);
vtkGetMacro(Gamma,double);
//@}
//@{
/**
* When set to true (default), the reader will preserve intermediate computed
* quantities that were not explicitly requested e.g. if `VelocityMagnitude` is
* enabled, but not `Velocity`, the reader still needs to compute `Velocity`.
* If `PreserveIntermediateFunctions` if false, then the output will not have
* `Velocity` array, only the requested `VelocityMagnitude`. This is useful to
* avoid using up memory for arrays that are not relevant for the analysis.
*/
vtkSetMacro(PreserveIntermediateFunctions, bool);
vtkGetMacro(PreserveIntermediateFunctions, bool);
vtkBooleanMacro(PreserveIntermediateFunctions, bool);
//@{
/**
* Specify the scalar function to extract. If ==(-1), then no scalar
* function is extracted.
*/
void SetScalarFunctionNumber(int num);
vtkGetMacro(ScalarFunctionNumber,int);
//@}
//@{
/**
* Specify the vector function to extract. If ==(-1), then no vector
* function is extracted.
*/
void SetVectorFunctionNumber(int num);
vtkGetMacro(VectorFunctionNumber,int);
//@}
//@{
/**
* Specify additional functions to read. These are placed into the
* point data as data arrays. Later on they can be used by labeling
* them as scalars, etc.
*/
void AddFunction(int functionNumber);
void RemoveFunction(int);
void RemoveAllFunctions();
//@}
/**
* Return 1 if the reader can read the given file name. Only meaningful
* for binary files.
*/
virtual int CanReadBinaryFile(const char* fname);
//@{
/**
* Set/Get the communicator object (we'll use global World controller
* if you don't set a different one).
*/
void SetController(vtkMultiProcessController *c);
vtkGetObjectMacro(Controller, vtkMultiProcessController);
//@}
void AddFunctionName(const std::string &name) {FunctionNames.push_back(name);}
enum
{
FILE_BIG_ENDIAN=0,
FILE_LITTLE_ENDIAN=1
};
protected:
vtkMultiBlockPLOT3DReader();
~vtkMultiBlockPLOT3DReader() override;
vtkDataArray* CreateFloatArray();
int CheckFile(FILE*& fp, const char* fname);
int CheckGeometryFile(FILE*& xyzFp);
int CheckSolutionFile(FILE*& qFp);
int CheckFunctionFile(FILE*& fFp);
int GetByteCountSize();
int SkipByteCount (FILE* fp);
int ReadIntBlock (FILE* fp, int n, int* block);
vtkIdType ReadValues(
FILE* fp,
int n,
vtkDataArray* scalar);
virtual int ReadIntScalar(
void* vfp,
int extent[6], int wextent[6],
vtkDataArray* scalar, vtkTypeUInt64 offset,
const vtkMultiBlockPLOT3DReaderRecord& currentRecord);
virtual int ReadScalar(
void* vfp,
int extent[6], int wextent[6],
vtkDataArray* scalar, vtkTypeUInt64 offset,
const vtkMultiBlockPLOT3DReaderRecord& currentRecord);
virtual int ReadVector(
void* vfp,
int extent[6], int wextent[6],
int numDims, vtkDataArray* vector, vtkTypeUInt64 offset,
const vtkMultiBlockPLOT3DReaderRecord& currentRecord);
virtual int OpenFileForDataRead(void*& fp, const char* fname);
virtual void CloseFile(void* fp);
int GetNumberOfBlocksInternal(FILE* xyzFp, int allocate);
int ReadGeometryHeader(FILE* fp);
int ReadQHeader(FILE* fp, bool checkGrid, int& nq, int& nqc, int& overflow);
int ReadFunctionHeader(FILE* fp, int* nFunctions);
void CalculateFileSize(FILE* fp);
int AutoDetectionCheck(FILE* fp);
void AssignAttribute(int fNumber, vtkStructuredGrid* output,
int attributeType);
void MapFunction(int fNumber, vtkStructuredGrid* output);
//@{
/**
* Each of these methods compute a derived quantity. On success, the array is
* added to the output and a pointer to the same is returned.
*/
vtkDataArray* ComputeTemperature(vtkStructuredGrid* output);
vtkDataArray* ComputePressure(vtkStructuredGrid* output);
vtkDataArray* ComputeEnthalpy(vtkStructuredGrid* output);
vtkDataArray* ComputeKineticEnergy(vtkStructuredGrid* output);
vtkDataArray* ComputeVelocityMagnitude(vtkStructuredGrid* output);
vtkDataArray* ComputeEntropy(vtkStructuredGrid* output);
vtkDataArray* ComputeSwirl(vtkStructuredGrid* output);
vtkDataArray* ComputeVelocity(vtkStructuredGrid* output);
vtkDataArray* ComputeVorticity(vtkStructuredGrid* output);
vtkDataArray* ComputePressureGradient(vtkStructuredGrid* output);
vtkDataArray* ComputePressureCoefficient(vtkStructuredGrid* output);
vtkDataArray* ComputeMachNumber(vtkStructuredGrid* output);
vtkDataArray* ComputeSoundSpeed(vtkStructuredGrid* output);
vtkDataArray* ComputeVorticityMagnitude(vtkStructuredGrid* output);
vtkDataArray* ComputeStrainRate(vtkStructuredGrid* output);
//@}
// Returns a vtkFloatArray or a vtkDoubleArray depending
// on DoublePrecision setting
vtkDataArray* NewFloatArray();
// Delete references to any existing vtkPoints and
// I-blank arrays. The next Update() will (re)read
// the XYZ file.
void ClearGeometryCache();
double GetGamma(vtkIdType idx, vtkDataArray* gamma);
//plot3d FileNames
char *XYZFileName;
char *QFileName;
char *FunctionFileName;
int BinaryFile;
int HasByteCount;
int TwoDimensionalGeometry;
int MultiGrid;
int ForceRead;
int ByteOrder;
int IBlanking;
int DoublePrecision;
int AutoDetectFormat;
int ExecutedGhostLevels;
size_t FileSize;
//parameters used in computing derived functions
double R;
double Gamma;
double GammaInf;
bool PreserveIntermediateFunctions;
//named functions from meta data
std::vector<std::string> FunctionNames;
//functions to read that are not scalars or vectors
vtkIntArray *FunctionList;
int ScalarFunctionNumber;
int VectorFunctionNumber;
int FillOutputPortInformation(int port, vtkInformation* info) override;
int RequestData(vtkInformation*,
vtkInformationVector**,
vtkInformationVector*) override;
int RequestInformation(vtkInformation*,
vtkInformationVector**,
vtkInformationVector*) override;
vtkMultiBlockPLOT3DReaderInternals* Internal;
vtkMultiProcessController *Controller;
private:
vtkMultiBlockPLOT3DReader(const vtkMultiBlockPLOT3DReader&) = delete;
void operator=(const vtkMultiBlockPLOT3DReader&) = delete;
// Key used to flag intermediate results.
static vtkInformationIntegerKey* INTERMEDIATE_RESULT();
/**
* Remove intermediate results
*/
void RemoveIntermediateFunctions(vtkDataSetAttributes* dsa);
};
#endif
| 32.715415 | 91 | 0.727921 | [
"geometry",
"object",
"vector"
] |
9a998a65dde6a2bc6837be709e4614febbc570d9 | 979 | h | C | sourceCode/platform/vFileFinder.h | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | sourceCode/platform/vFileFinder.h | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | sourceCode/platform/vFileFinder.h | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | #pragma once
#include <vector>
#include <string>
struct SFileOrFolder
{
std::string name;
std::string path;
bool isFile;
unsigned long long int lastWriteTime;
};
class VFileFinder
{
public:
VFileFinder();
virtual ~VFileFinder();
int searchFilesWithExtension(const char* pathWithoutTerminalSlash,const char* extension);
int searchFolders(const char* pathWithoutTerminalSlash);
int searchFilesOrFolders(const char* pathWithoutTerminalSlash);
static int countFiles(const char* pathWithoutTerminalSlash);
static int countFolders(const char* pathWithoutTerminalSlash);
static int countFilesWithPrefix(const char* pathWithoutTerminalSlash,const char* prefix);
SFileOrFolder* getFoundItem(int index);
private:
int _searchFilesOrFolders(const char* pathWithoutTerminalSlash,const char* extension,int mode); // mode=0 --> file, mode=1 --> folder, mode=2 --> file and folder
std::vector<SFileOrFolder> _searchResult;
};
| 28.794118 | 165 | 0.750766 | [
"vector"
] |
9a9cf6996d4e3ba713e82c80bafbcd5942acf747 | 181,716 | c | C | vp9/encoder/vp9_rdopt.c | leo-lb/chromium_libvpx | bb9511684f70a735b3b909712666021e178c93e7 | [
"BSD-3-Clause"
] | null | null | null | vp9/encoder/vp9_rdopt.c | leo-lb/chromium_libvpx | bb9511684f70a735b3b909712666021e178c93e7 | [
"BSD-3-Clause"
] | null | null | null | vp9/encoder/vp9_rdopt.c | leo-lb/chromium_libvpx | bb9511684f70a735b3b909712666021e178c93e7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <assert.h>
#include <math.h>
#include "./vp9_rtcd.h"
#include "./vpx_dsp_rtcd.h"
#include "vpx_dsp/vpx_dsp_common.h"
#include "vpx_mem/vpx_mem.h"
#include "vpx_ports/mem.h"
#include "vpx_ports/system_state.h"
#include "vp9/common/vp9_common.h"
#include "vp9/common/vp9_entropy.h"
#include "vp9/common/vp9_entropymode.h"
#include "vp9/common/vp9_idct.h"
#include "vp9/common/vp9_mvref_common.h"
#include "vp9/common/vp9_pred_common.h"
#include "vp9/common/vp9_quant_common.h"
#include "vp9/common/vp9_reconinter.h"
#include "vp9/common/vp9_reconintra.h"
#include "vp9/common/vp9_scan.h"
#include "vp9/common/vp9_seg_common.h"
#if !CONFIG_REALTIME_ONLY
#include "vp9/encoder/vp9_aq_variance.h"
#endif
#include "vp9/encoder/vp9_cost.h"
#include "vp9/encoder/vp9_encodemb.h"
#include "vp9/encoder/vp9_encodemv.h"
#include "vp9/encoder/vp9_encoder.h"
#include "vp9/encoder/vp9_mcomp.h"
#include "vp9/encoder/vp9_quantize.h"
#include "vp9/encoder/vp9_ratectrl.h"
#include "vp9/encoder/vp9_rd.h"
#include "vp9/encoder/vp9_rdopt.h"
#define LAST_FRAME_MODE_MASK \
((1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
#define GOLDEN_FRAME_MODE_MASK \
((1 << LAST_FRAME) | (1 << ALTREF_FRAME) | (1 << INTRA_FRAME))
#define ALT_REF_MODE_MASK \
((1 << LAST_FRAME) | (1 << GOLDEN_FRAME) | (1 << INTRA_FRAME))
#define SECOND_REF_FRAME_MASK ((1 << ALTREF_FRAME) | 0x01)
#define MIN_EARLY_TERM_INDEX 3
#define NEW_MV_DISCOUNT_FACTOR 8
typedef struct {
PREDICTION_MODE mode;
MV_REFERENCE_FRAME ref_frame[2];
} MODE_DEFINITION;
typedef struct {
MV_REFERENCE_FRAME ref_frame[2];
} REF_DEFINITION;
struct rdcost_block_args {
const VP9_COMP *cpi;
MACROBLOCK *x;
ENTROPY_CONTEXT t_above[16];
ENTROPY_CONTEXT t_left[16];
int this_rate;
int64_t this_dist;
int64_t this_sse;
int64_t this_rd;
int64_t best_rd;
int exit_early;
int use_fast_coef_costing;
const scan_order *so;
uint8_t skippable;
struct buf_2d *this_recon;
};
#define LAST_NEW_MV_INDEX 6
#if !CONFIG_REALTIME_ONLY
static const MODE_DEFINITION vp9_mode_order[MAX_MODES] = {
{ NEARESTMV, { LAST_FRAME, NONE } },
{ NEARESTMV, { ALTREF_FRAME, NONE } },
{ NEARESTMV, { GOLDEN_FRAME, NONE } },
{ DC_PRED, { INTRA_FRAME, NONE } },
{ NEWMV, { LAST_FRAME, NONE } },
{ NEWMV, { ALTREF_FRAME, NONE } },
{ NEWMV, { GOLDEN_FRAME, NONE } },
{ NEARMV, { LAST_FRAME, NONE } },
{ NEARMV, { ALTREF_FRAME, NONE } },
{ NEARMV, { GOLDEN_FRAME, NONE } },
{ ZEROMV, { LAST_FRAME, NONE } },
{ ZEROMV, { GOLDEN_FRAME, NONE } },
{ ZEROMV, { ALTREF_FRAME, NONE } },
{ NEARESTMV, { LAST_FRAME, ALTREF_FRAME } },
{ NEARESTMV, { GOLDEN_FRAME, ALTREF_FRAME } },
{ TM_PRED, { INTRA_FRAME, NONE } },
{ NEARMV, { LAST_FRAME, ALTREF_FRAME } },
{ NEWMV, { LAST_FRAME, ALTREF_FRAME } },
{ NEARMV, { GOLDEN_FRAME, ALTREF_FRAME } },
{ NEWMV, { GOLDEN_FRAME, ALTREF_FRAME } },
{ ZEROMV, { LAST_FRAME, ALTREF_FRAME } },
{ ZEROMV, { GOLDEN_FRAME, ALTREF_FRAME } },
{ H_PRED, { INTRA_FRAME, NONE } },
{ V_PRED, { INTRA_FRAME, NONE } },
{ D135_PRED, { INTRA_FRAME, NONE } },
{ D207_PRED, { INTRA_FRAME, NONE } },
{ D153_PRED, { INTRA_FRAME, NONE } },
{ D63_PRED, { INTRA_FRAME, NONE } },
{ D117_PRED, { INTRA_FRAME, NONE } },
{ D45_PRED, { INTRA_FRAME, NONE } },
};
static const REF_DEFINITION vp9_ref_order[MAX_REFS] = {
{ { LAST_FRAME, NONE } }, { { GOLDEN_FRAME, NONE } },
{ { ALTREF_FRAME, NONE } }, { { LAST_FRAME, ALTREF_FRAME } },
{ { GOLDEN_FRAME, ALTREF_FRAME } }, { { INTRA_FRAME, NONE } },
};
#endif // !CONFIG_REALTIME_ONLY
static void swap_block_ptr(MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int m, int n,
int min_plane, int max_plane) {
int i;
for (i = min_plane; i < max_plane; ++i) {
struct macroblock_plane *const p = &x->plane[i];
struct macroblockd_plane *const pd = &x->e_mbd.plane[i];
p->coeff = ctx->coeff_pbuf[i][m];
p->qcoeff = ctx->qcoeff_pbuf[i][m];
pd->dqcoeff = ctx->dqcoeff_pbuf[i][m];
p->eobs = ctx->eobs_pbuf[i][m];
ctx->coeff_pbuf[i][m] = ctx->coeff_pbuf[i][n];
ctx->qcoeff_pbuf[i][m] = ctx->qcoeff_pbuf[i][n];
ctx->dqcoeff_pbuf[i][m] = ctx->dqcoeff_pbuf[i][n];
ctx->eobs_pbuf[i][m] = ctx->eobs_pbuf[i][n];
ctx->coeff_pbuf[i][n] = p->coeff;
ctx->qcoeff_pbuf[i][n] = p->qcoeff;
ctx->dqcoeff_pbuf[i][n] = pd->dqcoeff;
ctx->eobs_pbuf[i][n] = p->eobs;
}
}
#if !CONFIG_REALTIME_ONLY
static void model_rd_for_sb(VP9_COMP *cpi, BLOCK_SIZE bsize, MACROBLOCK *x,
MACROBLOCKD *xd, int *out_rate_sum,
int64_t *out_dist_sum, int *skip_txfm_sb,
int64_t *skip_sse_sb) {
// Note our transform coeffs are 8 times an orthogonal transform.
// Hence quantizer step is also 8 times. To get effective quantizer
// we need to divide by 8 before sending to modeling function.
int i;
int64_t rate_sum = 0;
int64_t dist_sum = 0;
const int ref = xd->mi[0]->ref_frame[0];
unsigned int sse;
unsigned int var = 0;
int64_t total_sse = 0;
int skip_flag = 1;
const int shift = 6;
int64_t dist;
const int dequant_shift =
#if CONFIG_VP9_HIGHBITDEPTH
(xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd - 5 :
#endif // CONFIG_VP9_HIGHBITDEPTH
3;
unsigned int qstep_vec[MAX_MB_PLANE];
unsigned int nlog2_vec[MAX_MB_PLANE];
unsigned int sum_sse_vec[MAX_MB_PLANE];
int any_zero_sum_sse = 0;
x->pred_sse[ref] = 0;
for (i = 0; i < MAX_MB_PLANE; ++i) {
struct macroblock_plane *const p = &x->plane[i];
struct macroblockd_plane *const pd = &xd->plane[i];
const BLOCK_SIZE bs = get_plane_block_size(bsize, pd);
const TX_SIZE max_tx_size = max_txsize_lookup[bs];
const BLOCK_SIZE unit_size = txsize_to_bsize[max_tx_size];
const int64_t dc_thr = p->quant_thred[0] >> shift;
const int64_t ac_thr = p->quant_thred[1] >> shift;
unsigned int sum_sse = 0;
// The low thresholds are used to measure if the prediction errors are
// low enough so that we can skip the mode search.
const int64_t low_dc_thr = VPXMIN(50, dc_thr >> 2);
const int64_t low_ac_thr = VPXMIN(80, ac_thr >> 2);
int bw = 1 << (b_width_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
int bh = 1 << (b_height_log2_lookup[bs] - b_width_log2_lookup[unit_size]);
int idx, idy;
int lw = b_width_log2_lookup[unit_size] + 2;
int lh = b_height_log2_lookup[unit_size] + 2;
for (idy = 0; idy < bh; ++idy) {
for (idx = 0; idx < bw; ++idx) {
uint8_t *src = p->src.buf + (idy * p->src.stride << lh) + (idx << lw);
uint8_t *dst = pd->dst.buf + (idy * pd->dst.stride << lh) + (idx << lh);
int block_idx = (idy << 1) + idx;
int low_err_skip = 0;
var = cpi->fn_ptr[unit_size].vf(src, p->src.stride, dst, pd->dst.stride,
&sse);
x->bsse[(i << 2) + block_idx] = sse;
sum_sse += sse;
x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_NONE;
if (!x->select_tx_size) {
// Check if all ac coefficients can be quantized to zero.
if (var < ac_thr || var == 0) {
x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_ONLY;
// Check if dc coefficient can be quantized to zero.
if (sse - var < dc_thr || sse == var) {
x->skip_txfm[(i << 2) + block_idx] = SKIP_TXFM_AC_DC;
if (!sse || (var < low_ac_thr && sse - var < low_dc_thr))
low_err_skip = 1;
}
}
}
if (skip_flag && !low_err_skip) skip_flag = 0;
if (i == 0) x->pred_sse[ref] += sse;
}
}
total_sse += sum_sse;
sum_sse_vec[i] = sum_sse;
any_zero_sum_sse = any_zero_sum_sse || (sum_sse == 0);
qstep_vec[i] = pd->dequant[1] >> dequant_shift;
nlog2_vec[i] = num_pels_log2_lookup[bs];
}
// Fast approximate the modelling function.
if (cpi->sf.simple_model_rd_from_var) {
for (i = 0; i < MAX_MB_PLANE; ++i) {
int64_t rate;
const int64_t square_error = sum_sse_vec[i];
int quantizer = qstep_vec[i];
if (quantizer < 120)
rate = (square_error * (280 - quantizer)) >> (16 - VP9_PROB_COST_SHIFT);
else
rate = 0;
dist = (square_error * quantizer) >> 8;
rate_sum += rate;
dist_sum += dist;
}
} else {
if (any_zero_sum_sse) {
for (i = 0; i < MAX_MB_PLANE; ++i) {
int rate;
vp9_model_rd_from_var_lapndz(sum_sse_vec[i], nlog2_vec[i], qstep_vec[i],
&rate, &dist);
rate_sum += rate;
dist_sum += dist;
}
} else {
vp9_model_rd_from_var_lapndz_vec(sum_sse_vec, nlog2_vec, qstep_vec,
&rate_sum, &dist_sum);
}
}
*skip_txfm_sb = skip_flag;
*skip_sse_sb = total_sse << VP9_DIST_SCALE_LOG2;
*out_rate_sum = (int)rate_sum;
*out_dist_sum = dist_sum << VP9_DIST_SCALE_LOG2;
}
#endif // !CONFIG_REALTIME_ONLY
#if CONFIG_VP9_HIGHBITDEPTH
int64_t vp9_highbd_block_error_c(const tran_low_t *coeff,
const tran_low_t *dqcoeff, intptr_t block_size,
int64_t *ssz, int bd) {
int i;
int64_t error = 0, sqcoeff = 0;
int shift = 2 * (bd - 8);
int rounding = shift > 0 ? 1 << (shift - 1) : 0;
for (i = 0; i < block_size; i++) {
const int64_t diff = coeff[i] - dqcoeff[i];
error += diff * diff;
sqcoeff += (int64_t)coeff[i] * (int64_t)coeff[i];
}
assert(error >= 0 && sqcoeff >= 0);
error = (error + rounding) >> shift;
sqcoeff = (sqcoeff + rounding) >> shift;
*ssz = sqcoeff;
return error;
}
static int64_t vp9_highbd_block_error_dispatch(const tran_low_t *coeff,
const tran_low_t *dqcoeff,
intptr_t block_size,
int64_t *ssz, int bd) {
if (bd == 8) {
return vp9_block_error(coeff, dqcoeff, block_size, ssz);
} else {
return vp9_highbd_block_error(coeff, dqcoeff, block_size, ssz, bd);
}
}
#endif // CONFIG_VP9_HIGHBITDEPTH
int64_t vp9_block_error_c(const tran_low_t *coeff, const tran_low_t *dqcoeff,
intptr_t block_size, int64_t *ssz) {
int i;
int64_t error = 0, sqcoeff = 0;
for (i = 0; i < block_size; i++) {
const int diff = coeff[i] - dqcoeff[i];
error += diff * diff;
sqcoeff += coeff[i] * coeff[i];
}
*ssz = sqcoeff;
return error;
}
int64_t vp9_block_error_fp_c(const tran_low_t *coeff, const tran_low_t *dqcoeff,
int block_size) {
int i;
int64_t error = 0;
for (i = 0; i < block_size; i++) {
const int diff = coeff[i] - dqcoeff[i];
error += diff * diff;
}
return error;
}
/* The trailing '0' is a terminator which is used inside cost_coeffs() to
* decide whether to include cost of a trailing EOB node or not (i.e. we
* can skip this if the last coefficient in this transform block, e.g. the
* 16th coefficient in a 4x4 block or the 64th coefficient in a 8x8 block,
* were non-zero). */
static const int16_t band_counts[TX_SIZES][8] = {
{ 1, 2, 3, 4, 3, 16 - 13, 0 },
{ 1, 2, 3, 4, 11, 64 - 21, 0 },
{ 1, 2, 3, 4, 11, 256 - 21, 0 },
{ 1, 2, 3, 4, 11, 1024 - 21, 0 },
};
static int cost_coeffs(MACROBLOCK *x, int plane, int block, TX_SIZE tx_size,
int pt, const int16_t *scan, const int16_t *nb,
int use_fast_coef_costing) {
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *mi = xd->mi[0];
const struct macroblock_plane *p = &x->plane[plane];
const PLANE_TYPE type = get_plane_type(plane);
const int16_t *band_count = &band_counts[tx_size][1];
const int eob = p->eobs[block];
const tran_low_t *const qcoeff = BLOCK_OFFSET(p->qcoeff, block);
unsigned int(*token_costs)[2][COEFF_CONTEXTS][ENTROPY_TOKENS] =
x->token_costs[tx_size][type][is_inter_block(mi)];
uint8_t token_cache[32 * 32];
int cost;
#if CONFIG_VP9_HIGHBITDEPTH
const uint16_t *cat6_high_cost = vp9_get_high_cost_table(xd->bd);
#else
const uint16_t *cat6_high_cost = vp9_get_high_cost_table(8);
#endif
// Check for consistency of tx_size with mode info
assert(type == PLANE_TYPE_Y
? mi->tx_size == tx_size
: get_uv_tx_size(mi, &xd->plane[plane]) == tx_size);
if (eob == 0) {
// single eob token
cost = token_costs[0][0][pt][EOB_TOKEN];
} else {
if (use_fast_coef_costing) {
int band_left = *band_count++;
int c;
// dc token
int v = qcoeff[0];
int16_t prev_t;
cost = vp9_get_token_cost(v, &prev_t, cat6_high_cost);
cost += (*token_costs)[0][pt][prev_t];
token_cache[0] = vp9_pt_energy_class[prev_t];
++token_costs;
// ac tokens
for (c = 1; c < eob; c++) {
const int rc = scan[c];
int16_t t;
v = qcoeff[rc];
cost += vp9_get_token_cost(v, &t, cat6_high_cost);
cost += (*token_costs)[!prev_t][!prev_t][t];
prev_t = t;
if (!--band_left) {
band_left = *band_count++;
++token_costs;
}
}
// eob token
if (band_left) cost += (*token_costs)[0][!prev_t][EOB_TOKEN];
} else { // !use_fast_coef_costing
int band_left = *band_count++;
int c;
// dc token
int v = qcoeff[0];
int16_t tok;
unsigned int(*tok_cost_ptr)[COEFF_CONTEXTS][ENTROPY_TOKENS];
cost = vp9_get_token_cost(v, &tok, cat6_high_cost);
cost += (*token_costs)[0][pt][tok];
token_cache[0] = vp9_pt_energy_class[tok];
++token_costs;
tok_cost_ptr = &((*token_costs)[!tok]);
// ac tokens
for (c = 1; c < eob; c++) {
const int rc = scan[c];
v = qcoeff[rc];
cost += vp9_get_token_cost(v, &tok, cat6_high_cost);
pt = get_coef_context(nb, token_cache, c);
cost += (*tok_cost_ptr)[pt][tok];
token_cache[rc] = vp9_pt_energy_class[tok];
if (!--band_left) {
band_left = *band_count++;
++token_costs;
}
tok_cost_ptr = &((*token_costs)[!tok]);
}
// eob token
if (band_left) {
pt = get_coef_context(nb, token_cache, c);
cost += (*token_costs)[0][pt][EOB_TOKEN];
}
}
}
return cost;
}
static INLINE int num_4x4_to_edge(int plane_4x4_dim, int mb_to_edge_dim,
int subsampling_dim, int blk_dim) {
return plane_4x4_dim + (mb_to_edge_dim >> (5 + subsampling_dim)) - blk_dim;
}
// Copy all visible 4x4s in the transform block.
static void copy_block_visible(const MACROBLOCKD *xd,
const struct macroblockd_plane *const pd,
const uint8_t *src, const int src_stride,
uint8_t *dst, const int dst_stride, int blk_row,
int blk_col, const BLOCK_SIZE plane_bsize,
const BLOCK_SIZE tx_bsize) {
const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
pd->subsampling_x, blk_col);
int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
pd->subsampling_y, blk_row);
const int is_highbd = xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH;
if (tx_bsize == BLOCK_4X4 ||
(b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
const int w = tx_4x4_w << 2;
const int h = tx_4x4_h << 2;
#if CONFIG_VP9_HIGHBITDEPTH
if (is_highbd) {
vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(src), src_stride,
CONVERT_TO_SHORTPTR(dst), dst_stride, NULL, 0, 0,
0, 0, w, h, xd->bd);
} else {
#endif
vpx_convolve_copy(src, src_stride, dst, dst_stride, NULL, 0, 0, 0, 0, w,
h);
#if CONFIG_VP9_HIGHBITDEPTH
}
#endif
} else {
int r, c;
int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
// if we are in the unrestricted motion border.
for (r = 0; r < max_r; ++r) {
// Skip visiting the sub blocks that are wholly within the UMV.
for (c = 0; c < max_c; ++c) {
const uint8_t *src_ptr = src + r * src_stride * 4 + c * 4;
uint8_t *dst_ptr = dst + r * dst_stride * 4 + c * 4;
#if CONFIG_VP9_HIGHBITDEPTH
if (is_highbd) {
vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(src_ptr), src_stride,
CONVERT_TO_SHORTPTR(dst_ptr), dst_stride,
NULL, 0, 0, 0, 0, 4, 4, xd->bd);
} else {
#endif
vpx_convolve_copy(src_ptr, src_stride, dst_ptr, dst_stride, NULL, 0,
0, 0, 0, 4, 4);
#if CONFIG_VP9_HIGHBITDEPTH
}
#endif
}
}
}
(void)is_highbd;
}
// Compute the pixel domain sum square error on all visible 4x4s in the
// transform block.
static unsigned pixel_sse(const VP9_COMP *const cpi, const MACROBLOCKD *xd,
const struct macroblockd_plane *const pd,
const uint8_t *src, const int src_stride,
const uint8_t *dst, const int dst_stride, int blk_row,
int blk_col, const BLOCK_SIZE plane_bsize,
const BLOCK_SIZE tx_bsize) {
unsigned int sse = 0;
const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
pd->subsampling_x, blk_col);
int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
pd->subsampling_y, blk_row);
if (tx_bsize == BLOCK_4X4 ||
(b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
cpi->fn_ptr[tx_bsize].vf(src, src_stride, dst, dst_stride, &sse);
} else {
const vpx_variance_fn_t vf_4x4 = cpi->fn_ptr[BLOCK_4X4].vf;
int r, c;
unsigned this_sse = 0;
int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
sse = 0;
// if we are in the unrestricted motion border.
for (r = 0; r < max_r; ++r) {
// Skip visiting the sub blocks that are wholly within the UMV.
for (c = 0; c < max_c; ++c) {
vf_4x4(src + r * src_stride * 4 + c * 4, src_stride,
dst + r * dst_stride * 4 + c * 4, dst_stride, &this_sse);
sse += this_sse;
}
}
}
return sse;
}
// Compute the squares sum squares on all visible 4x4s in the transform block.
static int64_t sum_squares_visible(const MACROBLOCKD *xd,
const struct macroblockd_plane *const pd,
const int16_t *diff, const int diff_stride,
int blk_row, int blk_col,
const BLOCK_SIZE plane_bsize,
const BLOCK_SIZE tx_bsize) {
int64_t sse;
const int plane_4x4_w = num_4x4_blocks_wide_lookup[plane_bsize];
const int plane_4x4_h = num_4x4_blocks_high_lookup[plane_bsize];
const int tx_4x4_w = num_4x4_blocks_wide_lookup[tx_bsize];
const int tx_4x4_h = num_4x4_blocks_high_lookup[tx_bsize];
int b4x4s_to_right_edge = num_4x4_to_edge(plane_4x4_w, xd->mb_to_right_edge,
pd->subsampling_x, blk_col);
int b4x4s_to_bottom_edge = num_4x4_to_edge(plane_4x4_h, xd->mb_to_bottom_edge,
pd->subsampling_y, blk_row);
if (tx_bsize == BLOCK_4X4 ||
(b4x4s_to_right_edge >= tx_4x4_w && b4x4s_to_bottom_edge >= tx_4x4_h)) {
assert(tx_4x4_w == tx_4x4_h);
sse = (int64_t)vpx_sum_squares_2d_i16(diff, diff_stride, tx_4x4_w << 2);
} else {
int r, c;
int max_r = VPXMIN(b4x4s_to_bottom_edge, tx_4x4_h);
int max_c = VPXMIN(b4x4s_to_right_edge, tx_4x4_w);
sse = 0;
// if we are in the unrestricted motion border.
for (r = 0; r < max_r; ++r) {
// Skip visiting the sub blocks that are wholly within the UMV.
for (c = 0; c < max_c; ++c) {
sse += (int64_t)vpx_sum_squares_2d_i16(
diff + r * diff_stride * 4 + c * 4, diff_stride, 4);
}
}
}
return sse;
}
static void dist_block(const VP9_COMP *cpi, MACROBLOCK *x, int plane,
BLOCK_SIZE plane_bsize, int block, int blk_row,
int blk_col, TX_SIZE tx_size, int64_t *out_dist,
int64_t *out_sse, struct buf_2d *out_recon) {
MACROBLOCKD *const xd = &x->e_mbd;
const struct macroblock_plane *const p = &x->plane[plane];
const struct macroblockd_plane *const pd = &xd->plane[plane];
const int eob = p->eobs[block];
if (!out_recon && x->block_tx_domain && eob) {
const int ss_txfrm_size = tx_size << 1;
int64_t this_sse;
const int shift = tx_size == TX_32X32 ? 0 : 2;
const tran_low_t *const coeff = BLOCK_OFFSET(p->coeff, block);
const tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
#if CONFIG_VP9_HIGHBITDEPTH
const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
*out_dist = vp9_highbd_block_error_dispatch(
coeff, dqcoeff, 16 << ss_txfrm_size, &this_sse, bd) >>
shift;
#else
*out_dist =
vp9_block_error(coeff, dqcoeff, 16 << ss_txfrm_size, &this_sse) >>
shift;
#endif // CONFIG_VP9_HIGHBITDEPTH
*out_sse = this_sse >> shift;
if (x->skip_encode && !is_inter_block(xd->mi[0])) {
// TODO(jingning): tune the model to better capture the distortion.
const int64_t p =
(pd->dequant[1] * pd->dequant[1] * (1 << ss_txfrm_size)) >>
#if CONFIG_VP9_HIGHBITDEPTH
(shift + 2 + (bd - 8) * 2);
#else
(shift + 2);
#endif // CONFIG_VP9_HIGHBITDEPTH
*out_dist += (p >> 4);
*out_sse += p;
}
} else {
const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
const int bs = 4 * num_4x4_blocks_wide_lookup[tx_bsize];
const int src_stride = p->src.stride;
const int dst_stride = pd->dst.stride;
const int src_idx = 4 * (blk_row * src_stride + blk_col);
const int dst_idx = 4 * (blk_row * dst_stride + blk_col);
const uint8_t *src = &p->src.buf[src_idx];
const uint8_t *dst = &pd->dst.buf[dst_idx];
uint8_t *out_recon_ptr = 0;
const tran_low_t *dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
unsigned int tmp;
tmp = pixel_sse(cpi, xd, pd, src, src_stride, dst, dst_stride, blk_row,
blk_col, plane_bsize, tx_bsize);
*out_sse = (int64_t)tmp * 16;
if (out_recon) {
const int out_recon_idx = 4 * (blk_row * out_recon->stride + blk_col);
out_recon_ptr = &out_recon->buf[out_recon_idx];
copy_block_visible(xd, pd, dst, dst_stride, out_recon_ptr,
out_recon->stride, blk_row, blk_col, plane_bsize,
tx_bsize);
}
if (eob) {
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, recon16[1024]);
uint8_t *recon = (uint8_t *)recon16;
#else
DECLARE_ALIGNED(16, uint8_t, recon[1024]);
#endif // CONFIG_VP9_HIGHBITDEPTH
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
vpx_highbd_convolve_copy(CONVERT_TO_SHORTPTR(dst), dst_stride, recon16,
32, NULL, 0, 0, 0, 0, bs, bs, xd->bd);
if (xd->lossless) {
vp9_highbd_iwht4x4_add(dqcoeff, recon16, 32, eob, xd->bd);
} else {
switch (tx_size) {
case TX_4X4:
vp9_highbd_idct4x4_add(dqcoeff, recon16, 32, eob, xd->bd);
break;
case TX_8X8:
vp9_highbd_idct8x8_add(dqcoeff, recon16, 32, eob, xd->bd);
break;
case TX_16X16:
vp9_highbd_idct16x16_add(dqcoeff, recon16, 32, eob, xd->bd);
break;
default:
assert(tx_size == TX_32X32);
vp9_highbd_idct32x32_add(dqcoeff, recon16, 32, eob, xd->bd);
break;
}
}
recon = CONVERT_TO_BYTEPTR(recon16);
} else {
#endif // CONFIG_VP9_HIGHBITDEPTH
vpx_convolve_copy(dst, dst_stride, recon, 32, NULL, 0, 0, 0, 0, bs, bs);
switch (tx_size) {
case TX_32X32: vp9_idct32x32_add(dqcoeff, recon, 32, eob); break;
case TX_16X16: vp9_idct16x16_add(dqcoeff, recon, 32, eob); break;
case TX_8X8: vp9_idct8x8_add(dqcoeff, recon, 32, eob); break;
default:
assert(tx_size == TX_4X4);
// this is like vp9_short_idct4x4 but has a special case around
// eob<=1, which is significant (not just an optimization) for
// the lossless case.
x->inv_txfm_add(dqcoeff, recon, 32, eob);
break;
}
#if CONFIG_VP9_HIGHBITDEPTH
}
#endif // CONFIG_VP9_HIGHBITDEPTH
tmp = pixel_sse(cpi, xd, pd, src, src_stride, recon, 32, blk_row, blk_col,
plane_bsize, tx_bsize);
if (out_recon) {
copy_block_visible(xd, pd, recon, 32, out_recon_ptr, out_recon->stride,
blk_row, blk_col, plane_bsize, tx_bsize);
}
}
*out_dist = (int64_t)tmp * 16;
}
}
static int rate_block(int plane, int block, TX_SIZE tx_size, int coeff_ctx,
struct rdcost_block_args *args) {
return cost_coeffs(args->x, plane, block, tx_size, coeff_ctx, args->so->scan,
args->so->neighbors, args->use_fast_coef_costing);
}
static void block_rd_txfm(int plane, int block, int blk_row, int blk_col,
BLOCK_SIZE plane_bsize, TX_SIZE tx_size, void *arg) {
struct rdcost_block_args *args = arg;
MACROBLOCK *const x = args->x;
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
int64_t rd1, rd2, rd;
int rate;
int64_t dist;
int64_t sse;
const int coeff_ctx =
combine_entropy_contexts(args->t_left[blk_row], args->t_above[blk_col]);
struct buf_2d *recon = args->this_recon;
const BLOCK_SIZE tx_bsize = txsize_to_bsize[tx_size];
const struct macroblockd_plane *const pd = &xd->plane[plane];
const int dst_stride = pd->dst.stride;
const uint8_t *dst = &pd->dst.buf[4 * (blk_row * dst_stride + blk_col)];
if (args->exit_early) return;
if (!is_inter_block(mi)) {
#if CONFIG_MISMATCH_DEBUG
struct encode_b_args intra_arg = {
x, x->block_qcoeff_opt, args->t_above, args->t_left, &mi->skip, 0, 0, 0
};
#else
struct encode_b_args intra_arg = { x, x->block_qcoeff_opt, args->t_above,
args->t_left, &mi->skip };
#endif
vp9_encode_block_intra(plane, block, blk_row, blk_col, plane_bsize, tx_size,
&intra_arg);
if (recon) {
uint8_t *rec_ptr = &recon->buf[4 * (blk_row * recon->stride + blk_col)];
copy_block_visible(xd, pd, dst, dst_stride, rec_ptr, recon->stride,
blk_row, blk_col, plane_bsize, tx_bsize);
}
if (x->block_tx_domain) {
dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
tx_size, &dist, &sse, /*recon =*/0);
} else {
const struct macroblock_plane *const p = &x->plane[plane];
const int src_stride = p->src.stride;
const int diff_stride = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
const uint8_t *src = &p->src.buf[4 * (blk_row * src_stride + blk_col)];
const int16_t *diff = &p->src_diff[4 * (blk_row * diff_stride + blk_col)];
unsigned int tmp;
sse = sum_squares_visible(xd, pd, diff, diff_stride, blk_row, blk_col,
plane_bsize, tx_bsize);
#if CONFIG_VP9_HIGHBITDEPTH
if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) && (xd->bd > 8))
sse = ROUND64_POWER_OF_TWO(sse, (xd->bd - 8) * 2);
#endif // CONFIG_VP9_HIGHBITDEPTH
sse = sse * 16;
tmp = pixel_sse(args->cpi, xd, pd, src, src_stride, dst, dst_stride,
blk_row, blk_col, plane_bsize, tx_bsize);
dist = (int64_t)tmp * 16;
}
} else {
int skip_txfm_flag = SKIP_TXFM_NONE;
if (max_txsize_lookup[plane_bsize] == tx_size)
skip_txfm_flag = x->skip_txfm[(plane << 2) + (block >> (tx_size << 1))];
if (skip_txfm_flag == SKIP_TXFM_NONE ||
(recon && skip_txfm_flag == SKIP_TXFM_AC_ONLY)) {
// full forward transform and quantization
vp9_xform_quant(x, plane, block, blk_row, blk_col, plane_bsize, tx_size);
if (x->block_qcoeff_opt)
vp9_optimize_b(x, plane, block, tx_size, coeff_ctx);
dist_block(args->cpi, x, plane, plane_bsize, block, blk_row, blk_col,
tx_size, &dist, &sse, recon);
} else if (skip_txfm_flag == SKIP_TXFM_AC_ONLY) {
// compute DC coefficient
tran_low_t *const coeff = BLOCK_OFFSET(x->plane[plane].coeff, block);
tran_low_t *const dqcoeff = BLOCK_OFFSET(xd->plane[plane].dqcoeff, block);
vp9_xform_quant_dc(x, plane, block, blk_row, blk_col, plane_bsize,
tx_size);
sse = x->bsse[(plane << 2) + (block >> (tx_size << 1))] << 4;
dist = sse;
if (x->plane[plane].eobs[block]) {
const int64_t orig_sse = (int64_t)coeff[0] * coeff[0];
const int64_t resd_sse = coeff[0] - dqcoeff[0];
int64_t dc_correct = orig_sse - resd_sse * resd_sse;
#if CONFIG_VP9_HIGHBITDEPTH
dc_correct >>= ((xd->bd - 8) * 2);
#endif
if (tx_size != TX_32X32) dc_correct >>= 2;
dist = VPXMAX(0, sse - dc_correct);
}
} else {
// SKIP_TXFM_AC_DC
// skip forward transform. Because this is handled here, the quantization
// does not need to do it.
x->plane[plane].eobs[block] = 0;
sse = x->bsse[(plane << 2) + (block >> (tx_size << 1))] << 4;
dist = sse;
if (recon) {
uint8_t *rec_ptr = &recon->buf[4 * (blk_row * recon->stride + blk_col)];
copy_block_visible(xd, pd, dst, dst_stride, rec_ptr, recon->stride,
blk_row, blk_col, plane_bsize, tx_bsize);
}
}
}
rd = RDCOST(x->rdmult, x->rddiv, 0, dist);
if (args->this_rd + rd > args->best_rd) {
args->exit_early = 1;
return;
}
rate = rate_block(plane, block, tx_size, coeff_ctx, args);
args->t_above[blk_col] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
args->t_left[blk_row] = (x->plane[plane].eobs[block] > 0) ? 1 : 0;
rd1 = RDCOST(x->rdmult, x->rddiv, rate, dist);
rd2 = RDCOST(x->rdmult, x->rddiv, 0, sse);
// TODO(jingning): temporarily enabled only for luma component
rd = VPXMIN(rd1, rd2);
if (plane == 0) {
x->zcoeff_blk[tx_size][block] =
!x->plane[plane].eobs[block] ||
(x->sharpness == 0 && rd1 > rd2 && !xd->lossless);
x->sum_y_eobs[tx_size] += x->plane[plane].eobs[block];
}
args->this_rate += rate;
args->this_dist += dist;
args->this_sse += sse;
args->this_rd += rd;
if (args->this_rd > args->best_rd) {
args->exit_early = 1;
return;
}
args->skippable &= !x->plane[plane].eobs[block];
}
static void txfm_rd_in_plane(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
int64_t *distortion, int *skippable, int64_t *sse,
int64_t ref_best_rd, int plane, BLOCK_SIZE bsize,
TX_SIZE tx_size, int use_fast_coef_costing,
struct buf_2d *recon) {
MACROBLOCKD *const xd = &x->e_mbd;
const struct macroblockd_plane *const pd = &xd->plane[plane];
struct rdcost_block_args args;
vp9_zero(args);
args.cpi = cpi;
args.x = x;
args.best_rd = ref_best_rd;
args.use_fast_coef_costing = use_fast_coef_costing;
args.skippable = 1;
args.this_recon = recon;
if (plane == 0) xd->mi[0]->tx_size = tx_size;
vp9_get_entropy_contexts(bsize, tx_size, pd, args.t_above, args.t_left);
args.so = get_scan(xd, tx_size, get_plane_type(plane), 0);
vp9_foreach_transformed_block_in_plane(xd, bsize, plane, block_rd_txfm,
&args);
if (args.exit_early) {
*rate = INT_MAX;
*distortion = INT64_MAX;
*sse = INT64_MAX;
*skippable = 0;
} else {
*distortion = args.this_dist;
*rate = args.this_rate;
*sse = args.this_sse;
*skippable = args.skippable;
}
}
static void choose_largest_tx_size(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
int64_t *distortion, int *skip, int64_t *sse,
int64_t ref_best_rd, BLOCK_SIZE bs,
struct buf_2d *recon) {
const TX_SIZE max_tx_size = max_txsize_lookup[bs];
VP9_COMMON *const cm = &cpi->common;
const TX_SIZE largest_tx_size = tx_mode_to_biggest_tx_size[cm->tx_mode];
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
mi->tx_size = VPXMIN(max_tx_size, largest_tx_size);
txfm_rd_in_plane(cpi, x, rate, distortion, skip, sse, ref_best_rd, 0, bs,
mi->tx_size, cpi->sf.use_fast_coef_costing, recon);
}
static void choose_tx_size_from_rd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
int64_t *distortion, int *skip,
int64_t *psse, int64_t ref_best_rd,
BLOCK_SIZE bs, struct buf_2d *recon) {
const TX_SIZE max_tx_size = max_txsize_lookup[bs];
VP9_COMMON *const cm = &cpi->common;
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
int r[TX_SIZES][2], s[TX_SIZES];
int64_t d[TX_SIZES], sse[TX_SIZES];
int64_t rd[TX_SIZES][2] = { { INT64_MAX, INT64_MAX },
{ INT64_MAX, INT64_MAX },
{ INT64_MAX, INT64_MAX },
{ INT64_MAX, INT64_MAX } };
int n;
int s0, s1;
int64_t best_rd = ref_best_rd;
TX_SIZE best_tx = max_tx_size;
int start_tx, end_tx;
const int tx_size_ctx = get_tx_size_context(xd);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, recon_buf16[TX_SIZES][64 * 64]);
uint8_t *recon_buf[TX_SIZES];
for (n = 0; n < TX_SIZES; ++n) {
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
recon_buf[n] = CONVERT_TO_BYTEPTR(recon_buf16[n]);
} else {
recon_buf[n] = (uint8_t *)recon_buf16[n];
}
}
#else
DECLARE_ALIGNED(16, uint8_t, recon_buf[TX_SIZES][64 * 64]);
#endif // CONFIG_VP9_HIGHBITDEPTH
assert(skip_prob > 0);
s0 = vp9_cost_bit(skip_prob, 0);
s1 = vp9_cost_bit(skip_prob, 1);
if (cm->tx_mode == TX_MODE_SELECT) {
start_tx = max_tx_size;
end_tx = VPXMAX(start_tx - cpi->sf.tx_size_search_depth, 0);
if (bs > BLOCK_32X32) end_tx = VPXMIN(end_tx + 1, start_tx);
} else {
TX_SIZE chosen_tx_size =
VPXMIN(max_tx_size, tx_mode_to_biggest_tx_size[cm->tx_mode]);
start_tx = chosen_tx_size;
end_tx = chosen_tx_size;
}
for (n = start_tx; n >= end_tx; n--) {
const int r_tx_size = cpi->tx_size_cost[max_tx_size - 1][tx_size_ctx][n];
if (recon) {
struct buf_2d this_recon;
this_recon.buf = recon_buf[n];
this_recon.stride = recon->stride;
txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], best_rd, 0, bs,
n, cpi->sf.use_fast_coef_costing, &this_recon);
} else {
txfm_rd_in_plane(cpi, x, &r[n][0], &d[n], &s[n], &sse[n], best_rd, 0, bs,
n, cpi->sf.use_fast_coef_costing, 0);
}
r[n][1] = r[n][0];
if (r[n][0] < INT_MAX) {
r[n][1] += r_tx_size;
}
if (d[n] == INT64_MAX || r[n][0] == INT_MAX) {
rd[n][0] = rd[n][1] = INT64_MAX;
} else if (s[n]) {
if (is_inter_block(mi)) {
rd[n][0] = rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
r[n][1] -= r_tx_size;
} else {
rd[n][0] = RDCOST(x->rdmult, x->rddiv, s1, sse[n]);
rd[n][1] = RDCOST(x->rdmult, x->rddiv, s1 + r_tx_size, sse[n]);
}
} else {
rd[n][0] = RDCOST(x->rdmult, x->rddiv, r[n][0] + s0, d[n]);
rd[n][1] = RDCOST(x->rdmult, x->rddiv, r[n][1] + s0, d[n]);
}
if (is_inter_block(mi) && !xd->lossless && !s[n] && sse[n] != INT64_MAX) {
rd[n][0] = VPXMIN(rd[n][0], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
rd[n][1] = VPXMIN(rd[n][1], RDCOST(x->rdmult, x->rddiv, s1, sse[n]));
}
// Early termination in transform size search.
if (cpi->sf.tx_size_search_breakout &&
(rd[n][1] == INT64_MAX ||
(n < (int)max_tx_size && rd[n][1] > rd[n + 1][1]) || s[n] == 1))
break;
if (rd[n][1] < best_rd) {
best_tx = n;
best_rd = rd[n][1];
}
}
mi->tx_size = best_tx;
*distortion = d[mi->tx_size];
*rate = r[mi->tx_size][cm->tx_mode == TX_MODE_SELECT];
*skip = s[mi->tx_size];
*psse = sse[mi->tx_size];
if (recon) {
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
memcpy(CONVERT_TO_SHORTPTR(recon->buf),
CONVERT_TO_SHORTPTR(recon_buf[mi->tx_size]),
64 * 64 * sizeof(uint16_t));
} else {
#endif
memcpy(recon->buf, recon_buf[mi->tx_size], 64 * 64);
#if CONFIG_VP9_HIGHBITDEPTH
}
#endif
}
}
static void super_block_yrd(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
int64_t *distortion, int *skip, int64_t *psse,
BLOCK_SIZE bs, int64_t ref_best_rd,
struct buf_2d *recon) {
MACROBLOCKD *xd = &x->e_mbd;
int64_t sse;
int64_t *ret_sse = psse ? psse : &sse;
assert(bs == xd->mi[0]->sb_type);
if (cpi->sf.tx_size_search_method == USE_LARGESTALL || xd->lossless) {
choose_largest_tx_size(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
bs, recon);
} else {
choose_tx_size_from_rd(cpi, x, rate, distortion, skip, ret_sse, ref_best_rd,
bs, recon);
}
}
static int conditional_skipintra(PREDICTION_MODE mode,
PREDICTION_MODE best_intra_mode) {
if (mode == D117_PRED && best_intra_mode != V_PRED &&
best_intra_mode != D135_PRED)
return 1;
if (mode == D63_PRED && best_intra_mode != V_PRED &&
best_intra_mode != D45_PRED)
return 1;
if (mode == D207_PRED && best_intra_mode != H_PRED &&
best_intra_mode != D45_PRED)
return 1;
if (mode == D153_PRED && best_intra_mode != H_PRED &&
best_intra_mode != D135_PRED)
return 1;
return 0;
}
static int64_t rd_pick_intra4x4block(VP9_COMP *cpi, MACROBLOCK *x, int row,
int col, PREDICTION_MODE *best_mode,
const int *bmode_costs, ENTROPY_CONTEXT *a,
ENTROPY_CONTEXT *l, int *bestrate,
int *bestratey, int64_t *bestdistortion,
BLOCK_SIZE bsize, int64_t rd_thresh) {
PREDICTION_MODE mode;
MACROBLOCKD *const xd = &x->e_mbd;
int64_t best_rd = rd_thresh;
struct macroblock_plane *p = &x->plane[0];
struct macroblockd_plane *pd = &xd->plane[0];
const int src_stride = p->src.stride;
const int dst_stride = pd->dst.stride;
const uint8_t *src_init = &p->src.buf[row * 4 * src_stride + col * 4];
uint8_t *dst_init = &pd->dst.buf[row * 4 * src_stride + col * 4];
ENTROPY_CONTEXT ta[2], tempa[2];
ENTROPY_CONTEXT tl[2], templ[2];
const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
int idx, idy;
uint8_t best_dst[8 * 8];
#if CONFIG_VP9_HIGHBITDEPTH
uint16_t best_dst16[8 * 8];
#endif
memcpy(ta, a, num_4x4_blocks_wide * sizeof(a[0]));
memcpy(tl, l, num_4x4_blocks_high * sizeof(l[0]));
xd->mi[0]->tx_size = TX_4X4;
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
int64_t this_rd;
int ratey = 0;
int64_t distortion = 0;
int rate = bmode_costs[mode];
if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
// Only do the oblique modes if the best so far is
// one of the neighboring directional modes
if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
if (conditional_skipintra(mode, *best_mode)) continue;
}
memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
const int block = (row + idy) * 2 + (col + idx);
const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
uint16_t *const dst16 = CONVERT_TO_SHORTPTR(dst);
int16_t *const src_diff =
vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
tran_low_t *const coeff = BLOCK_OFFSET(x->plane[0].coeff, block);
xd->mi[0]->bmi[block].as_mode = mode;
vp9_predict_intra_block(xd, 1, TX_4X4, mode,
x->skip_encode ? src : dst,
x->skip_encode ? src_stride : dst_stride, dst,
dst_stride, col + idx, row + idy, 0);
vpx_highbd_subtract_block(4, 4, src_diff, 8, src, src_stride, dst,
dst_stride, xd->bd);
if (xd->lossless) {
const scan_order *so = &vp9_default_scan_orders[TX_4X4];
const int coeff_ctx =
combine_entropy_contexts(tempa[idx], templ[idy]);
vp9_highbd_fwht4x4(src_diff, coeff, 8);
vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
so->neighbors, cpi->sf.use_fast_coef_costing);
tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
goto next_highbd;
vp9_highbd_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst16,
dst_stride, p->eobs[block], xd->bd);
} else {
int64_t unused;
const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
const scan_order *so = &vp9_scan_orders[TX_4X4][tx_type];
const int coeff_ctx =
combine_entropy_contexts(tempa[idx], templ[idy]);
if (tx_type == DCT_DCT)
vpx_highbd_fdct4x4(src_diff, coeff, 8);
else
vp9_highbd_fht4x4(src_diff, coeff, 8, tx_type);
vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
so->neighbors, cpi->sf.use_fast_coef_costing);
distortion += vp9_highbd_block_error_dispatch(
coeff, BLOCK_OFFSET(pd->dqcoeff, block), 16,
&unused, xd->bd) >>
2;
tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0 ? 1 : 0);
if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
goto next_highbd;
vp9_highbd_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block),
dst16, dst_stride, p->eobs[block], xd->bd);
}
}
}
rate += ratey;
this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
if (this_rd < best_rd) {
*bestrate = rate;
*bestratey = ratey;
*bestdistortion = distortion;
best_rd = this_rd;
*best_mode = mode;
memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
memcpy(best_dst16 + idy * 8,
CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
num_4x4_blocks_wide * 4 * sizeof(uint16_t));
}
}
next_highbd : {}
}
if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy) {
memcpy(CONVERT_TO_SHORTPTR(dst_init + idy * dst_stride),
best_dst16 + idy * 8, num_4x4_blocks_wide * 4 * sizeof(uint16_t));
}
return best_rd;
}
#endif // CONFIG_VP9_HIGHBITDEPTH
for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
int64_t this_rd;
int ratey = 0;
int64_t distortion = 0;
int rate = bmode_costs[mode];
if (!(cpi->sf.intra_y_mode_mask[TX_4X4] & (1 << mode))) continue;
// Only do the oblique modes if the best so far is
// one of the neighboring directional modes
if (cpi->sf.mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
if (conditional_skipintra(mode, *best_mode)) continue;
}
memcpy(tempa, ta, num_4x4_blocks_wide * sizeof(ta[0]));
memcpy(templ, tl, num_4x4_blocks_high * sizeof(tl[0]));
for (idy = 0; idy < num_4x4_blocks_high; ++idy) {
for (idx = 0; idx < num_4x4_blocks_wide; ++idx) {
const int block = (row + idy) * 2 + (col + idx);
const uint8_t *const src = &src_init[idx * 4 + idy * 4 * src_stride];
uint8_t *const dst = &dst_init[idx * 4 + idy * 4 * dst_stride];
int16_t *const src_diff =
vp9_raster_block_offset_int16(BLOCK_8X8, block, p->src_diff);
tran_low_t *const coeff = BLOCK_OFFSET(x->plane[0].coeff, block);
xd->mi[0]->bmi[block].as_mode = mode;
vp9_predict_intra_block(xd, 1, TX_4X4, mode, x->skip_encode ? src : dst,
x->skip_encode ? src_stride : dst_stride, dst,
dst_stride, col + idx, row + idy, 0);
vpx_subtract_block(4, 4, src_diff, 8, src, src_stride, dst, dst_stride);
if (xd->lossless) {
const scan_order *so = &vp9_default_scan_orders[TX_4X4];
const int coeff_ctx =
combine_entropy_contexts(tempa[idx], templ[idy]);
vp9_fwht4x4(src_diff, coeff, 8);
vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
so->neighbors, cpi->sf.use_fast_coef_costing);
tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
goto next;
vp9_iwht4x4_add(BLOCK_OFFSET(pd->dqcoeff, block), dst, dst_stride,
p->eobs[block]);
} else {
int64_t unused;
const TX_TYPE tx_type = get_tx_type_4x4(PLANE_TYPE_Y, xd, block);
const scan_order *so = &vp9_scan_orders[TX_4X4][tx_type];
const int coeff_ctx =
combine_entropy_contexts(tempa[idx], templ[idy]);
vp9_fht4x4(src_diff, coeff, 8, tx_type);
vp9_regular_quantize_b_4x4(x, 0, block, so->scan, so->iscan);
ratey += cost_coeffs(x, 0, block, TX_4X4, coeff_ctx, so->scan,
so->neighbors, cpi->sf.use_fast_coef_costing);
tempa[idx] = templ[idy] = (x->plane[0].eobs[block] > 0) ? 1 : 0;
distortion += vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, block),
16, &unused) >>
2;
if (RDCOST(x->rdmult, x->rddiv, ratey, distortion) >= best_rd)
goto next;
vp9_iht4x4_add(tx_type, BLOCK_OFFSET(pd->dqcoeff, block), dst,
dst_stride, p->eobs[block]);
}
}
}
rate += ratey;
this_rd = RDCOST(x->rdmult, x->rddiv, rate, distortion);
if (this_rd < best_rd) {
*bestrate = rate;
*bestratey = ratey;
*bestdistortion = distortion;
best_rd = this_rd;
*best_mode = mode;
memcpy(a, tempa, num_4x4_blocks_wide * sizeof(tempa[0]));
memcpy(l, templ, num_4x4_blocks_high * sizeof(templ[0]));
for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
memcpy(best_dst + idy * 8, dst_init + idy * dst_stride,
num_4x4_blocks_wide * 4);
}
next : {}
}
if (best_rd >= rd_thresh || x->skip_encode) return best_rd;
for (idy = 0; idy < num_4x4_blocks_high * 4; ++idy)
memcpy(dst_init + idy * dst_stride, best_dst + idy * 8,
num_4x4_blocks_wide * 4);
return best_rd;
}
static int64_t rd_pick_intra_sub_8x8_y_mode(VP9_COMP *cpi, MACROBLOCK *mb,
int *rate, int *rate_y,
int64_t *distortion,
int64_t best_rd) {
int i, j;
const MACROBLOCKD *const xd = &mb->e_mbd;
MODE_INFO *const mic = xd->mi[0];
const MODE_INFO *above_mi = xd->above_mi;
const MODE_INFO *left_mi = xd->left_mi;
const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
int idx, idy;
int cost = 0;
int64_t total_distortion = 0;
int tot_rate_y = 0;
int64_t total_rd = 0;
const int *bmode_costs = cpi->mbmode_cost;
// Pick modes for each sub-block (of size 4x4, 4x8, or 8x4) in an 8x8 block.
for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
PREDICTION_MODE best_mode = DC_PRED;
int r = INT_MAX, ry = INT_MAX;
int64_t d = INT64_MAX, this_rd = INT64_MAX;
i = idy * 2 + idx;
if (cpi->common.frame_type == KEY_FRAME) {
const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, i);
const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, i);
bmode_costs = cpi->y_mode_costs[A][L];
}
this_rd = rd_pick_intra4x4block(
cpi, mb, idy, idx, &best_mode, bmode_costs,
xd->plane[0].above_context + idx, xd->plane[0].left_context + idy, &r,
&ry, &d, bsize, best_rd - total_rd);
if (this_rd >= best_rd - total_rd) return INT64_MAX;
total_rd += this_rd;
cost += r;
total_distortion += d;
tot_rate_y += ry;
mic->bmi[i].as_mode = best_mode;
for (j = 1; j < num_4x4_blocks_high; ++j)
mic->bmi[i + j * 2].as_mode = best_mode;
for (j = 1; j < num_4x4_blocks_wide; ++j)
mic->bmi[i + j].as_mode = best_mode;
if (total_rd >= best_rd) return INT64_MAX;
}
}
*rate = cost;
*rate_y = tot_rate_y;
*distortion = total_distortion;
mic->mode = mic->bmi[3].as_mode;
return RDCOST(mb->rdmult, mb->rddiv, cost, total_distortion);
}
// This function is used only for intra_only frames
static int64_t rd_pick_intra_sby_mode(VP9_COMP *cpi, MACROBLOCK *x, int *rate,
int *rate_tokenonly, int64_t *distortion,
int *skippable, BLOCK_SIZE bsize,
int64_t best_rd) {
PREDICTION_MODE mode;
PREDICTION_MODE mode_selected = DC_PRED;
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mic = xd->mi[0];
int this_rate, this_rate_tokenonly, s;
int64_t this_distortion, this_rd;
TX_SIZE best_tx = TX_4X4;
int *bmode_costs;
const MODE_INFO *above_mi = xd->above_mi;
const MODE_INFO *left_mi = xd->left_mi;
const PREDICTION_MODE A = vp9_above_block_mode(mic, above_mi, 0);
const PREDICTION_MODE L = vp9_left_block_mode(mic, left_mi, 0);
bmode_costs = cpi->y_mode_costs[A][L];
memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
/* Y Search for intra prediction mode */
for (mode = DC_PRED; mode <= TM_PRED; mode++) {
if (cpi->sf.use_nonrd_pick_mode) {
// These speed features are turned on in hybrid non-RD and RD mode
// for key frame coding in the context of real-time setting.
if (conditional_skipintra(mode, mode_selected)) continue;
if (*skippable) break;
}
mic->mode = mode;
super_block_yrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s, NULL,
bsize, best_rd, /*recon = */ 0);
if (this_rate_tokenonly == INT_MAX) continue;
this_rate = this_rate_tokenonly + bmode_costs[mode];
this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
if (this_rd < best_rd) {
mode_selected = mode;
best_rd = this_rd;
best_tx = mic->tx_size;
*rate = this_rate;
*rate_tokenonly = this_rate_tokenonly;
*distortion = this_distortion;
*skippable = s;
}
}
mic->mode = mode_selected;
mic->tx_size = best_tx;
return best_rd;
}
// Return value 0: early termination triggered, no valid rd cost available;
// 1: rd cost values are valid.
static int super_block_uvrd(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
int64_t *distortion, int *skippable, int64_t *sse,
BLOCK_SIZE bsize, int64_t ref_best_rd) {
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
const TX_SIZE uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
int plane;
int pnrate = 0, pnskip = 1;
int64_t pndist = 0, pnsse = 0;
int is_cost_valid = 1;
if (ref_best_rd < 0) is_cost_valid = 0;
if (is_inter_block(mi) && is_cost_valid) {
int plane;
for (plane = 1; plane < MAX_MB_PLANE; ++plane)
vp9_subtract_plane(x, bsize, plane);
}
*rate = 0;
*distortion = 0;
*sse = 0;
*skippable = 1;
for (plane = 1; plane < MAX_MB_PLANE; ++plane) {
txfm_rd_in_plane(cpi, x, &pnrate, &pndist, &pnskip, &pnsse, ref_best_rd,
plane, bsize, uv_tx_size, cpi->sf.use_fast_coef_costing,
/*recon = */ 0);
if (pnrate == INT_MAX) {
is_cost_valid = 0;
break;
}
*rate += pnrate;
*distortion += pndist;
*sse += pnsse;
*skippable &= pnskip;
}
if (!is_cost_valid) {
// reset cost value
*rate = INT_MAX;
*distortion = INT64_MAX;
*sse = INT64_MAX;
*skippable = 0;
}
return is_cost_valid;
}
static int64_t rd_pick_intra_sbuv_mode(VP9_COMP *cpi, MACROBLOCK *x,
PICK_MODE_CONTEXT *ctx, int *rate,
int *rate_tokenonly, int64_t *distortion,
int *skippable, BLOCK_SIZE bsize,
TX_SIZE max_tx_size) {
MACROBLOCKD *xd = &x->e_mbd;
PREDICTION_MODE mode;
PREDICTION_MODE mode_selected = DC_PRED;
int64_t best_rd = INT64_MAX, this_rd;
int this_rate_tokenonly, this_rate, s;
int64_t this_distortion, this_sse;
memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
for (mode = DC_PRED; mode <= TM_PRED; ++mode) {
if (!(cpi->sf.intra_uv_mode_mask[max_tx_size] & (1 << mode))) continue;
#if CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
if ((xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) &&
(xd->above_mi == NULL || xd->left_mi == NULL) && need_top_left[mode])
continue;
#endif // CONFIG_BETTER_HW_COMPATIBILITY && CONFIG_VP9_HIGHBITDEPTH
xd->mi[0]->uv_mode = mode;
if (!super_block_uvrd(cpi, x, &this_rate_tokenonly, &this_distortion, &s,
&this_sse, bsize, best_rd))
continue;
this_rate =
this_rate_tokenonly +
cpi->intra_uv_mode_cost[cpi->common.frame_type][xd->mi[0]->mode][mode];
this_rd = RDCOST(x->rdmult, x->rddiv, this_rate, this_distortion);
if (this_rd < best_rd) {
mode_selected = mode;
best_rd = this_rd;
*rate = this_rate;
*rate_tokenonly = this_rate_tokenonly;
*distortion = this_distortion;
*skippable = s;
if (!x->select_tx_size) swap_block_ptr(x, ctx, 2, 0, 1, MAX_MB_PLANE);
}
}
xd->mi[0]->uv_mode = mode_selected;
return best_rd;
}
#if !CONFIG_REALTIME_ONLY
static int64_t rd_sbuv_dcpred(const VP9_COMP *cpi, MACROBLOCK *x, int *rate,
int *rate_tokenonly, int64_t *distortion,
int *skippable, BLOCK_SIZE bsize) {
const VP9_COMMON *cm = &cpi->common;
int64_t unused;
x->e_mbd.mi[0]->uv_mode = DC_PRED;
memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
super_block_uvrd(cpi, x, rate_tokenonly, distortion, skippable, &unused,
bsize, INT64_MAX);
*rate =
*rate_tokenonly +
cpi->intra_uv_mode_cost[cm->frame_type][x->e_mbd.mi[0]->mode][DC_PRED];
return RDCOST(x->rdmult, x->rddiv, *rate, *distortion);
}
static void choose_intra_uv_mode(VP9_COMP *cpi, MACROBLOCK *const x,
PICK_MODE_CONTEXT *ctx, BLOCK_SIZE bsize,
TX_SIZE max_tx_size, int *rate_uv,
int *rate_uv_tokenonly, int64_t *dist_uv,
int *skip_uv, PREDICTION_MODE *mode_uv) {
// Use an estimated rd for uv_intra based on DC_PRED if the
// appropriate speed flag is set.
if (cpi->sf.use_uv_intra_rd_estimate) {
rd_sbuv_dcpred(cpi, x, rate_uv, rate_uv_tokenonly, dist_uv, skip_uv,
bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize);
// Else do a proper rd search for each possible transform size that may
// be considered in the main rd loop.
} else {
rd_pick_intra_sbuv_mode(cpi, x, ctx, rate_uv, rate_uv_tokenonly, dist_uv,
skip_uv, bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
max_tx_size);
}
*mode_uv = x->e_mbd.mi[0]->uv_mode;
}
static int cost_mv_ref(const VP9_COMP *cpi, PREDICTION_MODE mode,
int mode_context) {
assert(is_inter_mode(mode));
return cpi->inter_mode_cost[mode_context][INTER_OFFSET(mode)];
}
static int set_and_cost_bmi_mvs(VP9_COMP *cpi, MACROBLOCK *x, MACROBLOCKD *xd,
int i, PREDICTION_MODE mode, int_mv this_mv[2],
int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
int_mv seg_mvs[MAX_REF_FRAMES],
int_mv *best_ref_mv[2], const int *mvjcost,
int *mvcost[2]) {
MODE_INFO *const mi = xd->mi[0];
const MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
int thismvcost = 0;
int idx, idy;
const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[mi->sb_type];
const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[mi->sb_type];
const int is_compound = has_second_ref(mi);
switch (mode) {
case NEWMV:
this_mv[0].as_int = seg_mvs[mi->ref_frame[0]].as_int;
thismvcost += vp9_mv_bit_cost(&this_mv[0].as_mv, &best_ref_mv[0]->as_mv,
mvjcost, mvcost, MV_COST_WEIGHT_SUB);
if (is_compound) {
this_mv[1].as_int = seg_mvs[mi->ref_frame[1]].as_int;
thismvcost += vp9_mv_bit_cost(&this_mv[1].as_mv, &best_ref_mv[1]->as_mv,
mvjcost, mvcost, MV_COST_WEIGHT_SUB);
}
break;
case NEARMV:
case NEARESTMV:
this_mv[0].as_int = frame_mv[mode][mi->ref_frame[0]].as_int;
if (is_compound)
this_mv[1].as_int = frame_mv[mode][mi->ref_frame[1]].as_int;
break;
default:
assert(mode == ZEROMV);
this_mv[0].as_int = 0;
if (is_compound) this_mv[1].as_int = 0;
break;
}
mi->bmi[i].as_mv[0].as_int = this_mv[0].as_int;
if (is_compound) mi->bmi[i].as_mv[1].as_int = this_mv[1].as_int;
mi->bmi[i].as_mode = mode;
for (idy = 0; idy < num_4x4_blocks_high; ++idy)
for (idx = 0; idx < num_4x4_blocks_wide; ++idx)
memmove(&mi->bmi[i + idy * 2 + idx], &mi->bmi[i], sizeof(mi->bmi[i]));
return cost_mv_ref(cpi, mode, mbmi_ext->mode_context[mi->ref_frame[0]]) +
thismvcost;
}
static int64_t encode_inter_mb_segment(VP9_COMP *cpi, MACROBLOCK *x,
int64_t best_yrd, int i, int *labelyrate,
int64_t *distortion, int64_t *sse,
ENTROPY_CONTEXT *ta, ENTROPY_CONTEXT *tl,
int mi_row, int mi_col) {
int k;
MACROBLOCKD *xd = &x->e_mbd;
struct macroblockd_plane *const pd = &xd->plane[0];
struct macroblock_plane *const p = &x->plane[0];
MODE_INFO *const mi = xd->mi[0];
const BLOCK_SIZE plane_bsize = get_plane_block_size(mi->sb_type, pd);
const int width = 4 * num_4x4_blocks_wide_lookup[plane_bsize];
const int height = 4 * num_4x4_blocks_high_lookup[plane_bsize];
int idx, idy;
const uint8_t *const src =
&p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
uint8_t *const dst =
&pd->dst.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->dst.stride)];
int64_t thisdistortion = 0, thissse = 0;
int thisrate = 0, ref;
const scan_order *so = &vp9_default_scan_orders[TX_4X4];
const int is_compound = has_second_ref(mi);
const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
for (ref = 0; ref < 1 + is_compound; ++ref) {
const int bw = b_width_log2_lookup[BLOCK_8X8];
const int h = 4 * (i >> bw);
const int w = 4 * (i & ((1 << bw) - 1));
const struct scale_factors *sf = &xd->block_refs[ref]->sf;
int y_stride = pd->pre[ref].stride;
uint8_t *pre = pd->pre[ref].buf + (h * pd->pre[ref].stride + w);
if (vp9_is_scaled(sf)) {
const int x_start = (-xd->mb_to_left_edge >> (3 + pd->subsampling_x));
const int y_start = (-xd->mb_to_top_edge >> (3 + pd->subsampling_y));
y_stride = xd->block_refs[ref]->buf->y_stride;
pre = xd->block_refs[ref]->buf->y_buffer;
pre += scaled_buffer_offset(x_start + w, y_start + h, y_stride, sf);
}
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
vp9_highbd_build_inter_predictor(
CONVERT_TO_SHORTPTR(pre), y_stride, CONVERT_TO_SHORTPTR(dst),
pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
&xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2),
xd->bd);
} else {
vp9_build_inter_predictor(
pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
&xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
}
#else
vp9_build_inter_predictor(
pre, y_stride, dst, pd->dst.stride, &mi->bmi[i].as_mv[ref].as_mv,
&xd->block_refs[ref]->sf, width, height, ref, kernel, MV_PRECISION_Q3,
mi_col * MI_SIZE + 4 * (i % 2), mi_row * MI_SIZE + 4 * (i / 2));
#endif // CONFIG_VP9_HIGHBITDEPTH
}
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
vpx_highbd_subtract_block(
height, width, vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
8, src, p->src.stride, dst, pd->dst.stride, xd->bd);
} else {
vpx_subtract_block(height, width,
vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
8, src, p->src.stride, dst, pd->dst.stride);
}
#else
vpx_subtract_block(height, width,
vp9_raster_block_offset_int16(BLOCK_8X8, i, p->src_diff),
8, src, p->src.stride, dst, pd->dst.stride);
#endif // CONFIG_VP9_HIGHBITDEPTH
k = i;
for (idy = 0; idy < height / 4; ++idy) {
for (idx = 0; idx < width / 4; ++idx) {
#if CONFIG_VP9_HIGHBITDEPTH
const int bd = (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) ? xd->bd : 8;
#endif
int64_t ssz, rd, rd1, rd2;
tran_low_t *coeff;
int coeff_ctx;
k += (idy * 2 + idx);
coeff_ctx = combine_entropy_contexts(ta[k & 1], tl[k >> 1]);
coeff = BLOCK_OFFSET(p->coeff, k);
x->fwd_txfm4x4(vp9_raster_block_offset_int16(BLOCK_8X8, k, p->src_diff),
coeff, 8);
vp9_regular_quantize_b_4x4(x, 0, k, so->scan, so->iscan);
#if CONFIG_VP9_HIGHBITDEPTH
thisdistortion += vp9_highbd_block_error_dispatch(
coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz, bd);
#else
thisdistortion +=
vp9_block_error(coeff, BLOCK_OFFSET(pd->dqcoeff, k), 16, &ssz);
#endif // CONFIG_VP9_HIGHBITDEPTH
thissse += ssz;
thisrate += cost_coeffs(x, 0, k, TX_4X4, coeff_ctx, so->scan,
so->neighbors, cpi->sf.use_fast_coef_costing);
ta[k & 1] = tl[k >> 1] = (x->plane[0].eobs[k] > 0) ? 1 : 0;
rd1 = RDCOST(x->rdmult, x->rddiv, thisrate, thisdistortion >> 2);
rd2 = RDCOST(x->rdmult, x->rddiv, 0, thissse >> 2);
rd = VPXMIN(rd1, rd2);
if (rd >= best_yrd) return INT64_MAX;
}
}
*distortion = thisdistortion >> 2;
*labelyrate = thisrate;
*sse = thissse >> 2;
return RDCOST(x->rdmult, x->rddiv, *labelyrate, *distortion);
}
#endif // !CONFIG_REALTIME_ONLY
typedef struct {
int eobs;
int brate;
int byrate;
int64_t bdist;
int64_t bsse;
int64_t brdcost;
int_mv mvs[2];
ENTROPY_CONTEXT ta[2];
ENTROPY_CONTEXT tl[2];
} SEG_RDSTAT;
typedef struct {
int_mv *ref_mv[2];
int_mv mvp;
int64_t segment_rd;
int r;
int64_t d;
int64_t sse;
int segment_yrate;
PREDICTION_MODE modes[4];
SEG_RDSTAT rdstat[4][INTER_MODES];
int mvthresh;
} BEST_SEG_INFO;
#if !CONFIG_REALTIME_ONLY
static INLINE int mv_check_bounds(const MvLimits *mv_limits, const MV *mv) {
return (mv->row >> 3) < mv_limits->row_min ||
(mv->row >> 3) > mv_limits->row_max ||
(mv->col >> 3) < mv_limits->col_min ||
(mv->col >> 3) > mv_limits->col_max;
}
static INLINE void mi_buf_shift(MACROBLOCK *x, int i) {
MODE_INFO *const mi = x->e_mbd.mi[0];
struct macroblock_plane *const p = &x->plane[0];
struct macroblockd_plane *const pd = &x->e_mbd.plane[0];
p->src.buf =
&p->src.buf[vp9_raster_block_offset(BLOCK_8X8, i, p->src.stride)];
assert(((intptr_t)pd->pre[0].buf & 0x7) == 0);
pd->pre[0].buf =
&pd->pre[0].buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[0].stride)];
if (has_second_ref(mi))
pd->pre[1].buf =
&pd->pre[1]
.buf[vp9_raster_block_offset(BLOCK_8X8, i, pd->pre[1].stride)];
}
static INLINE void mi_buf_restore(MACROBLOCK *x, struct buf_2d orig_src,
struct buf_2d orig_pre[2]) {
MODE_INFO *mi = x->e_mbd.mi[0];
x->plane[0].src = orig_src;
x->e_mbd.plane[0].pre[0] = orig_pre[0];
if (has_second_ref(mi)) x->e_mbd.plane[0].pre[1] = orig_pre[1];
}
static INLINE int mv_has_subpel(const MV *mv) {
return (mv->row & 0x0F) || (mv->col & 0x0F);
}
// Check if NEARESTMV/NEARMV/ZEROMV is the cheapest way encode zero motion.
// TODO(aconverse): Find out if this is still productive then clean up or remove
static int check_best_zero_mv(const VP9_COMP *cpi,
const uint8_t mode_context[MAX_REF_FRAMES],
int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES],
int this_mode,
const MV_REFERENCE_FRAME ref_frames[2]) {
if ((this_mode == NEARMV || this_mode == NEARESTMV || this_mode == ZEROMV) &&
frame_mv[this_mode][ref_frames[0]].as_int == 0 &&
(ref_frames[1] == NONE ||
frame_mv[this_mode][ref_frames[1]].as_int == 0)) {
int rfc = mode_context[ref_frames[0]];
int c1 = cost_mv_ref(cpi, NEARMV, rfc);
int c2 = cost_mv_ref(cpi, NEARESTMV, rfc);
int c3 = cost_mv_ref(cpi, ZEROMV, rfc);
if (this_mode == NEARMV) {
if (c1 > c3) return 0;
} else if (this_mode == NEARESTMV) {
if (c2 > c3) return 0;
} else {
assert(this_mode == ZEROMV);
if (ref_frames[1] == NONE) {
if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0) ||
(c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0))
return 0;
} else {
if ((c3 >= c2 && frame_mv[NEARESTMV][ref_frames[0]].as_int == 0 &&
frame_mv[NEARESTMV][ref_frames[1]].as_int == 0) ||
(c3 >= c1 && frame_mv[NEARMV][ref_frames[0]].as_int == 0 &&
frame_mv[NEARMV][ref_frames[1]].as_int == 0))
return 0;
}
}
}
return 1;
}
static void joint_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
int_mv *frame_mv, int mi_row, int mi_col,
int_mv single_newmv[MAX_REF_FRAMES],
int *rate_mv) {
const VP9_COMMON *const cm = &cpi->common;
const int pw = 4 * num_4x4_blocks_wide_lookup[bsize];
const int ph = 4 * num_4x4_blocks_high_lookup[bsize];
MACROBLOCKD *xd = &x->e_mbd;
MODE_INFO *mi = xd->mi[0];
const int refs[2] = { mi->ref_frame[0],
mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1] };
int_mv ref_mv[2];
int ite, ref;
const InterpKernel *kernel = vp9_filter_kernels[mi->interp_filter];
struct scale_factors sf;
// Do joint motion search in compound mode to get more accurate mv.
struct buf_2d backup_yv12[2][MAX_MB_PLANE];
uint32_t last_besterr[2] = { UINT_MAX, UINT_MAX };
const YV12_BUFFER_CONFIG *const scaled_ref_frame[2] = {
vp9_get_scaled_ref_frame(cpi, mi->ref_frame[0]),
vp9_get_scaled_ref_frame(cpi, mi->ref_frame[1])
};
// Prediction buffer from second frame.
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, second_pred_alloc_16[64 * 64]);
uint8_t *second_pred;
#else
DECLARE_ALIGNED(16, uint8_t, second_pred[64 * 64]);
#endif // CONFIG_VP9_HIGHBITDEPTH
for (ref = 0; ref < 2; ++ref) {
ref_mv[ref] = x->mbmi_ext->ref_mvs[refs[ref]][0];
if (scaled_ref_frame[ref]) {
int i;
// Swap out the reference frame for a version that's been scaled to
// match the resolution of the current frame, allowing the existing
// motion search code to be used without additional modifications.
for (i = 0; i < MAX_MB_PLANE; i++)
backup_yv12[ref][i] = xd->plane[i].pre[ref];
vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
NULL);
}
frame_mv[refs[ref]].as_int = single_newmv[refs[ref]].as_int;
}
// Since we have scaled the reference frames to match the size of the current
// frame we must use a unit scaling factor during mode selection.
#if CONFIG_VP9_HIGHBITDEPTH
vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
cm->height, cm->use_highbitdepth);
#else
vp9_setup_scale_factors_for_frame(&sf, cm->width, cm->height, cm->width,
cm->height);
#endif // CONFIG_VP9_HIGHBITDEPTH
// Allow joint search multiple times iteratively for each reference frame
// and break out of the search loop if it couldn't find a better mv.
for (ite = 0; ite < 4; ite++) {
struct buf_2d ref_yv12[2];
uint32_t bestsme = UINT_MAX;
int sadpb = x->sadperbit16;
MV tmp_mv;
int search_range = 3;
const MvLimits tmp_mv_limits = x->mv_limits;
int id = ite % 2; // Even iterations search in the first reference frame,
// odd iterations search in the second. The predictor
// found for the 'other' reference frame is factored in.
// Initialized here because of compiler problem in Visual Studio.
ref_yv12[0] = xd->plane[0].pre[0];
ref_yv12[1] = xd->plane[0].pre[1];
// Get the prediction block from the 'other' reference frame.
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
second_pred = CONVERT_TO_BYTEPTR(second_pred_alloc_16);
vp9_highbd_build_inter_predictor(
CONVERT_TO_SHORTPTR(ref_yv12[!id].buf), ref_yv12[!id].stride,
second_pred_alloc_16, pw, &frame_mv[refs[!id]].as_mv, &sf, pw, ph, 0,
kernel, MV_PRECISION_Q3, mi_col * MI_SIZE, mi_row * MI_SIZE, xd->bd);
} else {
second_pred = (uint8_t *)second_pred_alloc_16;
vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
second_pred, pw, &frame_mv[refs[!id]].as_mv,
&sf, pw, ph, 0, kernel, MV_PRECISION_Q3,
mi_col * MI_SIZE, mi_row * MI_SIZE);
}
#else
vp9_build_inter_predictor(ref_yv12[!id].buf, ref_yv12[!id].stride,
second_pred, pw, &frame_mv[refs[!id]].as_mv, &sf,
pw, ph, 0, kernel, MV_PRECISION_Q3,
mi_col * MI_SIZE, mi_row * MI_SIZE);
#endif // CONFIG_VP9_HIGHBITDEPTH
// Do compound motion search on the current reference frame.
if (id) xd->plane[0].pre[0] = ref_yv12[id];
vp9_set_mv_search_range(&x->mv_limits, &ref_mv[id].as_mv);
// Use the mv result from the single mode as mv predictor.
tmp_mv = frame_mv[refs[id]].as_mv;
tmp_mv.col >>= 3;
tmp_mv.row >>= 3;
// Small-range full-pixel motion search.
bestsme = vp9_refining_search_8p_c(x, &tmp_mv, sadpb, search_range,
&cpi->fn_ptr[bsize], &ref_mv[id].as_mv,
second_pred);
if (bestsme < UINT_MAX)
bestsme = vp9_get_mvpred_av_var(x, &tmp_mv, &ref_mv[id].as_mv,
second_pred, &cpi->fn_ptr[bsize], 1);
x->mv_limits = tmp_mv_limits;
if (bestsme < UINT_MAX) {
uint32_t dis; /* TODO: use dis in distortion calculation later. */
uint32_t sse;
bestsme = cpi->find_fractional_mv_step(
x, &tmp_mv, &ref_mv[id].as_mv, cpi->common.allow_high_precision_mv,
x->errorperbit, &cpi->fn_ptr[bsize], 0,
cpi->sf.mv.subpel_search_level, NULL, x->nmvjointcost, x->mvcost,
&dis, &sse, second_pred, pw, ph, cpi->sf.use_accurate_subpel_search);
}
// Restore the pointer to the first (possibly scaled) prediction buffer.
if (id) xd->plane[0].pre[0] = ref_yv12[0];
if (bestsme < last_besterr[id]) {
frame_mv[refs[id]].as_mv = tmp_mv;
last_besterr[id] = bestsme;
} else {
break;
}
}
*rate_mv = 0;
for (ref = 0; ref < 2; ++ref) {
if (scaled_ref_frame[ref]) {
// Restore the prediction frame pointers to their unscaled versions.
int i;
for (i = 0; i < MAX_MB_PLANE; i++)
xd->plane[i].pre[ref] = backup_yv12[ref][i];
}
*rate_mv += vp9_mv_bit_cost(&frame_mv[refs[ref]].as_mv,
&x->mbmi_ext->ref_mvs[refs[ref]][0].as_mv,
x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
}
}
static int64_t rd_pick_best_sub8x8_mode(
VP9_COMP *cpi, MACROBLOCK *x, int_mv *best_ref_mv,
int_mv *second_best_ref_mv, int64_t best_rd, int *returntotrate,
int *returnyrate, int64_t *returndistortion, int *skippable, int64_t *psse,
int mvthresh, int_mv seg_mvs[4][MAX_REF_FRAMES], BEST_SEG_INFO *bsi_buf,
int filter_idx, int mi_row, int mi_col) {
int i;
BEST_SEG_INFO *bsi = bsi_buf + filter_idx;
MACROBLOCKD *xd = &x->e_mbd;
MODE_INFO *mi = xd->mi[0];
int mode_idx;
int k, br = 0, idx, idy;
int64_t bd = 0, block_sse = 0;
PREDICTION_MODE this_mode;
VP9_COMMON *cm = &cpi->common;
struct macroblock_plane *const p = &x->plane[0];
struct macroblockd_plane *const pd = &xd->plane[0];
const int label_count = 4;
int64_t this_segment_rd = 0;
int label_mv_thresh;
int segmentyrate = 0;
const BLOCK_SIZE bsize = mi->sb_type;
const int num_4x4_blocks_wide = num_4x4_blocks_wide_lookup[bsize];
const int num_4x4_blocks_high = num_4x4_blocks_high_lookup[bsize];
const int pw = num_4x4_blocks_wide << 2;
const int ph = num_4x4_blocks_high << 2;
ENTROPY_CONTEXT t_above[2], t_left[2];
int subpelmv = 1, have_ref = 0;
SPEED_FEATURES *const sf = &cpi->sf;
const int has_second_rf = has_second_ref(mi);
const int inter_mode_mask = sf->inter_mode_mask[bsize];
MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
vp9_zero(*bsi);
bsi->segment_rd = best_rd;
bsi->ref_mv[0] = best_ref_mv;
bsi->ref_mv[1] = second_best_ref_mv;
bsi->mvp.as_int = best_ref_mv->as_int;
bsi->mvthresh = mvthresh;
for (i = 0; i < 4; i++) bsi->modes[i] = ZEROMV;
memcpy(t_above, pd->above_context, sizeof(t_above));
memcpy(t_left, pd->left_context, sizeof(t_left));
// 64 makes this threshold really big effectively
// making it so that we very rarely check mvs on
// segments. setting this to 1 would make mv thresh
// roughly equal to what it is for macroblocks
label_mv_thresh = 1 * bsi->mvthresh / label_count;
// Segmentation method overheads
for (idy = 0; idy < 2; idy += num_4x4_blocks_high) {
for (idx = 0; idx < 2; idx += num_4x4_blocks_wide) {
// TODO(jingning,rbultje): rewrite the rate-distortion optimization
// loop for 4x4/4x8/8x4 block coding. to be replaced with new rd loop
int_mv mode_mv[MB_MODE_COUNT][2];
int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
PREDICTION_MODE mode_selected = ZEROMV;
int64_t best_rd = INT64_MAX;
const int i = idy * 2 + idx;
int ref;
for (ref = 0; ref < 1 + has_second_rf; ++ref) {
const MV_REFERENCE_FRAME frame = mi->ref_frame[ref];
frame_mv[ZEROMV][frame].as_int = 0;
vp9_append_sub8x8_mvs_for_idx(
cm, xd, i, ref, mi_row, mi_col, &frame_mv[NEARESTMV][frame],
&frame_mv[NEARMV][frame], mbmi_ext->mode_context);
}
// search for the best motion vector on this segment
for (this_mode = NEARESTMV; this_mode <= NEWMV; ++this_mode) {
const struct buf_2d orig_src = x->plane[0].src;
struct buf_2d orig_pre[2];
mode_idx = INTER_OFFSET(this_mode);
bsi->rdstat[i][mode_idx].brdcost = INT64_MAX;
if (!(inter_mode_mask & (1 << this_mode))) continue;
if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv,
this_mode, mi->ref_frame))
continue;
memcpy(orig_pre, pd->pre, sizeof(orig_pre));
memcpy(bsi->rdstat[i][mode_idx].ta, t_above,
sizeof(bsi->rdstat[i][mode_idx].ta));
memcpy(bsi->rdstat[i][mode_idx].tl, t_left,
sizeof(bsi->rdstat[i][mode_idx].tl));
// motion search for newmv (single predictor case only)
if (!has_second_rf && this_mode == NEWMV &&
seg_mvs[i][mi->ref_frame[0]].as_int == INVALID_MV) {
MV *const new_mv = &mode_mv[NEWMV][0].as_mv;
int step_param = 0;
uint32_t bestsme = UINT_MAX;
int sadpb = x->sadperbit4;
MV mvp_full;
int max_mv;
int cost_list[5];
const MvLimits tmp_mv_limits = x->mv_limits;
/* Is the best so far sufficiently good that we cant justify doing
* and new motion search. */
if (best_rd < label_mv_thresh) break;
if (cpi->oxcf.mode != BEST) {
// use previous block's result as next block's MV predictor.
if (i > 0) {
bsi->mvp.as_int = mi->bmi[i - 1].as_mv[0].as_int;
if (i == 2) bsi->mvp.as_int = mi->bmi[i - 2].as_mv[0].as_int;
}
}
if (i == 0)
max_mv = x->max_mv_context[mi->ref_frame[0]];
else
max_mv =
VPXMAX(abs(bsi->mvp.as_mv.row), abs(bsi->mvp.as_mv.col)) >> 3;
if (sf->mv.auto_mv_step_size && cm->show_frame) {
// Take wtd average of the step_params based on the last frame's
// max mv magnitude and the best ref mvs of the current block for
// the given reference.
step_param =
(vp9_init_search_range(max_mv) + cpi->mv_step_param) / 2;
} else {
step_param = cpi->mv_step_param;
}
mvp_full.row = bsi->mvp.as_mv.row >> 3;
mvp_full.col = bsi->mvp.as_mv.col >> 3;
if (sf->adaptive_motion_search) {
if (x->pred_mv[mi->ref_frame[0]].row != INT16_MAX &&
x->pred_mv[mi->ref_frame[0]].col != INT16_MAX) {
mvp_full.row = x->pred_mv[mi->ref_frame[0]].row >> 3;
mvp_full.col = x->pred_mv[mi->ref_frame[0]].col >> 3;
}
step_param = VPXMAX(step_param, 8);
}
// adjust src pointer for this block
mi_buf_shift(x, i);
vp9_set_mv_search_range(&x->mv_limits, &bsi->ref_mv[0]->as_mv);
bestsme = vp9_full_pixel_search(
cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method,
sadpb,
sf->mv.subpel_search_method != SUBPEL_TREE ? cost_list : NULL,
&bsi->ref_mv[0]->as_mv, new_mv, INT_MAX, 1);
x->mv_limits = tmp_mv_limits;
if (bestsme < UINT_MAX) {
uint32_t distortion;
cpi->find_fractional_mv_step(
x, new_mv, &bsi->ref_mv[0]->as_mv, cm->allow_high_precision_mv,
x->errorperbit, &cpi->fn_ptr[bsize], sf->mv.subpel_force_stop,
sf->mv.subpel_search_level, cond_cost_list(cpi, cost_list),
x->nmvjointcost, x->mvcost, &distortion,
&x->pred_sse[mi->ref_frame[0]], NULL, pw, ph,
cpi->sf.use_accurate_subpel_search);
// save motion search result for use in compound prediction
seg_mvs[i][mi->ref_frame[0]].as_mv = *new_mv;
}
x->pred_mv[mi->ref_frame[0]] = *new_mv;
// restore src pointers
mi_buf_restore(x, orig_src, orig_pre);
}
if (has_second_rf) {
if (seg_mvs[i][mi->ref_frame[1]].as_int == INVALID_MV ||
seg_mvs[i][mi->ref_frame[0]].as_int == INVALID_MV)
continue;
}
if (has_second_rf && this_mode == NEWMV &&
mi->interp_filter == EIGHTTAP) {
// adjust src pointers
mi_buf_shift(x, i);
if (sf->comp_inter_joint_search_thresh <= bsize) {
int rate_mv;
joint_motion_search(cpi, x, bsize, frame_mv[this_mode], mi_row,
mi_col, seg_mvs[i], &rate_mv);
seg_mvs[i][mi->ref_frame[0]].as_int =
frame_mv[this_mode][mi->ref_frame[0]].as_int;
seg_mvs[i][mi->ref_frame[1]].as_int =
frame_mv[this_mode][mi->ref_frame[1]].as_int;
}
// restore src pointers
mi_buf_restore(x, orig_src, orig_pre);
}
bsi->rdstat[i][mode_idx].brate = set_and_cost_bmi_mvs(
cpi, x, xd, i, this_mode, mode_mv[this_mode], frame_mv, seg_mvs[i],
bsi->ref_mv, x->nmvjointcost, x->mvcost);
for (ref = 0; ref < 1 + has_second_rf; ++ref) {
bsi->rdstat[i][mode_idx].mvs[ref].as_int =
mode_mv[this_mode][ref].as_int;
if (num_4x4_blocks_wide > 1)
bsi->rdstat[i + 1][mode_idx].mvs[ref].as_int =
mode_mv[this_mode][ref].as_int;
if (num_4x4_blocks_high > 1)
bsi->rdstat[i + 2][mode_idx].mvs[ref].as_int =
mode_mv[this_mode][ref].as_int;
}
// Trap vectors that reach beyond the UMV borders
if (mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][0].as_mv) ||
(has_second_rf &&
mv_check_bounds(&x->mv_limits, &mode_mv[this_mode][1].as_mv)))
continue;
if (filter_idx > 0) {
BEST_SEG_INFO *ref_bsi = bsi_buf;
subpelmv = 0;
have_ref = 1;
for (ref = 0; ref < 1 + has_second_rf; ++ref) {
subpelmv |= mv_has_subpel(&mode_mv[this_mode][ref].as_mv);
have_ref &= mode_mv[this_mode][ref].as_int ==
ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
}
if (filter_idx > 1 && !subpelmv && !have_ref) {
ref_bsi = bsi_buf + 1;
have_ref = 1;
for (ref = 0; ref < 1 + has_second_rf; ++ref)
have_ref &= mode_mv[this_mode][ref].as_int ==
ref_bsi->rdstat[i][mode_idx].mvs[ref].as_int;
}
if (!subpelmv && have_ref &&
ref_bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
memcpy(&bsi->rdstat[i][mode_idx], &ref_bsi->rdstat[i][mode_idx],
sizeof(SEG_RDSTAT));
if (num_4x4_blocks_wide > 1)
bsi->rdstat[i + 1][mode_idx].eobs =
ref_bsi->rdstat[i + 1][mode_idx].eobs;
if (num_4x4_blocks_high > 1)
bsi->rdstat[i + 2][mode_idx].eobs =
ref_bsi->rdstat[i + 2][mode_idx].eobs;
if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
mode_selected = this_mode;
best_rd = bsi->rdstat[i][mode_idx].brdcost;
}
continue;
}
}
bsi->rdstat[i][mode_idx].brdcost = encode_inter_mb_segment(
cpi, x, bsi->segment_rd - this_segment_rd, i,
&bsi->rdstat[i][mode_idx].byrate, &bsi->rdstat[i][mode_idx].bdist,
&bsi->rdstat[i][mode_idx].bsse, bsi->rdstat[i][mode_idx].ta,
bsi->rdstat[i][mode_idx].tl, mi_row, mi_col);
if (bsi->rdstat[i][mode_idx].brdcost < INT64_MAX) {
bsi->rdstat[i][mode_idx].brdcost +=
RDCOST(x->rdmult, x->rddiv, bsi->rdstat[i][mode_idx].brate, 0);
bsi->rdstat[i][mode_idx].brate += bsi->rdstat[i][mode_idx].byrate;
bsi->rdstat[i][mode_idx].eobs = p->eobs[i];
if (num_4x4_blocks_wide > 1)
bsi->rdstat[i + 1][mode_idx].eobs = p->eobs[i + 1];
if (num_4x4_blocks_high > 1)
bsi->rdstat[i + 2][mode_idx].eobs = p->eobs[i + 2];
}
if (bsi->rdstat[i][mode_idx].brdcost < best_rd) {
mode_selected = this_mode;
best_rd = bsi->rdstat[i][mode_idx].brdcost;
}
} /*for each 4x4 mode*/
if (best_rd == INT64_MAX) {
int iy, midx;
for (iy = i + 1; iy < 4; ++iy)
for (midx = 0; midx < INTER_MODES; ++midx)
bsi->rdstat[iy][midx].brdcost = INT64_MAX;
bsi->segment_rd = INT64_MAX;
return INT64_MAX;
}
mode_idx = INTER_OFFSET(mode_selected);
memcpy(t_above, bsi->rdstat[i][mode_idx].ta, sizeof(t_above));
memcpy(t_left, bsi->rdstat[i][mode_idx].tl, sizeof(t_left));
set_and_cost_bmi_mvs(cpi, x, xd, i, mode_selected, mode_mv[mode_selected],
frame_mv, seg_mvs[i], bsi->ref_mv, x->nmvjointcost,
x->mvcost);
br += bsi->rdstat[i][mode_idx].brate;
bd += bsi->rdstat[i][mode_idx].bdist;
block_sse += bsi->rdstat[i][mode_idx].bsse;
segmentyrate += bsi->rdstat[i][mode_idx].byrate;
this_segment_rd += bsi->rdstat[i][mode_idx].brdcost;
if (this_segment_rd > bsi->segment_rd) {
int iy, midx;
for (iy = i + 1; iy < 4; ++iy)
for (midx = 0; midx < INTER_MODES; ++midx)
bsi->rdstat[iy][midx].brdcost = INT64_MAX;
bsi->segment_rd = INT64_MAX;
return INT64_MAX;
}
}
} /* for each label */
bsi->r = br;
bsi->d = bd;
bsi->segment_yrate = segmentyrate;
bsi->segment_rd = this_segment_rd;
bsi->sse = block_sse;
// update the coding decisions
for (k = 0; k < 4; ++k) bsi->modes[k] = mi->bmi[k].as_mode;
if (bsi->segment_rd > best_rd) return INT64_MAX;
/* set it to the best */
for (i = 0; i < 4; i++) {
mode_idx = INTER_OFFSET(bsi->modes[i]);
mi->bmi[i].as_mv[0].as_int = bsi->rdstat[i][mode_idx].mvs[0].as_int;
if (has_second_ref(mi))
mi->bmi[i].as_mv[1].as_int = bsi->rdstat[i][mode_idx].mvs[1].as_int;
x->plane[0].eobs[i] = bsi->rdstat[i][mode_idx].eobs;
mi->bmi[i].as_mode = bsi->modes[i];
}
/*
* used to set mbmi->mv.as_int
*/
*returntotrate = bsi->r;
*returndistortion = bsi->d;
*returnyrate = bsi->segment_yrate;
*skippable = vp9_is_skippable_in_plane(x, BLOCK_8X8, 0);
*psse = bsi->sse;
mi->mode = bsi->modes[3];
return bsi->segment_rd;
}
static void estimate_ref_frame_costs(const VP9_COMMON *cm,
const MACROBLOCKD *xd, int segment_id,
unsigned int *ref_costs_single,
unsigned int *ref_costs_comp,
vpx_prob *comp_mode_p) {
int seg_ref_active =
segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
if (seg_ref_active) {
memset(ref_costs_single, 0, MAX_REF_FRAMES * sizeof(*ref_costs_single));
memset(ref_costs_comp, 0, MAX_REF_FRAMES * sizeof(*ref_costs_comp));
*comp_mode_p = 128;
} else {
vpx_prob intra_inter_p = vp9_get_intra_inter_prob(cm, xd);
vpx_prob comp_inter_p = 128;
if (cm->reference_mode == REFERENCE_MODE_SELECT) {
comp_inter_p = vp9_get_reference_mode_prob(cm, xd);
*comp_mode_p = comp_inter_p;
} else {
*comp_mode_p = 128;
}
ref_costs_single[INTRA_FRAME] = vp9_cost_bit(intra_inter_p, 0);
if (cm->reference_mode != COMPOUND_REFERENCE) {
vpx_prob ref_single_p1 = vp9_get_pred_prob_single_ref_p1(cm, xd);
vpx_prob ref_single_p2 = vp9_get_pred_prob_single_ref_p2(cm, xd);
unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
if (cm->reference_mode == REFERENCE_MODE_SELECT)
base_cost += vp9_cost_bit(comp_inter_p, 0);
ref_costs_single[LAST_FRAME] = ref_costs_single[GOLDEN_FRAME] =
ref_costs_single[ALTREF_FRAME] = base_cost;
ref_costs_single[LAST_FRAME] += vp9_cost_bit(ref_single_p1, 0);
ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p1, 1);
ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p1, 1);
ref_costs_single[GOLDEN_FRAME] += vp9_cost_bit(ref_single_p2, 0);
ref_costs_single[ALTREF_FRAME] += vp9_cost_bit(ref_single_p2, 1);
} else {
ref_costs_single[LAST_FRAME] = 512;
ref_costs_single[GOLDEN_FRAME] = 512;
ref_costs_single[ALTREF_FRAME] = 512;
}
if (cm->reference_mode != SINGLE_REFERENCE) {
vpx_prob ref_comp_p = vp9_get_pred_prob_comp_ref_p(cm, xd);
unsigned int base_cost = vp9_cost_bit(intra_inter_p, 1);
if (cm->reference_mode == REFERENCE_MODE_SELECT)
base_cost += vp9_cost_bit(comp_inter_p, 1);
ref_costs_comp[LAST_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 0);
ref_costs_comp[GOLDEN_FRAME] = base_cost + vp9_cost_bit(ref_comp_p, 1);
} else {
ref_costs_comp[LAST_FRAME] = 512;
ref_costs_comp[GOLDEN_FRAME] = 512;
}
}
}
static void store_coding_context(
MACROBLOCK *x, PICK_MODE_CONTEXT *ctx, int mode_index,
int64_t comp_pred_diff[REFERENCE_MODES],
int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS], int skippable) {
MACROBLOCKD *const xd = &x->e_mbd;
// Take a snapshot of the coding context so it can be
// restored if we decide to encode this way
ctx->skip = x->skip;
ctx->skippable = skippable;
ctx->best_mode_index = mode_index;
ctx->mic = *xd->mi[0];
ctx->mbmi_ext = *x->mbmi_ext;
ctx->single_pred_diff = (int)comp_pred_diff[SINGLE_REFERENCE];
ctx->comp_pred_diff = (int)comp_pred_diff[COMPOUND_REFERENCE];
ctx->hybrid_pred_diff = (int)comp_pred_diff[REFERENCE_MODE_SELECT];
memcpy(ctx->best_filter_diff, best_filter_diff,
sizeof(*best_filter_diff) * SWITCHABLE_FILTER_CONTEXTS);
}
static void setup_buffer_inter(VP9_COMP *cpi, MACROBLOCK *x,
MV_REFERENCE_FRAME ref_frame,
BLOCK_SIZE block_size, int mi_row, int mi_col,
int_mv frame_nearest_mv[MAX_REF_FRAMES],
int_mv frame_near_mv[MAX_REF_FRAMES],
struct buf_2d yv12_mb[4][MAX_MB_PLANE]) {
const VP9_COMMON *cm = &cpi->common;
const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_buffer(cpi, ref_frame);
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
int_mv *const candidates = x->mbmi_ext->ref_mvs[ref_frame];
const struct scale_factors *const sf = &cm->frame_refs[ref_frame - 1].sf;
MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
assert(yv12 != NULL);
// TODO(jkoleszar): Is the UV buffer ever used here? If so, need to make this
// use the UV scaling factors.
vp9_setup_pred_block(xd, yv12_mb[ref_frame], yv12, mi_row, mi_col, sf, sf);
// Gets an initial list of candidate vectors from neighbours and orders them
vp9_find_mv_refs(cm, xd, mi, ref_frame, candidates, mi_row, mi_col,
mbmi_ext->mode_context);
// Candidate refinement carried out at encoder and decoder
vp9_find_best_ref_mvs(xd, cm->allow_high_precision_mv, candidates,
&frame_nearest_mv[ref_frame],
&frame_near_mv[ref_frame]);
// Further refinement that is encode side only to test the top few candidates
// in full and choose the best as the centre point for subsequent searches.
// The current implementation doesn't support scaling.
if (!vp9_is_scaled(sf) && block_size >= BLOCK_8X8)
vp9_mv_pred(cpi, x, yv12_mb[ref_frame][0].buf, yv12->y_stride, ref_frame,
block_size);
}
#if CONFIG_NON_GREEDY_MV
static int ref_frame_to_gf_rf_idx(int ref_frame) {
if (ref_frame == GOLDEN_FRAME) {
return 0;
}
if (ref_frame == LAST_FRAME) {
return 1;
}
if (ref_frame == ALTREF_FRAME) {
return 2;
}
assert(0);
return -1;
}
#endif
static void single_motion_search(VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize,
int mi_row, int mi_col, int_mv *tmp_mv,
int *rate_mv) {
MACROBLOCKD *xd = &x->e_mbd;
const VP9_COMMON *cm = &cpi->common;
MODE_INFO *mi = xd->mi[0];
struct buf_2d backup_yv12[MAX_MB_PLANE] = { { 0, 0 } };
int step_param;
MV mvp_full;
int ref = mi->ref_frame[0];
MV ref_mv = x->mbmi_ext->ref_mvs[ref][0].as_mv;
const MvLimits tmp_mv_limits = x->mv_limits;
int cost_list[5];
const int best_predmv_idx = x->mv_best_ref_index[ref];
const YV12_BUFFER_CONFIG *scaled_ref_frame =
vp9_get_scaled_ref_frame(cpi, ref);
const int pw = num_4x4_blocks_wide_lookup[bsize] << 2;
const int ph = num_4x4_blocks_high_lookup[bsize] << 2;
MV pred_mv[3];
#if CONFIG_NON_GREEDY_MV
double mv_dist = 0;
double mv_cost = 0;
double lambda = (pw * ph) / 4;
double bestsme;
int_mv nb_full_mvs[NB_MVS_NUM];
const int nb_full_mv_num = NB_MVS_NUM;
int gf_group_idx = cpi->twopass.gf_group.index;
int gf_rf_idx = ref_frame_to_gf_rf_idx(ref);
BLOCK_SIZE square_bsize = get_square_block_size(bsize);
vp9_prepare_nb_full_mvs(&cpi->tpl_stats[gf_group_idx], mi_row, mi_col,
gf_rf_idx, square_bsize, nb_full_mvs);
#else // CONFIG_NON_GREEDY_MV
int bestsme = INT_MAX;
int sadpb = x->sadperbit16;
#endif // CONFIG_NON_GREEDY_MV
pred_mv[0] = x->mbmi_ext->ref_mvs[ref][0].as_mv;
pred_mv[1] = x->mbmi_ext->ref_mvs[ref][1].as_mv;
pred_mv[2] = x->pred_mv[ref];
if (scaled_ref_frame) {
int i;
// Swap out the reference frame for a version that's been scaled to
// match the resolution of the current frame, allowing the existing
// motion search code to be used without additional modifications.
for (i = 0; i < MAX_MB_PLANE; i++) backup_yv12[i] = xd->plane[i].pre[0];
vp9_setup_pre_planes(xd, 0, scaled_ref_frame, mi_row, mi_col, NULL);
}
// Work out the size of the first step in the mv step search.
// 0 here is maximum length first step. 1 is VPXMAX >> 1 etc.
if (cpi->sf.mv.auto_mv_step_size && cm->show_frame) {
// Take wtd average of the step_params based on the last frame's
// max mv magnitude and that based on the best ref mvs of the current
// block for the given reference.
step_param =
(vp9_init_search_range(x->max_mv_context[ref]) + cpi->mv_step_param) /
2;
} else {
step_param = cpi->mv_step_param;
}
if (cpi->sf.adaptive_motion_search && bsize < BLOCK_64X64) {
const int boffset =
2 * (b_width_log2_lookup[BLOCK_64X64] -
VPXMIN(b_height_log2_lookup[bsize], b_width_log2_lookup[bsize]));
step_param = VPXMAX(step_param, boffset);
}
if (cpi->sf.adaptive_motion_search) {
int bwl = b_width_log2_lookup[bsize];
int bhl = b_height_log2_lookup[bsize];
int tlevel = x->pred_mv_sad[ref] >> (bwl + bhl + 4);
if (tlevel < 5) step_param += 2;
// prev_mv_sad is not setup for dynamically scaled frames.
if (cpi->oxcf.resize_mode != RESIZE_DYNAMIC) {
int i;
for (i = LAST_FRAME; i <= ALTREF_FRAME && cm->show_frame; ++i) {
if ((x->pred_mv_sad[ref] >> 3) > x->pred_mv_sad[i]) {
x->pred_mv[ref].row = INT16_MAX;
x->pred_mv[ref].col = INT16_MAX;
tmp_mv->as_int = INVALID_MV;
if (scaled_ref_frame) {
int i;
for (i = 0; i < MAX_MB_PLANE; ++i)
xd->plane[i].pre[0] = backup_yv12[i];
}
return;
}
}
}
}
// Note: MV limits are modified here. Always restore the original values
// after full-pixel motion search.
vp9_set_mv_search_range(&x->mv_limits, &ref_mv);
mvp_full = pred_mv[best_predmv_idx];
mvp_full.col >>= 3;
mvp_full.row >>= 3;
#if CONFIG_NON_GREEDY_MV
bestsme = vp9_full_pixel_diamond_new(
cpi, x, &mvp_full, step_param, lambda, 1, &cpi->fn_ptr[bsize],
nb_full_mvs, nb_full_mv_num, &tmp_mv->as_mv, &mv_dist, &mv_cost);
#else // CONFIG_NON_GREEDY_MV
bestsme = vp9_full_pixel_search(
cpi, x, bsize, &mvp_full, step_param, cpi->sf.mv.search_method, sadpb,
cond_cost_list(cpi, cost_list), &ref_mv, &tmp_mv->as_mv, INT_MAX, 1);
#endif // CONFIG_NON_GREEDY_MV
if (cpi->sf.enhanced_full_pixel_motion_search) {
int i;
for (i = 0; i < 3; ++i) {
#if CONFIG_NON_GREEDY_MV
double this_me;
#else // CONFIG_NON_GREEDY_MV
int this_me;
#endif // CONFIG_NON_GREEDY_MV
MV this_mv;
int diff_row;
int diff_col;
int step;
if (pred_mv[i].row == INT16_MAX || pred_mv[i].col == INT16_MAX) continue;
if (i == best_predmv_idx) continue;
diff_row = ((int)pred_mv[i].row -
pred_mv[i > 0 ? (i - 1) : best_predmv_idx].row) >>
3;
diff_col = ((int)pred_mv[i].col -
pred_mv[i > 0 ? (i - 1) : best_predmv_idx].col) >>
3;
if (diff_row == 0 && diff_col == 0) continue;
if (diff_row < 0) diff_row = -diff_row;
if (diff_col < 0) diff_col = -diff_col;
step = get_msb((diff_row + diff_col + 1) >> 1);
if (step <= 0) continue;
mvp_full = pred_mv[i];
mvp_full.col >>= 3;
mvp_full.row >>= 3;
#if CONFIG_NON_GREEDY_MV
this_me = vp9_full_pixel_diamond_new(
cpi, x, &mvp_full, VPXMAX(step_param, MAX_MVSEARCH_STEPS - step),
lambda, 1, &cpi->fn_ptr[bsize], nb_full_mvs, nb_full_mv_num, &this_mv,
&mv_dist, &mv_cost);
#else // CONFIG_NON_GREEDY_MV
this_me = vp9_full_pixel_search(
cpi, x, bsize, &mvp_full,
VPXMAX(step_param, MAX_MVSEARCH_STEPS - step),
cpi->sf.mv.search_method, sadpb, cond_cost_list(cpi, cost_list),
&ref_mv, &this_mv, INT_MAX, 1);
#endif // CONFIG_NON_GREEDY_MV
if (this_me < bestsme) {
tmp_mv->as_mv = this_mv;
bestsme = this_me;
}
}
}
x->mv_limits = tmp_mv_limits;
if (bestsme < INT_MAX) {
uint32_t dis; /* TODO: use dis in distortion calculation later. */
cpi->find_fractional_mv_step(
x, &tmp_mv->as_mv, &ref_mv, cm->allow_high_precision_mv, x->errorperbit,
&cpi->fn_ptr[bsize], cpi->sf.mv.subpel_force_stop,
cpi->sf.mv.subpel_search_level, cond_cost_list(cpi, cost_list),
x->nmvjointcost, x->mvcost, &dis, &x->pred_sse[ref], NULL, pw, ph,
cpi->sf.use_accurate_subpel_search);
}
*rate_mv = vp9_mv_bit_cost(&tmp_mv->as_mv, &ref_mv, x->nmvjointcost,
x->mvcost, MV_COST_WEIGHT);
x->pred_mv[ref] = tmp_mv->as_mv;
if (scaled_ref_frame) {
int i;
for (i = 0; i < MAX_MB_PLANE; i++) xd->plane[i].pre[0] = backup_yv12[i];
}
}
static INLINE void restore_dst_buf(MACROBLOCKD *xd,
uint8_t *orig_dst[MAX_MB_PLANE],
int orig_dst_stride[MAX_MB_PLANE]) {
int i;
for (i = 0; i < MAX_MB_PLANE; i++) {
xd->plane[i].dst.buf = orig_dst[i];
xd->plane[i].dst.stride = orig_dst_stride[i];
}
}
// In some situations we want to discount tha pparent cost of a new motion
// vector. Where there is a subtle motion field and especially where there is
// low spatial complexity then it can be hard to cover the cost of a new motion
// vector in a single block, even if that motion vector reduces distortion.
// However, once established that vector may be usable through the nearest and
// near mv modes to reduce distortion in subsequent blocks and also improve
// visual quality.
static int discount_newmv_test(const VP9_COMP *cpi, int this_mode,
int_mv this_mv,
int_mv (*mode_mv)[MAX_REF_FRAMES], int ref_frame,
int mi_row, int mi_col, BLOCK_SIZE bsize) {
#if CONFIG_NON_GREEDY_MV
(void)mode_mv;
(void)this_mv;
if (this_mode == NEWMV && bsize >= BLOCK_8X8 && cpi->tpl_ready) {
const int gf_group_idx = cpi->twopass.gf_group.index;
const int gf_rf_idx = ref_frame_to_gf_rf_idx(ref_frame);
const TplDepFrame tpl_frame = cpi->tpl_stats[gf_group_idx];
const int tpl_block_mi_h = num_8x8_blocks_high_lookup[cpi->tpl_bsize];
const int tpl_block_mi_w = num_8x8_blocks_wide_lookup[cpi->tpl_bsize];
const int tpl_mi_row = mi_row - (mi_row % tpl_block_mi_h);
const int tpl_mi_col = mi_col - (mi_col % tpl_block_mi_w);
const int mv_mode =
tpl_frame
.mv_mode_arr[gf_rf_idx][tpl_mi_row * tpl_frame.stride + tpl_mi_col];
if (mv_mode == NEW_MV_MODE) {
int_mv tpl_new_mv = *get_pyramid_mv(&tpl_frame, gf_rf_idx, cpi->tpl_bsize,
tpl_mi_row, tpl_mi_col);
int row_diff = abs(tpl_new_mv.as_mv.row - this_mv.as_mv.row);
int col_diff = abs(tpl_new_mv.as_mv.col - this_mv.as_mv.col);
if (VPXMAX(row_diff, col_diff) <= 8) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
#else
(void)mi_row;
(void)mi_col;
(void)bsize;
return (!cpi->rc.is_src_frame_alt_ref && (this_mode == NEWMV) &&
(this_mv.as_int != 0) &&
((mode_mv[NEARESTMV][ref_frame].as_int == 0) ||
(mode_mv[NEARESTMV][ref_frame].as_int == INVALID_MV)) &&
((mode_mv[NEARMV][ref_frame].as_int == 0) ||
(mode_mv[NEARMV][ref_frame].as_int == INVALID_MV)));
#endif
}
static int64_t handle_inter_mode(
VP9_COMP *cpi, MACROBLOCK *x, BLOCK_SIZE bsize, int *rate2,
int64_t *distortion, int *skippable, int *rate_y, int *rate_uv,
struct buf_2d *recon, int *disable_skip, int_mv (*mode_mv)[MAX_REF_FRAMES],
int mi_row, int mi_col, int_mv single_newmv[MAX_REF_FRAMES],
INTERP_FILTER (*single_filter)[MAX_REF_FRAMES],
int (*single_skippable)[MAX_REF_FRAMES], int64_t *psse,
const int64_t ref_best_rd, int64_t *mask_filter, int64_t filter_cache[]) {
VP9_COMMON *cm = &cpi->common;
MACROBLOCKD *xd = &x->e_mbd;
MODE_INFO *mi = xd->mi[0];
MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
const int is_comp_pred = has_second_ref(mi);
const int this_mode = mi->mode;
int_mv *frame_mv = mode_mv[this_mode];
int i;
int refs[2] = { mi->ref_frame[0],
(mi->ref_frame[1] < 0 ? 0 : mi->ref_frame[1]) };
int_mv cur_mv[2];
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, tmp_buf16[MAX_MB_PLANE * 64 * 64]);
uint8_t *tmp_buf;
#else
DECLARE_ALIGNED(16, uint8_t, tmp_buf[MAX_MB_PLANE * 64 * 64]);
#endif // CONFIG_VP9_HIGHBITDEPTH
int pred_exists = 0;
int intpel_mv;
int64_t rd, tmp_rd, best_rd = INT64_MAX;
int best_needs_copy = 0;
uint8_t *orig_dst[MAX_MB_PLANE];
int orig_dst_stride[MAX_MB_PLANE];
int rs = 0;
INTERP_FILTER best_filter = SWITCHABLE;
uint8_t skip_txfm[MAX_MB_PLANE << 2] = { 0 };
int64_t bsse[MAX_MB_PLANE << 2] = { 0 };
int bsl = mi_width_log2_lookup[bsize];
int pred_filter_search =
cpi->sf.cb_pred_filter_search
? (((mi_row + mi_col) >> bsl) +
get_chessboard_index(cm->current_video_frame)) &
0x1
: 0;
int skip_txfm_sb = 0;
int64_t skip_sse_sb = INT64_MAX;
int64_t distortion_y = 0, distortion_uv = 0;
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
tmp_buf = CONVERT_TO_BYTEPTR(tmp_buf16);
} else {
tmp_buf = (uint8_t *)tmp_buf16;
}
#endif // CONFIG_VP9_HIGHBITDEPTH
if (pred_filter_search) {
INTERP_FILTER af = SWITCHABLE, lf = SWITCHABLE;
if (xd->above_mi && is_inter_block(xd->above_mi))
af = xd->above_mi->interp_filter;
if (xd->left_mi && is_inter_block(xd->left_mi))
lf = xd->left_mi->interp_filter;
if ((this_mode != NEWMV) || (af == lf)) best_filter = af;
}
if (is_comp_pred) {
if (frame_mv[refs[0]].as_int == INVALID_MV ||
frame_mv[refs[1]].as_int == INVALID_MV)
return INT64_MAX;
if (cpi->sf.adaptive_mode_search) {
if (single_filter[this_mode][refs[0]] ==
single_filter[this_mode][refs[1]])
best_filter = single_filter[this_mode][refs[0]];
}
}
if (this_mode == NEWMV) {
int rate_mv;
if (is_comp_pred) {
// Initialize mv using single prediction mode result.
frame_mv[refs[0]].as_int = single_newmv[refs[0]].as_int;
frame_mv[refs[1]].as_int = single_newmv[refs[1]].as_int;
if (cpi->sf.comp_inter_joint_search_thresh <= bsize) {
joint_motion_search(cpi, x, bsize, frame_mv, mi_row, mi_col,
single_newmv, &rate_mv);
} else {
rate_mv = vp9_mv_bit_cost(&frame_mv[refs[0]].as_mv,
&x->mbmi_ext->ref_mvs[refs[0]][0].as_mv,
x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
rate_mv += vp9_mv_bit_cost(&frame_mv[refs[1]].as_mv,
&x->mbmi_ext->ref_mvs[refs[1]][0].as_mv,
x->nmvjointcost, x->mvcost, MV_COST_WEIGHT);
}
*rate2 += rate_mv;
} else {
int_mv tmp_mv;
single_motion_search(cpi, x, bsize, mi_row, mi_col, &tmp_mv, &rate_mv);
if (tmp_mv.as_int == INVALID_MV) return INT64_MAX;
frame_mv[refs[0]].as_int = xd->mi[0]->bmi[0].as_mv[0].as_int =
tmp_mv.as_int;
single_newmv[refs[0]].as_int = tmp_mv.as_int;
// Estimate the rate implications of a new mv but discount this
// under certain circumstances where we want to help initiate a weak
// motion field, where the distortion gain for a single block may not
// be enough to overcome the cost of a new mv.
if (discount_newmv_test(cpi, this_mode, tmp_mv, mode_mv, refs[0], mi_row,
mi_col, bsize)) {
*rate2 += VPXMAX((rate_mv / NEW_MV_DISCOUNT_FACTOR), 1);
} else {
*rate2 += rate_mv;
}
}
}
for (i = 0; i < is_comp_pred + 1; ++i) {
cur_mv[i] = frame_mv[refs[i]];
// Clip "next_nearest" so that it does not extend to far out of image
if (this_mode != NEWMV) clamp_mv2(&cur_mv[i].as_mv, xd);
if (mv_check_bounds(&x->mv_limits, &cur_mv[i].as_mv)) return INT64_MAX;
mi->mv[i].as_int = cur_mv[i].as_int;
}
// do first prediction into the destination buffer. Do the next
// prediction into a temporary buffer. Then keep track of which one
// of these currently holds the best predictor, and use the other
// one for future predictions. In the end, copy from tmp_buf to
// dst if necessary.
for (i = 0; i < MAX_MB_PLANE; i++) {
orig_dst[i] = xd->plane[i].dst.buf;
orig_dst_stride[i] = xd->plane[i].dst.stride;
}
// We don't include the cost of the second reference here, because there
// are only two options: Last/ARF or Golden/ARF; The second one is always
// known, which is ARF.
//
// Under some circumstances we discount the cost of new mv mode to encourage
// initiation of a motion field.
if (discount_newmv_test(cpi, this_mode, frame_mv[refs[0]], mode_mv, refs[0],
mi_row, mi_col, bsize)) {
*rate2 +=
VPXMIN(cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]),
cost_mv_ref(cpi, NEARESTMV, mbmi_ext->mode_context[refs[0]]));
} else {
*rate2 += cost_mv_ref(cpi, this_mode, mbmi_ext->mode_context[refs[0]]);
}
if (RDCOST(x->rdmult, x->rddiv, *rate2, 0) > ref_best_rd &&
mi->mode != NEARESTMV)
return INT64_MAX;
pred_exists = 0;
// Are all MVs integer pel for Y and UV
intpel_mv = !mv_has_subpel(&mi->mv[0].as_mv);
if (is_comp_pred) intpel_mv &= !mv_has_subpel(&mi->mv[1].as_mv);
// Search for best switchable filter by checking the variance of
// pred error irrespective of whether the filter will be used
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
if (cm->interp_filter != BILINEAR) {
if (x->source_variance < cpi->sf.disable_filter_search_var_thresh) {
best_filter = EIGHTTAP;
} else if (best_filter == SWITCHABLE) {
int newbest;
int tmp_rate_sum = 0;
int64_t tmp_dist_sum = 0;
for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
int j;
int64_t rs_rd;
int tmp_skip_sb = 0;
int64_t tmp_skip_sse = INT64_MAX;
mi->interp_filter = i;
rs = vp9_get_switchable_rate(cpi, xd);
rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
if (i > 0 && intpel_mv) {
rd = RDCOST(x->rdmult, x->rddiv, tmp_rate_sum, tmp_dist_sum);
filter_cache[i] = rd;
filter_cache[SWITCHABLE_FILTERS] =
VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
*mask_filter = VPXMAX(*mask_filter, rd);
} else {
int rate_sum = 0;
int64_t dist_sum = 0;
if (i > 0 && cpi->sf.adaptive_interp_filter_search &&
(cpi->sf.interp_filter_search_mask & (1 << i))) {
rate_sum = INT_MAX;
dist_sum = INT64_MAX;
continue;
}
if ((cm->interp_filter == SWITCHABLE && (!i || best_needs_copy)) ||
(cm->interp_filter != SWITCHABLE &&
(cm->interp_filter == mi->interp_filter ||
(i == 0 && intpel_mv)))) {
restore_dst_buf(xd, orig_dst, orig_dst_stride);
} else {
for (j = 0; j < MAX_MB_PLANE; j++) {
xd->plane[j].dst.buf = tmp_buf + j * 64 * 64;
xd->plane[j].dst.stride = 64;
}
}
vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
model_rd_for_sb(cpi, bsize, x, xd, &rate_sum, &dist_sum, &tmp_skip_sb,
&tmp_skip_sse);
rd = RDCOST(x->rdmult, x->rddiv, rate_sum, dist_sum);
filter_cache[i] = rd;
filter_cache[SWITCHABLE_FILTERS] =
VPXMIN(filter_cache[SWITCHABLE_FILTERS], rd + rs_rd);
if (cm->interp_filter == SWITCHABLE) rd += rs_rd;
*mask_filter = VPXMAX(*mask_filter, rd);
if (i == 0 && intpel_mv) {
tmp_rate_sum = rate_sum;
tmp_dist_sum = dist_sum;
}
}
if (i == 0 && cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
if (rd / 2 > ref_best_rd) {
restore_dst_buf(xd, orig_dst, orig_dst_stride);
return INT64_MAX;
}
}
newbest = i == 0 || rd < best_rd;
if (newbest) {
best_rd = rd;
best_filter = mi->interp_filter;
if (cm->interp_filter == SWITCHABLE && i && !intpel_mv)
best_needs_copy = !best_needs_copy;
}
if ((cm->interp_filter == SWITCHABLE && newbest) ||
(cm->interp_filter != SWITCHABLE &&
cm->interp_filter == mi->interp_filter)) {
pred_exists = 1;
tmp_rd = best_rd;
skip_txfm_sb = tmp_skip_sb;
skip_sse_sb = tmp_skip_sse;
memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
memcpy(bsse, x->bsse, sizeof(bsse));
}
}
restore_dst_buf(xd, orig_dst, orig_dst_stride);
}
}
// Set the appropriate filter
mi->interp_filter =
cm->interp_filter != SWITCHABLE ? cm->interp_filter : best_filter;
rs = cm->interp_filter == SWITCHABLE ? vp9_get_switchable_rate(cpi, xd) : 0;
if (pred_exists) {
if (best_needs_copy) {
// again temporarily set the buffers to local memory to prevent a memcpy
for (i = 0; i < MAX_MB_PLANE; i++) {
xd->plane[i].dst.buf = tmp_buf + i * 64 * 64;
xd->plane[i].dst.stride = 64;
}
}
rd = tmp_rd + RDCOST(x->rdmult, x->rddiv, rs, 0);
} else {
int tmp_rate;
int64_t tmp_dist;
// Handles the special case when a filter that is not in the
// switchable list (ex. bilinear) is indicated at the frame level, or
// skip condition holds.
vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
model_rd_for_sb(cpi, bsize, x, xd, &tmp_rate, &tmp_dist, &skip_txfm_sb,
&skip_sse_sb);
rd = RDCOST(x->rdmult, x->rddiv, rs + tmp_rate, tmp_dist);
memcpy(skip_txfm, x->skip_txfm, sizeof(skip_txfm));
memcpy(bsse, x->bsse, sizeof(bsse));
}
if (!is_comp_pred) single_filter[this_mode][refs[0]] = mi->interp_filter;
if (cpi->sf.adaptive_mode_search)
if (is_comp_pred)
if (single_skippable[this_mode][refs[0]] &&
single_skippable[this_mode][refs[1]])
memset(skip_txfm, SKIP_TXFM_AC_DC, sizeof(skip_txfm));
if (cpi->sf.use_rd_breakout && ref_best_rd < INT64_MAX) {
// if current pred_error modeled rd is substantially more than the best
// so far, do not bother doing full rd
if (rd / 2 > ref_best_rd) {
restore_dst_buf(xd, orig_dst, orig_dst_stride);
return INT64_MAX;
}
}
if (cm->interp_filter == SWITCHABLE) *rate2 += rs;
memcpy(x->skip_txfm, skip_txfm, sizeof(skip_txfm));
memcpy(x->bsse, bsse, sizeof(bsse));
if (!skip_txfm_sb || xd->lossless) {
int skippable_y, skippable_uv;
int64_t sseuv = INT64_MAX;
int64_t rdcosty = INT64_MAX;
// Y cost and distortion
vp9_subtract_plane(x, bsize, 0);
super_block_yrd(cpi, x, rate_y, &distortion_y, &skippable_y, psse, bsize,
ref_best_rd, recon);
if (*rate_y == INT_MAX) {
*rate2 = INT_MAX;
*distortion = INT64_MAX;
restore_dst_buf(xd, orig_dst, orig_dst_stride);
return INT64_MAX;
}
*rate2 += *rate_y;
*distortion += distortion_y;
rdcosty = RDCOST(x->rdmult, x->rddiv, *rate2, *distortion);
rdcosty = VPXMIN(rdcosty, RDCOST(x->rdmult, x->rddiv, 0, *psse));
if (!super_block_uvrd(cpi, x, rate_uv, &distortion_uv, &skippable_uv,
&sseuv, bsize, ref_best_rd - rdcosty)) {
*rate2 = INT_MAX;
*distortion = INT64_MAX;
restore_dst_buf(xd, orig_dst, orig_dst_stride);
return INT64_MAX;
}
*psse += sseuv;
*rate2 += *rate_uv;
*distortion += distortion_uv;
*skippable = skippable_y && skippable_uv;
} else {
x->skip = 1;
*disable_skip = 1;
// The cost of skip bit needs to be added.
*rate2 += vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
*distortion = skip_sse_sb;
}
if (!is_comp_pred) single_skippable[this_mode][refs[0]] = *skippable;
restore_dst_buf(xd, orig_dst, orig_dst_stride);
return 0; // The rate-distortion cost will be re-calculated by caller.
}
#endif // !CONFIG_REALTIME_ONLY
void vp9_rd_pick_intra_mode_sb(VP9_COMP *cpi, MACROBLOCK *x, RD_COST *rd_cost,
BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
int64_t best_rd) {
VP9_COMMON *const cm = &cpi->common;
MACROBLOCKD *const xd = &x->e_mbd;
struct macroblockd_plane *const pd = xd->plane;
int rate_y = 0, rate_uv = 0, rate_y_tokenonly = 0, rate_uv_tokenonly = 0;
int y_skip = 0, uv_skip = 0;
int64_t dist_y = 0, dist_uv = 0;
TX_SIZE max_uv_tx_size;
x->skip_encode = 0;
ctx->skip = 0;
xd->mi[0]->ref_frame[0] = INTRA_FRAME;
xd->mi[0]->ref_frame[1] = NONE;
// Initialize interp_filter here so we do not have to check for inter block
// modes in get_pred_context_switchable_interp()
xd->mi[0]->interp_filter = SWITCHABLE_FILTERS;
if (bsize >= BLOCK_8X8) {
if (rd_pick_intra_sby_mode(cpi, x, &rate_y, &rate_y_tokenonly, &dist_y,
&y_skip, bsize, best_rd) >= best_rd) {
rd_cost->rate = INT_MAX;
return;
}
} else {
y_skip = 0;
if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate_y, &rate_y_tokenonly,
&dist_y, best_rd) >= best_rd) {
rd_cost->rate = INT_MAX;
return;
}
}
max_uv_tx_size = uv_txsize_lookup[bsize][xd->mi[0]->tx_size]
[pd[1].subsampling_x][pd[1].subsampling_y];
rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv, &rate_uv_tokenonly, &dist_uv,
&uv_skip, VPXMAX(BLOCK_8X8, bsize), max_uv_tx_size);
if (y_skip && uv_skip) {
rd_cost->rate = rate_y + rate_uv - rate_y_tokenonly - rate_uv_tokenonly +
vp9_cost_bit(vp9_get_skip_prob(cm, xd), 1);
rd_cost->dist = dist_y + dist_uv;
} else {
rd_cost->rate =
rate_y + rate_uv + vp9_cost_bit(vp9_get_skip_prob(cm, xd), 0);
rd_cost->dist = dist_y + dist_uv;
}
ctx->mic = *xd->mi[0];
ctx->mbmi_ext = *x->mbmi_ext;
rd_cost->rdcost = RDCOST(x->rdmult, x->rddiv, rd_cost->rate, rd_cost->dist);
}
#if !CONFIG_REALTIME_ONLY
// This function is designed to apply a bias or adjustment to an rd value based
// on the relative variance of the source and reconstruction.
#define LOW_VAR_THRESH 250
#define VAR_MULT 250
static unsigned int max_var_adjust[VP9E_CONTENT_INVALID] = { 16, 16, 250 };
static void rd_variance_adjustment(VP9_COMP *cpi, MACROBLOCK *x,
BLOCK_SIZE bsize, int64_t *this_rd,
struct buf_2d *recon,
MV_REFERENCE_FRAME ref_frame,
MV_REFERENCE_FRAME second_ref_frame,
PREDICTION_MODE this_mode) {
MACROBLOCKD *const xd = &x->e_mbd;
unsigned int rec_variance;
unsigned int src_variance;
unsigned int src_rec_min;
unsigned int var_diff = 0;
unsigned int var_factor = 0;
unsigned int adj_max;
unsigned int low_var_thresh = LOW_VAR_THRESH;
const int bw = num_8x8_blocks_wide_lookup[bsize];
const int bh = num_8x8_blocks_high_lookup[bsize];
vp9e_tune_content content_type = cpi->oxcf.content;
if (*this_rd == INT64_MAX) return;
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
rec_variance = vp9_high_get_sby_variance(cpi, recon, bsize, xd->bd);
src_variance =
vp9_high_get_sby_variance(cpi, &x->plane[0].src, bsize, xd->bd);
} else {
rec_variance = vp9_get_sby_variance(cpi, recon, bsize);
src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
}
#else
rec_variance = vp9_get_sby_variance(cpi, recon, bsize);
src_variance = vp9_get_sby_variance(cpi, &x->plane[0].src, bsize);
#endif // CONFIG_VP9_HIGHBITDEPTH
// Scale based on area in 8x8 blocks
rec_variance /= (bw * bh);
src_variance /= (bw * bh);
if (content_type == VP9E_CONTENT_FILM) {
if (cpi->oxcf.pass == 2) {
// Adjust low variance threshold based on estimated group noise enegry.
double noise_factor =
(double)cpi->twopass.gf_group.group_noise_energy / SECTION_NOISE_DEF;
low_var_thresh = (unsigned int)(low_var_thresh * noise_factor);
if (ref_frame == INTRA_FRAME) {
low_var_thresh *= 2;
if (this_mode == DC_PRED) low_var_thresh *= 5;
} else if (second_ref_frame > INTRA_FRAME) {
low_var_thresh *= 2;
}
}
} else {
low_var_thresh = LOW_VAR_THRESH / 2;
}
// Lower of source (raw per pixel value) and recon variance. Note that
// if the source per pixel is 0 then the recon value here will not be per
// pixel (see above) so will likely be much larger.
src_rec_min = VPXMIN(src_variance, rec_variance);
if (src_rec_min > low_var_thresh) return;
// We care more when the reconstruction has lower variance so give this case
// a stronger weighting.
var_diff = (src_variance > rec_variance) ? (src_variance - rec_variance) * 2
: (rec_variance - src_variance) / 2;
adj_max = max_var_adjust[content_type];
var_factor =
(unsigned int)((int64_t)VAR_MULT * var_diff) / VPXMAX(1, src_variance);
var_factor = VPXMIN(adj_max, var_factor);
if ((content_type == VP9E_CONTENT_FILM) &&
((ref_frame == INTRA_FRAME) || (second_ref_frame > INTRA_FRAME))) {
var_factor *= 2;
}
*this_rd += (*this_rd * var_factor) / 100;
(void)xd;
}
#endif // !CONFIG_REALTIME_ONLY
// Do we have an internal image edge (e.g. formatting bars).
int vp9_internal_image_edge(VP9_COMP *cpi) {
return (cpi->oxcf.pass == 2) &&
((cpi->twopass.this_frame_stats.inactive_zone_rows > 0) ||
(cpi->twopass.this_frame_stats.inactive_zone_cols > 0));
}
// Checks to see if a super block is on a horizontal image edge.
// In most cases this is the "real" edge unless there are formatting
// bars embedded in the stream.
int vp9_active_h_edge(VP9_COMP *cpi, int mi_row, int mi_step) {
int top_edge = 0;
int bottom_edge = cpi->common.mi_rows;
int is_active_h_edge = 0;
// For two pass account for any formatting bars detected.
if (cpi->oxcf.pass == 2) {
TWO_PASS *twopass = &cpi->twopass;
// The inactive region is specified in MBs not mi units.
// The image edge is in the following MB row.
top_edge += (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
bottom_edge -= (int)(twopass->this_frame_stats.inactive_zone_rows * 2);
bottom_edge = VPXMAX(top_edge, bottom_edge);
}
if (((top_edge >= mi_row) && (top_edge < (mi_row + mi_step))) ||
((bottom_edge >= mi_row) && (bottom_edge < (mi_row + mi_step)))) {
is_active_h_edge = 1;
}
return is_active_h_edge;
}
// Checks to see if a super block is on a vertical image edge.
// In most cases this is the "real" edge unless there are formatting
// bars embedded in the stream.
int vp9_active_v_edge(VP9_COMP *cpi, int mi_col, int mi_step) {
int left_edge = 0;
int right_edge = cpi->common.mi_cols;
int is_active_v_edge = 0;
// For two pass account for any formatting bars detected.
if (cpi->oxcf.pass == 2) {
TWO_PASS *twopass = &cpi->twopass;
// The inactive region is specified in MBs not mi units.
// The image edge is in the following MB row.
left_edge += (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
right_edge -= (int)(twopass->this_frame_stats.inactive_zone_cols * 2);
right_edge = VPXMAX(left_edge, right_edge);
}
if (((left_edge >= mi_col) && (left_edge < (mi_col + mi_step))) ||
((right_edge >= mi_col) && (right_edge < (mi_col + mi_step)))) {
is_active_v_edge = 1;
}
return is_active_v_edge;
}
// Checks to see if a super block is at the edge of the active image.
// In most cases this is the "real" edge unless there are formatting
// bars embedded in the stream.
int vp9_active_edge_sb(VP9_COMP *cpi, int mi_row, int mi_col) {
return vp9_active_h_edge(cpi, mi_row, MI_BLOCK_SIZE) ||
vp9_active_v_edge(cpi, mi_col, MI_BLOCK_SIZE);
}
#if !CONFIG_REALTIME_ONLY
void vp9_rd_pick_inter_mode_sb(VP9_COMP *cpi, TileDataEnc *tile_data,
MACROBLOCK *x, int mi_row, int mi_col,
RD_COST *rd_cost, BLOCK_SIZE bsize,
PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far) {
VP9_COMMON *const cm = &cpi->common;
TileInfo *const tile_info = &tile_data->tile_info;
RD_OPT *const rd_opt = &cpi->rd;
SPEED_FEATURES *const sf = &cpi->sf;
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
MB_MODE_INFO_EXT *const mbmi_ext = x->mbmi_ext;
const struct segmentation *const seg = &cm->seg;
PREDICTION_MODE this_mode;
MV_REFERENCE_FRAME ref_frame, second_ref_frame;
unsigned char segment_id = mi->segment_id;
int comp_pred, i, k;
int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
struct buf_2d yv12_mb[4][MAX_MB_PLANE];
int_mv single_newmv[MAX_REF_FRAMES] = { { 0 } };
INTERP_FILTER single_inter_filter[MB_MODE_COUNT][MAX_REF_FRAMES];
int single_skippable[MB_MODE_COUNT][MAX_REF_FRAMES];
static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
VP9_ALT_FLAG };
int64_t best_rd = best_rd_so_far;
int64_t best_pred_diff[REFERENCE_MODES];
int64_t best_pred_rd[REFERENCE_MODES];
int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
MODE_INFO best_mbmode;
int best_mode_skippable = 0;
int midx, best_mode_index = -1;
unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
vpx_prob comp_mode_p;
int64_t best_intra_rd = INT64_MAX;
unsigned int best_pred_sse = UINT_MAX;
PREDICTION_MODE best_intra_mode = DC_PRED;
int rate_uv_intra[TX_SIZES], rate_uv_tokenonly[TX_SIZES];
int64_t dist_uv[TX_SIZES];
int skip_uv[TX_SIZES];
PREDICTION_MODE mode_uv[TX_SIZES];
const int intra_cost_penalty =
vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
int best_skip2 = 0;
uint8_t ref_frame_skip_mask[2] = { 0, 1 };
uint16_t mode_skip_mask[MAX_REF_FRAMES] = { 0 };
int mode_skip_start = sf->mode_skip_start + 1;
const int *const rd_threshes = rd_opt->threshes[segment_id][bsize];
const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
int64_t mode_threshold[MAX_MODES];
int8_t *tile_mode_map = tile_data->mode_map[bsize];
int8_t mode_map[MAX_MODES]; // Maintain mode_map information locally to avoid
// lock mechanism involved with reads from
// tile_mode_map
const int mode_search_skip_flags = sf->mode_search_skip_flags;
const int is_rect_partition =
num_4x4_blocks_wide_lookup[bsize] != num_4x4_blocks_high_lookup[bsize];
int64_t mask_filter = 0;
int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
struct buf_2d *recon;
struct buf_2d recon_buf;
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, recon16[64 * 64]);
recon_buf.buf = xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH
? CONVERT_TO_BYTEPTR(recon16)
: (uint8_t *)recon16;
#else
DECLARE_ALIGNED(16, uint8_t, recon8[64 * 64]);
recon_buf.buf = recon8;
#endif // CONFIG_VP9_HIGHBITDEPTH
recon_buf.stride = 64;
recon = cpi->oxcf.content == VP9E_CONTENT_FILM ? &recon_buf : 0;
vp9_zero(best_mbmode);
x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
&comp_mode_p);
for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = INT64_MAX;
for (i = 0; i < TX_SIZES; i++) rate_uv_intra[i] = INT_MAX;
for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
for (i = 0; i < MB_MODE_COUNT; ++i) {
for (k = 0; k < MAX_REF_FRAMES; ++k) {
single_inter_filter[i][k] = SWITCHABLE;
single_skippable[i][k] = 0;
}
}
rd_cost->rate = INT_MAX;
for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
x->pred_mv_sad[ref_frame] = INT_MAX;
if ((cpi->ref_frame_flags & flag_list[ref_frame]) &&
!(is_rect_partition && (ctx->skip_ref_frame_mask & (1 << ref_frame)))) {
assert(get_ref_frame_buffer(cpi, ref_frame) != NULL);
setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
}
frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
frame_mv[ZEROMV][ref_frame].as_int = 0;
}
for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
if (!(cpi->ref_frame_flags & flag_list[ref_frame])) {
// Skip checking missing references in both single and compound reference
// modes. Note that a mode will be skipped if both reference frames
// are masked out.
ref_frame_skip_mask[0] |= (1 << ref_frame);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
} else if (sf->reference_masking) {
for (i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
// Skip fixed mv modes for poor references
if ((x->pred_mv_sad[ref_frame] >> 2) > x->pred_mv_sad[i]) {
mode_skip_mask[ref_frame] |= INTER_NEAREST_NEAR_ZERO;
break;
}
}
}
// If the segment reference frame feature is enabled....
// then do nothing if the current ref frame is not allowed..
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
ref_frame_skip_mask[0] |= (1 << ref_frame);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
}
}
// Disable this drop out case if the ref frame
// segment level feature is enabled for this segment. This is to
// prevent the possibility that we end up unable to pick any mode.
if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
// Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
// unless ARNR filtering is enabled in which case we want
// an unfiltered alternative. We allow near/nearest as well
// because they may result in zero-zero MVs but be cheaper.
if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0)) {
ref_frame_skip_mask[0] = (1 << LAST_FRAME) | (1 << GOLDEN_FRAME);
ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
mode_skip_mask[ALTREF_FRAME] = ~INTER_NEAREST_NEAR_ZERO;
if (frame_mv[NEARMV][ALTREF_FRAME].as_int != 0)
mode_skip_mask[ALTREF_FRAME] |= (1 << NEARMV);
if (frame_mv[NEARESTMV][ALTREF_FRAME].as_int != 0)
mode_skip_mask[ALTREF_FRAME] |= (1 << NEARESTMV);
}
}
if (cpi->rc.is_src_frame_alt_ref) {
if (sf->alt_ref_search_fp) {
mode_skip_mask[ALTREF_FRAME] = 0;
ref_frame_skip_mask[0] = ~(1 << ALTREF_FRAME);
ref_frame_skip_mask[1] = SECOND_REF_FRAME_MASK;
}
}
if (sf->alt_ref_search_fp)
if (!cm->show_frame && x->pred_mv_sad[GOLDEN_FRAME] < INT_MAX)
if (x->pred_mv_sad[ALTREF_FRAME] > (x->pred_mv_sad[GOLDEN_FRAME] << 1))
mode_skip_mask[ALTREF_FRAME] |= INTER_ALL;
if (sf->adaptive_mode_search) {
if (cm->show_frame && !cpi->rc.is_src_frame_alt_ref &&
cpi->rc.frames_since_golden >= 3)
if (x->pred_mv_sad[GOLDEN_FRAME] > (x->pred_mv_sad[LAST_FRAME] << 1))
mode_skip_mask[GOLDEN_FRAME] |= INTER_ALL;
}
if (bsize > sf->max_intra_bsize) {
ref_frame_skip_mask[0] |= (1 << INTRA_FRAME);
ref_frame_skip_mask[1] |= (1 << INTRA_FRAME);
}
mode_skip_mask[INTRA_FRAME] |=
~(sf->intra_y_mode_mask[max_txsize_lookup[bsize]]);
for (i = 0; i <= LAST_NEW_MV_INDEX; ++i) mode_threshold[i] = 0;
for (i = LAST_NEW_MV_INDEX + 1; i < MAX_MODES; ++i)
mode_threshold[i] = ((int64_t)rd_threshes[i] * rd_thresh_freq_fact[i]) >> 5;
midx = sf->schedule_mode_search ? mode_skip_start : 0;
while (midx > 4) {
uint8_t end_pos = 0;
for (i = 5; i < midx; ++i) {
if (mode_threshold[tile_mode_map[i - 1]] >
mode_threshold[tile_mode_map[i]]) {
uint8_t tmp = tile_mode_map[i];
tile_mode_map[i] = tile_mode_map[i - 1];
tile_mode_map[i - 1] = tmp;
end_pos = i;
}
}
midx = end_pos;
}
memcpy(mode_map, tile_mode_map, sizeof(mode_map));
for (midx = 0; midx < MAX_MODES; ++midx) {
int mode_index = mode_map[midx];
int mode_excluded = 0;
int64_t this_rd = INT64_MAX;
int disable_skip = 0;
int compmode_cost = 0;
int rate2 = 0, rate_y = 0, rate_uv = 0;
int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
int skippable = 0;
int this_skip2 = 0;
int64_t total_sse = INT64_MAX;
int early_term = 0;
this_mode = vp9_mode_order[mode_index].mode;
ref_frame = vp9_mode_order[mode_index].ref_frame[0];
second_ref_frame = vp9_mode_order[mode_index].ref_frame[1];
vp9_zero(x->sum_y_eobs);
if (is_rect_partition) {
if (ctx->skip_ref_frame_mask & (1 << ref_frame)) continue;
if (second_ref_frame > 0 &&
(ctx->skip_ref_frame_mask & (1 << second_ref_frame)))
continue;
}
// Look at the reference frame of the best mode so far and set the
// skip mask to look at a subset of the remaining modes.
if (midx == mode_skip_start && best_mode_index >= 0) {
switch (best_mbmode.ref_frame[0]) {
case INTRA_FRAME: break;
case LAST_FRAME: ref_frame_skip_mask[0] |= LAST_FRAME_MODE_MASK; break;
case GOLDEN_FRAME:
ref_frame_skip_mask[0] |= GOLDEN_FRAME_MODE_MASK;
break;
case ALTREF_FRAME: ref_frame_skip_mask[0] |= ALT_REF_MODE_MASK; break;
case NONE:
case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
}
}
if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
(ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
continue;
if (mode_skip_mask[ref_frame] & (1 << this_mode)) continue;
// Test best rd so far against threshold for trying this mode.
if (best_mode_skippable && sf->schedule_mode_search)
mode_threshold[mode_index] <<= 1;
if (best_rd < mode_threshold[mode_index]) continue;
// This is only used in motion vector unit test.
if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
if (sf->motion_field_mode_search) {
const int mi_width = VPXMIN(num_8x8_blocks_wide_lookup[bsize],
tile_info->mi_col_end - mi_col);
const int mi_height = VPXMIN(num_8x8_blocks_high_lookup[bsize],
tile_info->mi_row_end - mi_row);
const int bsl = mi_width_log2_lookup[bsize];
int cb_partition_search_ctrl =
(((mi_row + mi_col) >> bsl) +
get_chessboard_index(cm->current_video_frame)) &
0x1;
MODE_INFO *ref_mi;
int const_motion = 1;
int skip_ref_frame = !cb_partition_search_ctrl;
MV_REFERENCE_FRAME rf = NONE;
int_mv ref_mv;
ref_mv.as_int = INVALID_MV;
if ((mi_row - 1) >= tile_info->mi_row_start) {
ref_mv = xd->mi[-xd->mi_stride]->mv[0];
rf = xd->mi[-xd->mi_stride]->ref_frame[0];
for (i = 0; i < mi_width; ++i) {
ref_mi = xd->mi[-xd->mi_stride + i];
const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
(ref_frame == ref_mi->ref_frame[0]);
skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
}
}
if ((mi_col - 1) >= tile_info->mi_col_start) {
if (ref_mv.as_int == INVALID_MV) ref_mv = xd->mi[-1]->mv[0];
if (rf == NONE) rf = xd->mi[-1]->ref_frame[0];
for (i = 0; i < mi_height; ++i) {
ref_mi = xd->mi[i * xd->mi_stride - 1];
const_motion &= (ref_mv.as_int == ref_mi->mv[0].as_int) &&
(ref_frame == ref_mi->ref_frame[0]);
skip_ref_frame &= (rf == ref_mi->ref_frame[0]);
}
}
if (skip_ref_frame && this_mode != NEARESTMV && this_mode != NEWMV)
if (rf > INTRA_FRAME)
if (ref_frame != rf) continue;
if (const_motion)
if (this_mode == NEARMV || this_mode == ZEROMV) continue;
}
comp_pred = second_ref_frame > INTRA_FRAME;
if (comp_pred) {
if (!cpi->allow_comp_inter_inter) continue;
if (cm->ref_frame_sign_bias[ref_frame] ==
cm->ref_frame_sign_bias[second_ref_frame])
continue;
// Skip compound inter modes if ARF is not available.
if (!(cpi->ref_frame_flags & flag_list[second_ref_frame])) continue;
// Do not allow compound prediction if the segment level reference frame
// feature is in use as in this case there can only be one reference.
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
if ((mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
best_mode_index >= 0 && best_mbmode.ref_frame[0] == INTRA_FRAME)
continue;
mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
} else {
if (ref_frame != INTRA_FRAME)
mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
}
if (ref_frame == INTRA_FRAME) {
if (sf->adaptive_mode_search)
if ((x->source_variance << num_pels_log2_lookup[bsize]) > best_pred_sse)
continue;
if (this_mode != DC_PRED) {
// Disable intra modes other than DC_PRED for blocks with low variance
// Threshold for intra skipping based on source variance
// TODO(debargha): Specialize the threshold for super block sizes
const unsigned int skip_intra_var_thresh =
(cpi->oxcf.content == VP9E_CONTENT_FILM) ? 0 : 64;
if ((mode_search_skip_flags & FLAG_SKIP_INTRA_LOWVAR) &&
x->source_variance < skip_intra_var_thresh)
continue;
// Only search the oblique modes if the best so far is
// one of the neighboring directional modes
if ((mode_search_skip_flags & FLAG_SKIP_INTRA_BESTINTER) &&
(this_mode >= D45_PRED && this_mode <= TM_PRED)) {
if (best_mode_index >= 0 && best_mbmode.ref_frame[0] > INTRA_FRAME)
continue;
}
if (mode_search_skip_flags & FLAG_SKIP_INTRA_DIRMISMATCH) {
if (conditional_skipintra(this_mode, best_intra_mode)) continue;
}
}
} else {
const MV_REFERENCE_FRAME ref_frames[2] = { ref_frame, second_ref_frame };
if (!check_best_zero_mv(cpi, mbmi_ext->mode_context, frame_mv, this_mode,
ref_frames))
continue;
}
mi->mode = this_mode;
mi->uv_mode = DC_PRED;
mi->ref_frame[0] = ref_frame;
mi->ref_frame[1] = second_ref_frame;
// Evaluate all sub-pel filters irrespective of whether we can use
// them for this frame.
mi->interp_filter =
cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
mi->mv[0].as_int = mi->mv[1].as_int = 0;
x->skip = 0;
set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
// Select prediction reference frames.
for (i = 0; i < MAX_MB_PLANE; i++) {
xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
}
if (ref_frame == INTRA_FRAME) {
TX_SIZE uv_tx;
struct macroblockd_plane *const pd = &xd->plane[1];
memset(x->skip_txfm, 0, sizeof(x->skip_txfm));
super_block_yrd(cpi, x, &rate_y, &distortion_y, &skippable, NULL, bsize,
best_rd, recon);
if (rate_y == INT_MAX) continue;
uv_tx = uv_txsize_lookup[bsize][mi->tx_size][pd->subsampling_x]
[pd->subsampling_y];
if (rate_uv_intra[uv_tx] == INT_MAX) {
choose_intra_uv_mode(cpi, x, ctx, bsize, uv_tx, &rate_uv_intra[uv_tx],
&rate_uv_tokenonly[uv_tx], &dist_uv[uv_tx],
&skip_uv[uv_tx], &mode_uv[uv_tx]);
}
rate_uv = rate_uv_tokenonly[uv_tx];
distortion_uv = dist_uv[uv_tx];
skippable = skippable && skip_uv[uv_tx];
mi->uv_mode = mode_uv[uv_tx];
rate2 = rate_y + cpi->mbmode_cost[mi->mode] + rate_uv_intra[uv_tx];
if (this_mode != DC_PRED && this_mode != TM_PRED)
rate2 += intra_cost_penalty;
distortion2 = distortion_y + distortion_uv;
} else {
this_rd = handle_inter_mode(
cpi, x, bsize, &rate2, &distortion2, &skippable, &rate_y, &rate_uv,
recon, &disable_skip, frame_mv, mi_row, mi_col, single_newmv,
single_inter_filter, single_skippable, &total_sse, best_rd,
&mask_filter, filter_cache);
if (this_rd == INT64_MAX) continue;
compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
}
// Estimate the reference frame signaling cost and add it
// to the rolling cost variable.
if (comp_pred) {
rate2 += ref_costs_comp[ref_frame];
} else {
rate2 += ref_costs_single[ref_frame];
}
if (!disable_skip) {
const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
if (skippable) {
// Back out the coefficient coding costs
rate2 -= (rate_y + rate_uv);
// Cost the skip mb case
rate2 += skip_cost1;
} else if (ref_frame != INTRA_FRAME && !xd->lossless &&
!cpi->oxcf.sharpness) {
if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
distortion2) <
RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
} else {
// FIXME(rbultje) make this work for splitmv also
assert(total_sse >= 0);
rate2 += skip_cost1;
distortion2 = total_sse;
rate2 -= (rate_y + rate_uv);
this_skip2 = 1;
}
} else {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
}
// Calculate the final RD estimate for this mode.
this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
}
if (recon) {
// In film mode bias against DC pred and other intra if there is a
// significant difference between the variance of the sub blocks in the
// the source. Also apply some bias against compound modes which also
// tend to blur fine texture such as film grain over time.
//
// The sub block test here acts in the case where one or more sub
// blocks have high relatively variance but others relatively low
// variance. Here the high variance sub blocks may push the
// total variance for the current block size over the thresholds
// used in rd_variance_adjustment() below.
if (cpi->oxcf.content == VP9E_CONTENT_FILM) {
if (bsize >= BLOCK_16X16) {
int min_energy, max_energy;
vp9_get_sub_block_energy(cpi, x, mi_row, mi_col, bsize, &min_energy,
&max_energy);
if (max_energy > min_energy) {
if (ref_frame == INTRA_FRAME) {
if (this_mode == DC_PRED)
this_rd += (this_rd * (max_energy - min_energy));
else
this_rd += (this_rd * (max_energy - min_energy)) / 4;
} else if (second_ref_frame > INTRA_FRAME) {
this_rd += this_rd / 4;
}
}
}
}
// Apply an adjustment to the rd value based on the similarity of the
// source variance and reconstructed variance.
rd_variance_adjustment(cpi, x, bsize, &this_rd, recon, ref_frame,
second_ref_frame, this_mode);
}
if (ref_frame == INTRA_FRAME) {
// Keep record of best intra rd
if (this_rd < best_intra_rd) {
best_intra_rd = this_rd;
best_intra_mode = mi->mode;
}
}
if (!disable_skip && ref_frame == INTRA_FRAME) {
for (i = 0; i < REFERENCE_MODES; ++i)
best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
}
// Did this mode help.. i.e. is it the new best mode
if (this_rd < best_rd || x->skip) {
int max_plane = MAX_MB_PLANE;
if (!mode_excluded) {
// Note index of best mode so far
best_mode_index = mode_index;
if (ref_frame == INTRA_FRAME) {
/* required for left and above block mv */
mi->mv[0].as_int = 0;
max_plane = 1;
// Initialize interp_filter here so we do not have to check for
// inter block modes in get_pred_context_switchable_interp()
mi->interp_filter = SWITCHABLE_FILTERS;
} else {
best_pred_sse = x->pred_sse[ref_frame];
}
rd_cost->rate = rate2;
rd_cost->dist = distortion2;
rd_cost->rdcost = this_rd;
best_rd = this_rd;
best_mbmode = *mi;
best_skip2 = this_skip2;
best_mode_skippable = skippable;
if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
memcpy(ctx->zcoeff_blk, x->zcoeff_blk[mi->tx_size],
sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
ctx->sum_y_eobs = x->sum_y_eobs[mi->tx_size];
// TODO(debargha): enhance this test with a better distortion prediction
// based on qp, activity mask and history
if ((mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
(mode_index > MIN_EARLY_TERM_INDEX)) {
int qstep = xd->plane[0].dequant[1];
// TODO(debargha): Enhance this by specializing for each mode_index
int scale = 4;
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
qstep >>= (xd->bd - 8);
}
#endif // CONFIG_VP9_HIGHBITDEPTH
if (x->source_variance < UINT_MAX) {
const int var_adjust = (x->source_variance < 16);
scale -= var_adjust;
}
if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
early_term = 1;
}
}
}
}
/* keep record of best compound/single-only prediction */
if (!disable_skip && ref_frame != INTRA_FRAME) {
int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
if (cm->reference_mode == REFERENCE_MODE_SELECT) {
single_rate = rate2 - compmode_cost;
hybrid_rate = rate2;
} else {
single_rate = rate2;
hybrid_rate = rate2 + compmode_cost;
}
single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
if (!comp_pred) {
if (single_rd < best_pred_rd[SINGLE_REFERENCE])
best_pred_rd[SINGLE_REFERENCE] = single_rd;
} else {
if (single_rd < best_pred_rd[COMPOUND_REFERENCE])
best_pred_rd[COMPOUND_REFERENCE] = single_rd;
}
if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
/* keep record of best filter type */
if (!mode_excluded && cm->interp_filter != BILINEAR) {
int64_t ref =
filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
: cm->interp_filter];
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
int64_t adj_rd;
if (ref == INT64_MAX)
adj_rd = 0;
else if (filter_cache[i] == INT64_MAX)
// when early termination is triggered, the encoder does not have
// access to the rate-distortion cost. it only knows that the cost
// should be above the maximum valid value. hence it takes the known
// maximum plus an arbitrary constant as the rate-distortion cost.
adj_rd = mask_filter - ref + 10;
else
adj_rd = filter_cache[i] - ref;
adj_rd += this_rd;
best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
}
}
}
if (early_term) break;
if (x->skip && !comp_pred) break;
}
// The inter modes' rate costs are not calculated precisely in some cases.
// Therefore, sometimes, NEWMV is chosen instead of NEARESTMV, NEARMV, and
// ZEROMV. Here, checks are added for those cases, and the mode decisions
// are corrected.
if (best_mbmode.mode == NEWMV) {
const MV_REFERENCE_FRAME refs[2] = { best_mbmode.ref_frame[0],
best_mbmode.ref_frame[1] };
int comp_pred_mode = refs[1] > INTRA_FRAME;
if (frame_mv[NEARESTMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
((comp_pred_mode &&
frame_mv[NEARESTMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
!comp_pred_mode))
best_mbmode.mode = NEARESTMV;
else if (frame_mv[NEARMV][refs[0]].as_int == best_mbmode.mv[0].as_int &&
((comp_pred_mode &&
frame_mv[NEARMV][refs[1]].as_int == best_mbmode.mv[1].as_int) ||
!comp_pred_mode))
best_mbmode.mode = NEARMV;
else if (best_mbmode.mv[0].as_int == 0 &&
((comp_pred_mode && best_mbmode.mv[1].as_int == 0) ||
!comp_pred_mode))
best_mbmode.mode = ZEROMV;
}
if (best_mode_index < 0 || best_rd >= best_rd_so_far) {
// If adaptive interp filter is enabled, then the current leaf node of 8x8
// data is needed for sub8x8. Hence preserve the context.
#if CONFIG_CONSISTENT_RECODE
if (bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
#else
if (cpi->row_mt && bsize == BLOCK_8X8) ctx->mic = *xd->mi[0];
#endif
rd_cost->rate = INT_MAX;
rd_cost->rdcost = INT64_MAX;
return;
}
// If we used an estimate for the uv intra rd in the loop above...
if (sf->use_uv_intra_rd_estimate) {
// Do Intra UV best rd mode selection if best mode choice above was intra.
if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
TX_SIZE uv_tx_size;
*mi = best_mbmode;
uv_tx_size = get_uv_tx_size(mi, &xd->plane[1]);
rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra[uv_tx_size],
&rate_uv_tokenonly[uv_tx_size],
&dist_uv[uv_tx_size], &skip_uv[uv_tx_size],
bsize < BLOCK_8X8 ? BLOCK_8X8 : bsize,
uv_tx_size);
}
}
assert((cm->interp_filter == SWITCHABLE) ||
(cm->interp_filter == best_mbmode.interp_filter) ||
!is_inter_block(&best_mbmode));
if (!cpi->rc.is_src_frame_alt_ref)
vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
sf->adaptive_rd_thresh, bsize, best_mode_index);
// macroblock modes
*mi = best_mbmode;
x->skip |= best_skip2;
for (i = 0; i < REFERENCE_MODES; ++i) {
if (best_pred_rd[i] == INT64_MAX)
best_pred_diff[i] = INT_MIN;
else
best_pred_diff[i] = best_rd - best_pred_rd[i];
}
if (!x->skip) {
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
if (best_filter_rd[i] == INT64_MAX)
best_filter_diff[i] = 0;
else
best_filter_diff[i] = best_rd - best_filter_rd[i];
}
if (cm->interp_filter == SWITCHABLE)
assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
} else {
vp9_zero(best_filter_diff);
}
// TODO(yunqingwang): Moving this line in front of the above best_filter_diff
// updating code causes PSNR loss. Need to figure out the confliction.
x->skip |= best_mode_skippable;
if (!x->skip && !x->select_tx_size) {
int has_high_freq_coeff = 0;
int plane;
int max_plane = is_inter_block(xd->mi[0]) ? MAX_MB_PLANE : 1;
for (plane = 0; plane < max_plane; ++plane) {
x->plane[plane].eobs = ctx->eobs_pbuf[plane][1];
has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
}
for (plane = max_plane; plane < MAX_MB_PLANE; ++plane) {
x->plane[plane].eobs = ctx->eobs_pbuf[plane][2];
has_high_freq_coeff |= vp9_has_high_freq_in_plane(x, bsize, plane);
}
best_mode_skippable |= !has_high_freq_coeff;
}
assert(best_mode_index >= 0);
store_coding_context(x, ctx, best_mode_index, best_pred_diff,
best_filter_diff, best_mode_skippable);
}
void vp9_rd_pick_inter_mode_sb_seg_skip(VP9_COMP *cpi, TileDataEnc *tile_data,
MACROBLOCK *x, RD_COST *rd_cost,
BLOCK_SIZE bsize,
PICK_MODE_CONTEXT *ctx,
int64_t best_rd_so_far) {
VP9_COMMON *const cm = &cpi->common;
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
unsigned char segment_id = mi->segment_id;
const int comp_pred = 0;
int i;
int64_t best_pred_diff[REFERENCE_MODES];
int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
vpx_prob comp_mode_p;
INTERP_FILTER best_filter = SWITCHABLE;
int64_t this_rd = INT64_MAX;
int rate2 = 0;
const int64_t distortion2 = 0;
x->skip_encode = cpi->sf.skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
&comp_mode_p);
for (i = 0; i < MAX_REF_FRAMES; ++i) x->pred_sse[i] = INT_MAX;
for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i) x->pred_mv_sad[i] = INT_MAX;
rd_cost->rate = INT_MAX;
assert(segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP));
mi->mode = ZEROMV;
mi->uv_mode = DC_PRED;
mi->ref_frame[0] = LAST_FRAME;
mi->ref_frame[1] = NONE;
mi->mv[0].as_int = 0;
x->skip = 1;
ctx->sum_y_eobs = 0;
if (cm->interp_filter != BILINEAR) {
best_filter = EIGHTTAP;
if (cm->interp_filter == SWITCHABLE &&
x->source_variance >= cpi->sf.disable_filter_search_var_thresh) {
int rs;
int best_rs = INT_MAX;
for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
mi->interp_filter = i;
rs = vp9_get_switchable_rate(cpi, xd);
if (rs < best_rs) {
best_rs = rs;
best_filter = mi->interp_filter;
}
}
}
}
// Set the appropriate filter
if (cm->interp_filter == SWITCHABLE) {
mi->interp_filter = best_filter;
rate2 += vp9_get_switchable_rate(cpi, xd);
} else {
mi->interp_filter = cm->interp_filter;
}
if (cm->reference_mode == REFERENCE_MODE_SELECT)
rate2 += vp9_cost_bit(comp_mode_p, comp_pred);
// Estimate the reference frame signaling cost and add it
// to the rolling cost variable.
rate2 += ref_costs_single[LAST_FRAME];
this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
rd_cost->rate = rate2;
rd_cost->dist = distortion2;
rd_cost->rdcost = this_rd;
if (this_rd >= best_rd_so_far) {
rd_cost->rate = INT_MAX;
rd_cost->rdcost = INT64_MAX;
return;
}
assert((cm->interp_filter == SWITCHABLE) ||
(cm->interp_filter == mi->interp_filter));
vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact,
cpi->sf.adaptive_rd_thresh, bsize, THR_ZEROMV);
vp9_zero(best_pred_diff);
vp9_zero(best_filter_diff);
if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, MAX_MB_PLANE);
store_coding_context(x, ctx, THR_ZEROMV, best_pred_diff, best_filter_diff, 0);
}
void vp9_rd_pick_inter_mode_sub8x8(VP9_COMP *cpi, TileDataEnc *tile_data,
MACROBLOCK *x, int mi_row, int mi_col,
RD_COST *rd_cost, BLOCK_SIZE bsize,
PICK_MODE_CONTEXT *ctx,
int64_t best_rd_so_far) {
VP9_COMMON *const cm = &cpi->common;
RD_OPT *const rd_opt = &cpi->rd;
SPEED_FEATURES *const sf = &cpi->sf;
MACROBLOCKD *const xd = &x->e_mbd;
MODE_INFO *const mi = xd->mi[0];
const struct segmentation *const seg = &cm->seg;
MV_REFERENCE_FRAME ref_frame, second_ref_frame;
unsigned char segment_id = mi->segment_id;
int comp_pred, i;
int_mv frame_mv[MB_MODE_COUNT][MAX_REF_FRAMES];
struct buf_2d yv12_mb[4][MAX_MB_PLANE];
static const int flag_list[4] = { 0, VP9_LAST_FLAG, VP9_GOLD_FLAG,
VP9_ALT_FLAG };
int64_t best_rd = best_rd_so_far;
int64_t best_yrd = best_rd_so_far; // FIXME(rbultje) more precise
int64_t best_pred_diff[REFERENCE_MODES];
int64_t best_pred_rd[REFERENCE_MODES];
int64_t best_filter_rd[SWITCHABLE_FILTER_CONTEXTS];
int64_t best_filter_diff[SWITCHABLE_FILTER_CONTEXTS];
MODE_INFO best_mbmode;
int ref_index, best_ref_index = 0;
unsigned int ref_costs_single[MAX_REF_FRAMES], ref_costs_comp[MAX_REF_FRAMES];
vpx_prob comp_mode_p;
INTERP_FILTER tmp_best_filter = SWITCHABLE;
int rate_uv_intra, rate_uv_tokenonly;
int64_t dist_uv;
int skip_uv;
PREDICTION_MODE mode_uv = DC_PRED;
const int intra_cost_penalty =
vp9_get_intra_cost_penalty(cpi, bsize, cm->base_qindex, cm->y_dc_delta_q);
int_mv seg_mvs[4][MAX_REF_FRAMES];
b_mode_info best_bmodes[4];
int best_skip2 = 0;
int ref_frame_skip_mask[2] = { 0 };
int64_t mask_filter = 0;
int64_t filter_cache[SWITCHABLE_FILTER_CONTEXTS];
int internal_active_edge =
vp9_active_edge_sb(cpi, mi_row, mi_col) && vp9_internal_image_edge(cpi);
const int *const rd_thresh_freq_fact = tile_data->thresh_freq_fact[bsize];
x->skip_encode = sf->skip_encode_frame && x->q_index < QIDX_SKIP_THRESH;
memset(x->zcoeff_blk[TX_4X4], 0, 4);
vp9_zero(best_mbmode);
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i) filter_cache[i] = INT64_MAX;
for (i = 0; i < 4; i++) {
int j;
for (j = 0; j < MAX_REF_FRAMES; j++) seg_mvs[i][j].as_int = INVALID_MV;
}
estimate_ref_frame_costs(cm, xd, segment_id, ref_costs_single, ref_costs_comp,
&comp_mode_p);
for (i = 0; i < REFERENCE_MODES; ++i) best_pred_rd[i] = INT64_MAX;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = INT64_MAX;
rate_uv_intra = INT_MAX;
rd_cost->rate = INT_MAX;
for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ref_frame++) {
if (cpi->ref_frame_flags & flag_list[ref_frame]) {
setup_buffer_inter(cpi, x, ref_frame, bsize, mi_row, mi_col,
frame_mv[NEARESTMV], frame_mv[NEARMV], yv12_mb);
} else {
ref_frame_skip_mask[0] |= (1 << ref_frame);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
}
frame_mv[NEWMV][ref_frame].as_int = INVALID_MV;
frame_mv[ZEROMV][ref_frame].as_int = 0;
}
for (ref_index = 0; ref_index < MAX_REFS; ++ref_index) {
int mode_excluded = 0;
int64_t this_rd = INT64_MAX;
int disable_skip = 0;
int compmode_cost = 0;
int rate2 = 0, rate_y = 0, rate_uv = 0;
int64_t distortion2 = 0, distortion_y = 0, distortion_uv = 0;
int skippable = 0;
int i;
int this_skip2 = 0;
int64_t total_sse = INT_MAX;
int early_term = 0;
struct buf_2d backup_yv12[2][MAX_MB_PLANE];
ref_frame = vp9_ref_order[ref_index].ref_frame[0];
second_ref_frame = vp9_ref_order[ref_index].ref_frame[1];
vp9_zero(x->sum_y_eobs);
#if CONFIG_BETTER_HW_COMPATIBILITY
// forbid 8X4 and 4X8 partitions if any reference frame is scaled.
if (bsize == BLOCK_8X4 || bsize == BLOCK_4X8) {
int ref_scaled = ref_frame > INTRA_FRAME &&
vp9_is_scaled(&cm->frame_refs[ref_frame - 1].sf);
if (second_ref_frame > INTRA_FRAME)
ref_scaled += vp9_is_scaled(&cm->frame_refs[second_ref_frame - 1].sf);
if (ref_scaled) continue;
}
#endif
// Look at the reference frame of the best mode so far and set the
// skip mask to look at a subset of the remaining modes.
if (ref_index > 2 && sf->mode_skip_start < MAX_MODES) {
if (ref_index == 3) {
switch (best_mbmode.ref_frame[0]) {
case INTRA_FRAME: break;
case LAST_FRAME:
ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << ALTREF_FRAME);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
break;
case GOLDEN_FRAME:
ref_frame_skip_mask[0] |= (1 << LAST_FRAME) | (1 << ALTREF_FRAME);
ref_frame_skip_mask[1] |= SECOND_REF_FRAME_MASK;
break;
case ALTREF_FRAME:
ref_frame_skip_mask[0] |= (1 << GOLDEN_FRAME) | (1 << LAST_FRAME);
break;
case NONE:
case MAX_REF_FRAMES: assert(0 && "Invalid Reference frame"); break;
}
}
}
if ((ref_frame_skip_mask[0] & (1 << ref_frame)) &&
(ref_frame_skip_mask[1] & (1 << VPXMAX(0, second_ref_frame))))
continue;
// Test best rd so far against threshold for trying this mode.
if (!internal_active_edge &&
rd_less_than_thresh(best_rd,
rd_opt->threshes[segment_id][bsize][ref_index],
&rd_thresh_freq_fact[ref_index]))
continue;
// This is only used in motion vector unit test.
if (cpi->oxcf.motion_vector_unit_test && ref_frame == INTRA_FRAME) continue;
comp_pred = second_ref_frame > INTRA_FRAME;
if (comp_pred) {
if (!cpi->allow_comp_inter_inter) continue;
if (cm->ref_frame_sign_bias[ref_frame] ==
cm->ref_frame_sign_bias[second_ref_frame])
continue;
if (!(cpi->ref_frame_flags & flag_list[second_ref_frame])) continue;
// Do not allow compound prediction if the segment level reference frame
// feature is in use as in this case there can only be one reference.
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) continue;
if ((sf->mode_search_skip_flags & FLAG_SKIP_COMP_BESTINTRA) &&
best_mbmode.ref_frame[0] == INTRA_FRAME)
continue;
}
if (comp_pred)
mode_excluded = cm->reference_mode == SINGLE_REFERENCE;
else if (ref_frame != INTRA_FRAME)
mode_excluded = cm->reference_mode == COMPOUND_REFERENCE;
// If the segment reference frame feature is enabled....
// then do nothing if the current ref frame is not allowed..
if (segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME) &&
get_segdata(seg, segment_id, SEG_LVL_REF_FRAME) != (int)ref_frame) {
continue;
// Disable this drop out case if the ref frame
// segment level feature is enabled for this segment. This is to
// prevent the possibility that we end up unable to pick any mode.
} else if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME)) {
// Only consider ZEROMV/ALTREF_FRAME for alt ref frame,
// unless ARNR filtering is enabled in which case we want
// an unfiltered alternative. We allow near/nearest as well
// because they may result in zero-zero MVs but be cheaper.
if (cpi->rc.is_src_frame_alt_ref && (cpi->oxcf.arnr_max_frames == 0))
continue;
}
mi->tx_size = TX_4X4;
mi->uv_mode = DC_PRED;
mi->ref_frame[0] = ref_frame;
mi->ref_frame[1] = second_ref_frame;
// Evaluate all sub-pel filters irrespective of whether we can use
// them for this frame.
mi->interp_filter =
cm->interp_filter == SWITCHABLE ? EIGHTTAP : cm->interp_filter;
x->skip = 0;
set_ref_ptrs(cm, xd, ref_frame, second_ref_frame);
// Select prediction reference frames.
for (i = 0; i < MAX_MB_PLANE; i++) {
xd->plane[i].pre[0] = yv12_mb[ref_frame][i];
if (comp_pred) xd->plane[i].pre[1] = yv12_mb[second_ref_frame][i];
}
if (ref_frame == INTRA_FRAME) {
int rate;
if (rd_pick_intra_sub_8x8_y_mode(cpi, x, &rate, &rate_y, &distortion_y,
best_rd) >= best_rd)
continue;
rate2 += rate;
rate2 += intra_cost_penalty;
distortion2 += distortion_y;
if (rate_uv_intra == INT_MAX) {
choose_intra_uv_mode(cpi, x, ctx, bsize, TX_4X4, &rate_uv_intra,
&rate_uv_tokenonly, &dist_uv, &skip_uv, &mode_uv);
}
rate2 += rate_uv_intra;
rate_uv = rate_uv_tokenonly;
distortion2 += dist_uv;
distortion_uv = dist_uv;
mi->uv_mode = mode_uv;
} else {
int rate;
int64_t distortion;
int64_t this_rd_thresh;
int64_t tmp_rd, tmp_best_rd = INT64_MAX, tmp_best_rdu = INT64_MAX;
int tmp_best_rate = INT_MAX, tmp_best_ratey = INT_MAX;
int64_t tmp_best_distortion = INT_MAX, tmp_best_sse, uv_sse;
int tmp_best_skippable = 0;
int switchable_filter_index;
int_mv *second_ref =
comp_pred ? &x->mbmi_ext->ref_mvs[second_ref_frame][0] : NULL;
b_mode_info tmp_best_bmodes[16];
MODE_INFO tmp_best_mbmode;
BEST_SEG_INFO bsi[SWITCHABLE_FILTERS];
int pred_exists = 0;
int uv_skippable;
YV12_BUFFER_CONFIG *scaled_ref_frame[2] = { NULL, NULL };
int ref;
for (ref = 0; ref < 2; ++ref) {
scaled_ref_frame[ref] =
mi->ref_frame[ref] > INTRA_FRAME
? vp9_get_scaled_ref_frame(cpi, mi->ref_frame[ref])
: NULL;
if (scaled_ref_frame[ref]) {
int i;
// Swap out the reference frame for a version that's been scaled to
// match the resolution of the current frame, allowing the existing
// motion search code to be used without additional modifications.
for (i = 0; i < MAX_MB_PLANE; i++)
backup_yv12[ref][i] = xd->plane[i].pre[ref];
vp9_setup_pre_planes(xd, ref, scaled_ref_frame[ref], mi_row, mi_col,
NULL);
}
}
this_rd_thresh = (ref_frame == LAST_FRAME)
? rd_opt->threshes[segment_id][bsize][THR_LAST]
: rd_opt->threshes[segment_id][bsize][THR_ALTR];
this_rd_thresh = (ref_frame == GOLDEN_FRAME)
? rd_opt->threshes[segment_id][bsize][THR_GOLD]
: this_rd_thresh;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; ++i)
filter_cache[i] = INT64_MAX;
if (cm->interp_filter != BILINEAR) {
tmp_best_filter = EIGHTTAP;
if (x->source_variance < sf->disable_filter_search_var_thresh) {
tmp_best_filter = EIGHTTAP;
} else if (sf->adaptive_pred_interp_filter == 1 &&
ctx->pred_interp_filter < SWITCHABLE) {
tmp_best_filter = ctx->pred_interp_filter;
} else if (sf->adaptive_pred_interp_filter == 2) {
tmp_best_filter = ctx->pred_interp_filter < SWITCHABLE
? ctx->pred_interp_filter
: 0;
} else {
for (switchable_filter_index = 0;
switchable_filter_index < SWITCHABLE_FILTERS;
++switchable_filter_index) {
int newbest, rs;
int64_t rs_rd;
MB_MODE_INFO_EXT *mbmi_ext = x->mbmi_ext;
mi->interp_filter = switchable_filter_index;
tmp_rd = rd_pick_best_sub8x8_mode(
cpi, x, &mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
&rate, &rate_y, &distortion, &skippable, &total_sse,
(int)this_rd_thresh, seg_mvs, bsi, switchable_filter_index,
mi_row, mi_col);
if (tmp_rd == INT64_MAX) continue;
rs = vp9_get_switchable_rate(cpi, xd);
rs_rd = RDCOST(x->rdmult, x->rddiv, rs, 0);
filter_cache[switchable_filter_index] = tmp_rd;
filter_cache[SWITCHABLE_FILTERS] =
VPXMIN(filter_cache[SWITCHABLE_FILTERS], tmp_rd + rs_rd);
if (cm->interp_filter == SWITCHABLE) tmp_rd += rs_rd;
mask_filter = VPXMAX(mask_filter, tmp_rd);
newbest = (tmp_rd < tmp_best_rd);
if (newbest) {
tmp_best_filter = mi->interp_filter;
tmp_best_rd = tmp_rd;
}
if ((newbest && cm->interp_filter == SWITCHABLE) ||
(mi->interp_filter == cm->interp_filter &&
cm->interp_filter != SWITCHABLE)) {
tmp_best_rdu = tmp_rd;
tmp_best_rate = rate;
tmp_best_ratey = rate_y;
tmp_best_distortion = distortion;
tmp_best_sse = total_sse;
tmp_best_skippable = skippable;
tmp_best_mbmode = *mi;
for (i = 0; i < 4; i++) {
tmp_best_bmodes[i] = xd->mi[0]->bmi[i];
x->zcoeff_blk[TX_4X4][i] = !x->plane[0].eobs[i];
x->sum_y_eobs[TX_4X4] += x->plane[0].eobs[i];
}
pred_exists = 1;
if (switchable_filter_index == 0 && sf->use_rd_breakout &&
best_rd < INT64_MAX) {
if (tmp_best_rdu / 2 > best_rd) {
// skip searching the other filters if the first is
// already substantially larger than the best so far
tmp_best_filter = mi->interp_filter;
tmp_best_rdu = INT64_MAX;
break;
}
}
}
} // switchable_filter_index loop
}
}
if (tmp_best_rdu == INT64_MAX && pred_exists) continue;
mi->interp_filter = (cm->interp_filter == SWITCHABLE ? tmp_best_filter
: cm->interp_filter);
if (!pred_exists) {
// Handles the special case when a filter that is not in the
// switchable list (bilinear, 6-tap) is indicated at the frame level
tmp_rd = rd_pick_best_sub8x8_mode(
cpi, x, &x->mbmi_ext->ref_mvs[ref_frame][0], second_ref, best_yrd,
&rate, &rate_y, &distortion, &skippable, &total_sse,
(int)this_rd_thresh, seg_mvs, bsi, 0, mi_row, mi_col);
if (tmp_rd == INT64_MAX) continue;
} else {
total_sse = tmp_best_sse;
rate = tmp_best_rate;
rate_y = tmp_best_ratey;
distortion = tmp_best_distortion;
skippable = tmp_best_skippable;
*mi = tmp_best_mbmode;
for (i = 0; i < 4; i++) xd->mi[0]->bmi[i] = tmp_best_bmodes[i];
}
rate2 += rate;
distortion2 += distortion;
if (cm->interp_filter == SWITCHABLE)
rate2 += vp9_get_switchable_rate(cpi, xd);
if (!mode_excluded)
mode_excluded = comp_pred ? cm->reference_mode == SINGLE_REFERENCE
: cm->reference_mode == COMPOUND_REFERENCE;
compmode_cost = vp9_cost_bit(comp_mode_p, comp_pred);
tmp_best_rdu =
best_rd - VPXMIN(RDCOST(x->rdmult, x->rddiv, rate2, distortion2),
RDCOST(x->rdmult, x->rddiv, 0, total_sse));
if (tmp_best_rdu > 0) {
// If even the 'Y' rd value of split is higher than best so far
// then dont bother looking at UV
vp9_build_inter_predictors_sbuv(&x->e_mbd, mi_row, mi_col, BLOCK_8X8);
memset(x->skip_txfm, SKIP_TXFM_NONE, sizeof(x->skip_txfm));
if (!super_block_uvrd(cpi, x, &rate_uv, &distortion_uv, &uv_skippable,
&uv_sse, BLOCK_8X8, tmp_best_rdu)) {
for (ref = 0; ref < 2; ++ref) {
if (scaled_ref_frame[ref]) {
int i;
for (i = 0; i < MAX_MB_PLANE; ++i)
xd->plane[i].pre[ref] = backup_yv12[ref][i];
}
}
continue;
}
rate2 += rate_uv;
distortion2 += distortion_uv;
skippable = skippable && uv_skippable;
total_sse += uv_sse;
}
for (ref = 0; ref < 2; ++ref) {
if (scaled_ref_frame[ref]) {
// Restore the prediction frame pointers to their unscaled versions.
int i;
for (i = 0; i < MAX_MB_PLANE; ++i)
xd->plane[i].pre[ref] = backup_yv12[ref][i];
}
}
}
if (cm->reference_mode == REFERENCE_MODE_SELECT) rate2 += compmode_cost;
// Estimate the reference frame signaling cost and add it
// to the rolling cost variable.
if (second_ref_frame > INTRA_FRAME) {
rate2 += ref_costs_comp[ref_frame];
} else {
rate2 += ref_costs_single[ref_frame];
}
if (!disable_skip) {
const vpx_prob skip_prob = vp9_get_skip_prob(cm, xd);
const int skip_cost0 = vp9_cost_bit(skip_prob, 0);
const int skip_cost1 = vp9_cost_bit(skip_prob, 1);
// Skip is never coded at the segment level for sub8x8 blocks and instead
// always coded in the bitstream at the mode info level.
if (ref_frame != INTRA_FRAME && !xd->lossless) {
if (RDCOST(x->rdmult, x->rddiv, rate_y + rate_uv + skip_cost0,
distortion2) <
RDCOST(x->rdmult, x->rddiv, skip_cost1, total_sse)) {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
} else {
// FIXME(rbultje) make this work for splitmv also
rate2 += skip_cost1;
distortion2 = total_sse;
assert(total_sse >= 0);
rate2 -= (rate_y + rate_uv);
rate_y = 0;
rate_uv = 0;
this_skip2 = 1;
}
} else {
// Add in the cost of the no skip flag.
rate2 += skip_cost0;
}
// Calculate the final RD estimate for this mode.
this_rd = RDCOST(x->rdmult, x->rddiv, rate2, distortion2);
}
if (!disable_skip && ref_frame == INTRA_FRAME) {
for (i = 0; i < REFERENCE_MODES; ++i)
best_pred_rd[i] = VPXMIN(best_pred_rd[i], this_rd);
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++)
best_filter_rd[i] = VPXMIN(best_filter_rd[i], this_rd);
}
// Did this mode help.. i.e. is it the new best mode
if (this_rd < best_rd || x->skip) {
if (!mode_excluded) {
int max_plane = MAX_MB_PLANE;
// Note index of best mode so far
best_ref_index = ref_index;
if (ref_frame == INTRA_FRAME) {
/* required for left and above block mv */
mi->mv[0].as_int = 0;
max_plane = 1;
// Initialize interp_filter here so we do not have to check for
// inter block modes in get_pred_context_switchable_interp()
mi->interp_filter = SWITCHABLE_FILTERS;
}
rd_cost->rate = rate2;
rd_cost->dist = distortion2;
rd_cost->rdcost = this_rd;
best_rd = this_rd;
best_yrd =
best_rd - RDCOST(x->rdmult, x->rddiv, rate_uv, distortion_uv);
best_mbmode = *mi;
best_skip2 = this_skip2;
if (!x->select_tx_size) swap_block_ptr(x, ctx, 1, 0, 0, max_plane);
memcpy(ctx->zcoeff_blk, x->zcoeff_blk[TX_4X4],
sizeof(ctx->zcoeff_blk[0]) * ctx->num_4x4_blk);
ctx->sum_y_eobs = x->sum_y_eobs[TX_4X4];
for (i = 0; i < 4; i++) best_bmodes[i] = xd->mi[0]->bmi[i];
// TODO(debargha): enhance this test with a better distortion prediction
// based on qp, activity mask and history
if ((sf->mode_search_skip_flags & FLAG_EARLY_TERMINATE) &&
(ref_index > MIN_EARLY_TERM_INDEX)) {
int qstep = xd->plane[0].dequant[1];
// TODO(debargha): Enhance this by specializing for each mode_index
int scale = 4;
#if CONFIG_VP9_HIGHBITDEPTH
if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
qstep >>= (xd->bd - 8);
}
#endif // CONFIG_VP9_HIGHBITDEPTH
if (x->source_variance < UINT_MAX) {
const int var_adjust = (x->source_variance < 16);
scale -= var_adjust;
}
if (ref_frame > INTRA_FRAME && distortion2 * scale < qstep * qstep) {
early_term = 1;
}
}
}
}
/* keep record of best compound/single-only prediction */
if (!disable_skip && ref_frame != INTRA_FRAME) {
int64_t single_rd, hybrid_rd, single_rate, hybrid_rate;
if (cm->reference_mode == REFERENCE_MODE_SELECT) {
single_rate = rate2 - compmode_cost;
hybrid_rate = rate2;
} else {
single_rate = rate2;
hybrid_rate = rate2 + compmode_cost;
}
single_rd = RDCOST(x->rdmult, x->rddiv, single_rate, distortion2);
hybrid_rd = RDCOST(x->rdmult, x->rddiv, hybrid_rate, distortion2);
if (!comp_pred && single_rd < best_pred_rd[SINGLE_REFERENCE])
best_pred_rd[SINGLE_REFERENCE] = single_rd;
else if (comp_pred && single_rd < best_pred_rd[COMPOUND_REFERENCE])
best_pred_rd[COMPOUND_REFERENCE] = single_rd;
if (hybrid_rd < best_pred_rd[REFERENCE_MODE_SELECT])
best_pred_rd[REFERENCE_MODE_SELECT] = hybrid_rd;
}
/* keep record of best filter type */
if (!mode_excluded && !disable_skip && ref_frame != INTRA_FRAME &&
cm->interp_filter != BILINEAR) {
int64_t ref =
filter_cache[cm->interp_filter == SWITCHABLE ? SWITCHABLE_FILTERS
: cm->interp_filter];
int64_t adj_rd;
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
if (ref == INT64_MAX)
adj_rd = 0;
else if (filter_cache[i] == INT64_MAX)
// when early termination is triggered, the encoder does not have
// access to the rate-distortion cost. it only knows that the cost
// should be above the maximum valid value. hence it takes the known
// maximum plus an arbitrary constant as the rate-distortion cost.
adj_rd = mask_filter - ref + 10;
else
adj_rd = filter_cache[i] - ref;
adj_rd += this_rd;
best_filter_rd[i] = VPXMIN(best_filter_rd[i], adj_rd);
}
}
if (early_term) break;
if (x->skip && !comp_pred) break;
}
if (best_rd >= best_rd_so_far) {
rd_cost->rate = INT_MAX;
rd_cost->rdcost = INT64_MAX;
return;
}
// If we used an estimate for the uv intra rd in the loop above...
if (sf->use_uv_intra_rd_estimate) {
// Do Intra UV best rd mode selection if best mode choice above was intra.
if (best_mbmode.ref_frame[0] == INTRA_FRAME) {
*mi = best_mbmode;
rd_pick_intra_sbuv_mode(cpi, x, ctx, &rate_uv_intra, &rate_uv_tokenonly,
&dist_uv, &skip_uv, BLOCK_8X8, TX_4X4);
}
}
if (best_rd == INT64_MAX) {
rd_cost->rate = INT_MAX;
rd_cost->dist = INT64_MAX;
rd_cost->rdcost = INT64_MAX;
return;
}
assert((cm->interp_filter == SWITCHABLE) ||
(cm->interp_filter == best_mbmode.interp_filter) ||
!is_inter_block(&best_mbmode));
vp9_update_rd_thresh_fact(tile_data->thresh_freq_fact, sf->adaptive_rd_thresh,
bsize, best_ref_index);
// macroblock modes
*mi = best_mbmode;
x->skip |= best_skip2;
if (!is_inter_block(&best_mbmode)) {
for (i = 0; i < 4; i++) xd->mi[0]->bmi[i].as_mode = best_bmodes[i].as_mode;
} else {
for (i = 0; i < 4; ++i)
memcpy(&xd->mi[0]->bmi[i], &best_bmodes[i], sizeof(b_mode_info));
mi->mv[0].as_int = xd->mi[0]->bmi[3].as_mv[0].as_int;
mi->mv[1].as_int = xd->mi[0]->bmi[3].as_mv[1].as_int;
}
for (i = 0; i < REFERENCE_MODES; ++i) {
if (best_pred_rd[i] == INT64_MAX)
best_pred_diff[i] = INT_MIN;
else
best_pred_diff[i] = best_rd - best_pred_rd[i];
}
if (!x->skip) {
for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) {
if (best_filter_rd[i] == INT64_MAX)
best_filter_diff[i] = 0;
else
best_filter_diff[i] = best_rd - best_filter_rd[i];
}
if (cm->interp_filter == SWITCHABLE)
assert(best_filter_diff[SWITCHABLE_FILTERS] == 0);
} else {
vp9_zero(best_filter_diff);
}
store_coding_context(x, ctx, best_ref_index, best_pred_diff, best_filter_diff,
0);
}
#endif // !CONFIG_REALTIME_ONLY
| 38.135572 | 80 | 0.610816 | [
"vector",
"model",
"transform"
] |
9a9ec27d9e28ce04f373850cdd88c3f6738da29e | 61,075 | c | C | datasets/linux-4.11-rc3/drivers/gpu/drm/bridge/dw-hdmi.c | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/linux-4.11-rc3/drivers/gpu/drm/bridge/dw-hdmi.c | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/linux-4.11-rc3/drivers/gpu/drm/bridge/dw-hdmi.c | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | /*
* DesignWare High-Definition Multimedia Interface (HDMI) driver
*
* Copyright (C) 2013-2015 Mentor Graphics Inc.
* Copyright (C) 2011-2013 Freescale Semiconductor, Inc.
* Copyright (C) 2010, Guennadi Liakhovetski <g.liakhovetski@gmx.de>
*
* 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.
*
*/
#include <linux/module.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/hdmi.h>
#include <linux/mutex.h>
#include <linux/of_device.h>
#include <linux/spinlock.h>
#include <drm/drm_of.h>
#include <drm/drmP.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_edid.h>
#include <drm/drm_encoder_slave.h>
#include <drm/bridge/dw_hdmi.h>
#include "dw-hdmi.h"
#include "dw-hdmi-audio.h"
#define HDMI_EDID_LEN 512
#define RGB 0
#define YCBCR444 1
#define YCBCR422_16BITS 2
#define YCBCR422_8BITS 3
#define XVYCC444 4
enum hdmi_datamap {
RGB444_8B = 0x01,
RGB444_10B = 0x03,
RGB444_12B = 0x05,
RGB444_16B = 0x07,
YCbCr444_8B = 0x09,
YCbCr444_10B = 0x0B,
YCbCr444_12B = 0x0D,
YCbCr444_16B = 0x0F,
YCbCr422_8B = 0x16,
YCbCr422_10B = 0x14,
YCbCr422_12B = 0x12,
};
static const u16 csc_coeff_default[3][4] = {
{ 0x2000, 0x0000, 0x0000, 0x0000 },
{ 0x0000, 0x2000, 0x0000, 0x0000 },
{ 0x0000, 0x0000, 0x2000, 0x0000 }
};
static const u16 csc_coeff_rgb_out_eitu601[3][4] = {
{ 0x2000, 0x6926, 0x74fd, 0x010e },
{ 0x2000, 0x2cdd, 0x0000, 0x7e9a },
{ 0x2000, 0x0000, 0x38b4, 0x7e3b }
};
static const u16 csc_coeff_rgb_out_eitu709[3][4] = {
{ 0x2000, 0x7106, 0x7a02, 0x00a7 },
{ 0x2000, 0x3264, 0x0000, 0x7e6d },
{ 0x2000, 0x0000, 0x3b61, 0x7e25 }
};
static const u16 csc_coeff_rgb_in_eitu601[3][4] = {
{ 0x2591, 0x1322, 0x074b, 0x0000 },
{ 0x6535, 0x2000, 0x7acc, 0x0200 },
{ 0x6acd, 0x7534, 0x2000, 0x0200 }
};
static const u16 csc_coeff_rgb_in_eitu709[3][4] = {
{ 0x2dc5, 0x0d9b, 0x049e, 0x0000 },
{ 0x62f0, 0x2000, 0x7d11, 0x0200 },
{ 0x6756, 0x78ab, 0x2000, 0x0200 }
};
struct hdmi_vmode {
bool mdataenablepolarity;
unsigned int mpixelclock;
unsigned int mpixelrepetitioninput;
unsigned int mpixelrepetitionoutput;
};
struct hdmi_data_info {
unsigned int enc_in_format;
unsigned int enc_out_format;
unsigned int enc_color_depth;
unsigned int colorimetry;
unsigned int pix_repet_factor;
unsigned int hdcp_enable;
struct hdmi_vmode video_mode;
};
struct dw_hdmi_i2c {
struct i2c_adapter adap;
struct mutex lock; /* used to serialize data transfers */
struct completion cmp;
u8 stat;
u8 slave_reg;
bool is_regaddr;
};
struct dw_hdmi_phy_data {
enum dw_hdmi_phy_type type;
const char *name;
bool has_svsret;
};
struct dw_hdmi {
struct drm_connector connector;
struct drm_bridge bridge;
enum dw_hdmi_devtype dev_type;
unsigned int version;
struct platform_device *audio;
struct device *dev;
struct clk *isfr_clk;
struct clk *iahb_clk;
struct dw_hdmi_i2c *i2c;
struct hdmi_data_info hdmi_data;
const struct dw_hdmi_plat_data *plat_data;
int vic;
u8 edid[HDMI_EDID_LEN];
bool cable_plugin;
const struct dw_hdmi_phy_data *phy;
bool phy_enabled;
struct drm_display_mode previous_mode;
struct i2c_adapter *ddc;
void __iomem *regs;
bool sink_is_hdmi;
bool sink_has_audio;
struct mutex mutex; /* for state below and previous_mode */
enum drm_connector_force force; /* mutex-protected force state */
bool disabled; /* DRM has disabled our bridge */
bool bridge_is_on; /* indicates the bridge is on */
bool rxsense; /* rxsense state */
u8 phy_mask; /* desired phy int mask settings */
spinlock_t audio_lock;
struct mutex audio_mutex;
unsigned int sample_rate;
unsigned int audio_cts;
unsigned int audio_n;
bool audio_enable;
void (*write)(struct dw_hdmi *hdmi, u8 val, int offset);
u8 (*read)(struct dw_hdmi *hdmi, int offset);
};
#define HDMI_IH_PHY_STAT0_RX_SENSE \
(HDMI_IH_PHY_STAT0_RX_SENSE0 | HDMI_IH_PHY_STAT0_RX_SENSE1 | \
HDMI_IH_PHY_STAT0_RX_SENSE2 | HDMI_IH_PHY_STAT0_RX_SENSE3)
#define HDMI_PHY_RX_SENSE \
(HDMI_PHY_RX_SENSE0 | HDMI_PHY_RX_SENSE1 | \
HDMI_PHY_RX_SENSE2 | HDMI_PHY_RX_SENSE3)
static void dw_hdmi_writel(struct dw_hdmi *hdmi, u8 val, int offset)
{
writel(val, hdmi->regs + (offset << 2));
}
static u8 dw_hdmi_readl(struct dw_hdmi *hdmi, int offset)
{
return readl(hdmi->regs + (offset << 2));
}
static void dw_hdmi_writeb(struct dw_hdmi *hdmi, u8 val, int offset)
{
writeb(val, hdmi->regs + offset);
}
static u8 dw_hdmi_readb(struct dw_hdmi *hdmi, int offset)
{
return readb(hdmi->regs + offset);
}
static inline void hdmi_writeb(struct dw_hdmi *hdmi, u8 val, int offset)
{
hdmi->write(hdmi, val, offset);
}
static inline u8 hdmi_readb(struct dw_hdmi *hdmi, int offset)
{
return hdmi->read(hdmi, offset);
}
static void hdmi_modb(struct dw_hdmi *hdmi, u8 data, u8 mask, unsigned reg)
{
u8 val = hdmi_readb(hdmi, reg) & ~mask;
val |= data & mask;
hdmi_writeb(hdmi, val, reg);
}
static void hdmi_mask_writeb(struct dw_hdmi *hdmi, u8 data, unsigned int reg,
u8 shift, u8 mask)
{
hdmi_modb(hdmi, data << shift, mask, reg);
}
static void dw_hdmi_i2c_init(struct dw_hdmi *hdmi)
{
/* Software reset */
hdmi_writeb(hdmi, 0x00, HDMI_I2CM_SOFTRSTZ);
/* Set Standard Mode speed (determined to be 100KHz on iMX6) */
hdmi_writeb(hdmi, 0x00, HDMI_I2CM_DIV);
/* Set done, not acknowledged and arbitration interrupt polarities */
hdmi_writeb(hdmi, HDMI_I2CM_INT_DONE_POL, HDMI_I2CM_INT);
hdmi_writeb(hdmi, HDMI_I2CM_CTLINT_NAC_POL | HDMI_I2CM_CTLINT_ARB_POL,
HDMI_I2CM_CTLINT);
/* Clear DONE and ERROR interrupts */
hdmi_writeb(hdmi, HDMI_IH_I2CM_STAT0_ERROR | HDMI_IH_I2CM_STAT0_DONE,
HDMI_IH_I2CM_STAT0);
/* Mute DONE and ERROR interrupts */
hdmi_writeb(hdmi, HDMI_IH_I2CM_STAT0_ERROR | HDMI_IH_I2CM_STAT0_DONE,
HDMI_IH_MUTE_I2CM_STAT0);
}
static int dw_hdmi_i2c_read(struct dw_hdmi *hdmi,
unsigned char *buf, unsigned int length)
{
struct dw_hdmi_i2c *i2c = hdmi->i2c;
int stat;
if (!i2c->is_regaddr) {
dev_dbg(hdmi->dev, "set read register address to 0\n");
i2c->slave_reg = 0x00;
i2c->is_regaddr = true;
}
while (length--) {
reinit_completion(&i2c->cmp);
hdmi_writeb(hdmi, i2c->slave_reg++, HDMI_I2CM_ADDRESS);
hdmi_writeb(hdmi, HDMI_I2CM_OPERATION_READ,
HDMI_I2CM_OPERATION);
stat = wait_for_completion_timeout(&i2c->cmp, HZ / 10);
if (!stat)
return -EAGAIN;
/* Check for error condition on the bus */
if (i2c->stat & HDMI_IH_I2CM_STAT0_ERROR)
return -EIO;
*buf++ = hdmi_readb(hdmi, HDMI_I2CM_DATAI);
}
return 0;
}
static int dw_hdmi_i2c_write(struct dw_hdmi *hdmi,
unsigned char *buf, unsigned int length)
{
struct dw_hdmi_i2c *i2c = hdmi->i2c;
int stat;
if (!i2c->is_regaddr) {
/* Use the first write byte as register address */
i2c->slave_reg = buf[0];
length--;
buf++;
i2c->is_regaddr = true;
}
while (length--) {
reinit_completion(&i2c->cmp);
hdmi_writeb(hdmi, *buf++, HDMI_I2CM_DATAO);
hdmi_writeb(hdmi, i2c->slave_reg++, HDMI_I2CM_ADDRESS);
hdmi_writeb(hdmi, HDMI_I2CM_OPERATION_WRITE,
HDMI_I2CM_OPERATION);
stat = wait_for_completion_timeout(&i2c->cmp, HZ / 10);
if (!stat)
return -EAGAIN;
/* Check for error condition on the bus */
if (i2c->stat & HDMI_IH_I2CM_STAT0_ERROR)
return -EIO;
}
return 0;
}
static int dw_hdmi_i2c_xfer(struct i2c_adapter *adap,
struct i2c_msg *msgs, int num)
{
struct dw_hdmi *hdmi = i2c_get_adapdata(adap);
struct dw_hdmi_i2c *i2c = hdmi->i2c;
u8 addr = msgs[0].addr;
int i, ret = 0;
dev_dbg(hdmi->dev, "xfer: num: %d, addr: %#x\n", num, addr);
for (i = 0; i < num; i++) {
if (msgs[i].addr != addr) {
dev_warn(hdmi->dev,
"unsupported transfer, changed slave address\n");
return -EOPNOTSUPP;
}
if (msgs[i].len == 0) {
dev_dbg(hdmi->dev,
"unsupported transfer %d/%d, no data\n",
i + 1, num);
return -EOPNOTSUPP;
}
}
mutex_lock(&i2c->lock);
/* Unmute DONE and ERROR interrupts */
hdmi_writeb(hdmi, 0x00, HDMI_IH_MUTE_I2CM_STAT0);
/* Set slave device address taken from the first I2C message */
hdmi_writeb(hdmi, addr, HDMI_I2CM_SLAVE);
/* Set slave device register address on transfer */
i2c->is_regaddr = false;
for (i = 0; i < num; i++) {
dev_dbg(hdmi->dev, "xfer: num: %d/%d, len: %d, flags: %#x\n",
i + 1, num, msgs[i].len, msgs[i].flags);
if (msgs[i].flags & I2C_M_RD)
ret = dw_hdmi_i2c_read(hdmi, msgs[i].buf, msgs[i].len);
else
ret = dw_hdmi_i2c_write(hdmi, msgs[i].buf, msgs[i].len);
if (ret < 0)
break;
}
if (!ret)
ret = num;
/* Mute DONE and ERROR interrupts */
hdmi_writeb(hdmi, HDMI_IH_I2CM_STAT0_ERROR | HDMI_IH_I2CM_STAT0_DONE,
HDMI_IH_MUTE_I2CM_STAT0);
mutex_unlock(&i2c->lock);
return ret;
}
static u32 dw_hdmi_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm dw_hdmi_algorithm = {
.master_xfer = dw_hdmi_i2c_xfer,
.functionality = dw_hdmi_i2c_func,
};
static struct i2c_adapter *dw_hdmi_i2c_adapter(struct dw_hdmi *hdmi)
{
struct i2c_adapter *adap;
struct dw_hdmi_i2c *i2c;
int ret;
i2c = devm_kzalloc(hdmi->dev, sizeof(*i2c), GFP_KERNEL);
if (!i2c)
return ERR_PTR(-ENOMEM);
mutex_init(&i2c->lock);
init_completion(&i2c->cmp);
adap = &i2c->adap;
adap->class = I2C_CLASS_DDC;
adap->owner = THIS_MODULE;
adap->dev.parent = hdmi->dev;
adap->algo = &dw_hdmi_algorithm;
strlcpy(adap->name, "DesignWare HDMI", sizeof(adap->name));
i2c_set_adapdata(adap, hdmi);
ret = i2c_add_adapter(adap);
if (ret) {
dev_warn(hdmi->dev, "cannot add %s I2C adapter\n", adap->name);
devm_kfree(hdmi->dev, i2c);
return ERR_PTR(ret);
}
hdmi->i2c = i2c;
dev_info(hdmi->dev, "registered %s I2C bus driver\n", adap->name);
return adap;
}
static void hdmi_set_cts_n(struct dw_hdmi *hdmi, unsigned int cts,
unsigned int n)
{
/* Must be set/cleared first */
hdmi_modb(hdmi, 0, HDMI_AUD_CTS3_CTS_MANUAL, HDMI_AUD_CTS3);
/* nshift factor = 0 */
hdmi_modb(hdmi, 0, HDMI_AUD_CTS3_N_SHIFT_MASK, HDMI_AUD_CTS3);
hdmi_writeb(hdmi, ((cts >> 16) & HDMI_AUD_CTS3_AUDCTS19_16_MASK) |
HDMI_AUD_CTS3_CTS_MANUAL, HDMI_AUD_CTS3);
hdmi_writeb(hdmi, (cts >> 8) & 0xff, HDMI_AUD_CTS2);
hdmi_writeb(hdmi, cts & 0xff, HDMI_AUD_CTS1);
hdmi_writeb(hdmi, (n >> 16) & 0x0f, HDMI_AUD_N3);
hdmi_writeb(hdmi, (n >> 8) & 0xff, HDMI_AUD_N2);
hdmi_writeb(hdmi, n & 0xff, HDMI_AUD_N1);
}
static unsigned int hdmi_compute_n(unsigned int freq, unsigned long pixel_clk)
{
unsigned int n = (128 * freq) / 1000;
unsigned int mult = 1;
while (freq > 48000) {
mult *= 2;
freq /= 2;
}
switch (freq) {
case 32000:
if (pixel_clk == 25175000)
n = 4576;
else if (pixel_clk == 27027000)
n = 4096;
else if (pixel_clk == 74176000 || pixel_clk == 148352000)
n = 11648;
else
n = 4096;
n *= mult;
break;
case 44100:
if (pixel_clk == 25175000)
n = 7007;
else if (pixel_clk == 74176000)
n = 17836;
else if (pixel_clk == 148352000)
n = 8918;
else
n = 6272;
n *= mult;
break;
case 48000:
if (pixel_clk == 25175000)
n = 6864;
else if (pixel_clk == 27027000)
n = 6144;
else if (pixel_clk == 74176000)
n = 11648;
else if (pixel_clk == 148352000)
n = 5824;
else
n = 6144;
n *= mult;
break;
default:
break;
}
return n;
}
static void hdmi_set_clk_regenerator(struct dw_hdmi *hdmi,
unsigned long pixel_clk, unsigned int sample_rate)
{
unsigned long ftdms = pixel_clk;
unsigned int n, cts;
u64 tmp;
n = hdmi_compute_n(sample_rate, pixel_clk);
/*
* Compute the CTS value from the N value. Note that CTS and N
* can be up to 20 bits in total, so we need 64-bit math. Also
* note that our TDMS clock is not fully accurate; it is accurate
* to kHz. This can introduce an unnecessary remainder in the
* calculation below, so we don't try to warn about that.
*/
tmp = (u64)ftdms * n;
do_div(tmp, 128 * sample_rate);
cts = tmp;
dev_dbg(hdmi->dev, "%s: fs=%uHz ftdms=%lu.%03luMHz N=%d cts=%d\n",
__func__, sample_rate, ftdms / 1000000, (ftdms / 1000) % 1000,
n, cts);
spin_lock_irq(&hdmi->audio_lock);
hdmi->audio_n = n;
hdmi->audio_cts = cts;
hdmi_set_cts_n(hdmi, cts, hdmi->audio_enable ? n : 0);
spin_unlock_irq(&hdmi->audio_lock);
}
static void hdmi_init_clk_regenerator(struct dw_hdmi *hdmi)
{
mutex_lock(&hdmi->audio_mutex);
hdmi_set_clk_regenerator(hdmi, 74250000, hdmi->sample_rate);
mutex_unlock(&hdmi->audio_mutex);
}
static void hdmi_clk_regenerator_update_pixel_clock(struct dw_hdmi *hdmi)
{
mutex_lock(&hdmi->audio_mutex);
hdmi_set_clk_regenerator(hdmi, hdmi->hdmi_data.video_mode.mpixelclock,
hdmi->sample_rate);
mutex_unlock(&hdmi->audio_mutex);
}
void dw_hdmi_set_sample_rate(struct dw_hdmi *hdmi, unsigned int rate)
{
mutex_lock(&hdmi->audio_mutex);
hdmi->sample_rate = rate;
hdmi_set_clk_regenerator(hdmi, hdmi->hdmi_data.video_mode.mpixelclock,
hdmi->sample_rate);
mutex_unlock(&hdmi->audio_mutex);
}
EXPORT_SYMBOL_GPL(dw_hdmi_set_sample_rate);
void dw_hdmi_audio_enable(struct dw_hdmi *hdmi)
{
unsigned long flags;
spin_lock_irqsave(&hdmi->audio_lock, flags);
hdmi->audio_enable = true;
hdmi_set_cts_n(hdmi, hdmi->audio_cts, hdmi->audio_n);
spin_unlock_irqrestore(&hdmi->audio_lock, flags);
}
EXPORT_SYMBOL_GPL(dw_hdmi_audio_enable);
void dw_hdmi_audio_disable(struct dw_hdmi *hdmi)
{
unsigned long flags;
spin_lock_irqsave(&hdmi->audio_lock, flags);
hdmi->audio_enable = false;
hdmi_set_cts_n(hdmi, hdmi->audio_cts, 0);
spin_unlock_irqrestore(&hdmi->audio_lock, flags);
}
EXPORT_SYMBOL_GPL(dw_hdmi_audio_disable);
/*
* this submodule is responsible for the video data synchronization.
* for example, for RGB 4:4:4 input, the data map is defined as
* pin{47~40} <==> R[7:0]
* pin{31~24} <==> G[7:0]
* pin{15~8} <==> B[7:0]
*/
static void hdmi_video_sample(struct dw_hdmi *hdmi)
{
int color_format = 0;
u8 val;
if (hdmi->hdmi_data.enc_in_format == RGB) {
if (hdmi->hdmi_data.enc_color_depth == 8)
color_format = 0x01;
else if (hdmi->hdmi_data.enc_color_depth == 10)
color_format = 0x03;
else if (hdmi->hdmi_data.enc_color_depth == 12)
color_format = 0x05;
else if (hdmi->hdmi_data.enc_color_depth == 16)
color_format = 0x07;
else
return;
} else if (hdmi->hdmi_data.enc_in_format == YCBCR444) {
if (hdmi->hdmi_data.enc_color_depth == 8)
color_format = 0x09;
else if (hdmi->hdmi_data.enc_color_depth == 10)
color_format = 0x0B;
else if (hdmi->hdmi_data.enc_color_depth == 12)
color_format = 0x0D;
else if (hdmi->hdmi_data.enc_color_depth == 16)
color_format = 0x0F;
else
return;
} else if (hdmi->hdmi_data.enc_in_format == YCBCR422_8BITS) {
if (hdmi->hdmi_data.enc_color_depth == 8)
color_format = 0x16;
else if (hdmi->hdmi_data.enc_color_depth == 10)
color_format = 0x14;
else if (hdmi->hdmi_data.enc_color_depth == 12)
color_format = 0x12;
else
return;
}
val = HDMI_TX_INVID0_INTERNAL_DE_GENERATOR_DISABLE |
((color_format << HDMI_TX_INVID0_VIDEO_MAPPING_OFFSET) &
HDMI_TX_INVID0_VIDEO_MAPPING_MASK);
hdmi_writeb(hdmi, val, HDMI_TX_INVID0);
/* Enable TX stuffing: When DE is inactive, fix the output data to 0 */
val = HDMI_TX_INSTUFFING_BDBDATA_STUFFING_ENABLE |
HDMI_TX_INSTUFFING_RCRDATA_STUFFING_ENABLE |
HDMI_TX_INSTUFFING_GYDATA_STUFFING_ENABLE;
hdmi_writeb(hdmi, val, HDMI_TX_INSTUFFING);
hdmi_writeb(hdmi, 0x0, HDMI_TX_GYDATA0);
hdmi_writeb(hdmi, 0x0, HDMI_TX_GYDATA1);
hdmi_writeb(hdmi, 0x0, HDMI_TX_RCRDATA0);
hdmi_writeb(hdmi, 0x0, HDMI_TX_RCRDATA1);
hdmi_writeb(hdmi, 0x0, HDMI_TX_BCBDATA0);
hdmi_writeb(hdmi, 0x0, HDMI_TX_BCBDATA1);
}
static int is_color_space_conversion(struct dw_hdmi *hdmi)
{
return hdmi->hdmi_data.enc_in_format != hdmi->hdmi_data.enc_out_format;
}
static int is_color_space_decimation(struct dw_hdmi *hdmi)
{
if (hdmi->hdmi_data.enc_out_format != YCBCR422_8BITS)
return 0;
if (hdmi->hdmi_data.enc_in_format == RGB ||
hdmi->hdmi_data.enc_in_format == YCBCR444)
return 1;
return 0;
}
static int is_color_space_interpolation(struct dw_hdmi *hdmi)
{
if (hdmi->hdmi_data.enc_in_format != YCBCR422_8BITS)
return 0;
if (hdmi->hdmi_data.enc_out_format == RGB ||
hdmi->hdmi_data.enc_out_format == YCBCR444)
return 1;
return 0;
}
static void dw_hdmi_update_csc_coeffs(struct dw_hdmi *hdmi)
{
const u16 (*csc_coeff)[3][4] = &csc_coeff_default;
unsigned i;
u32 csc_scale = 1;
if (is_color_space_conversion(hdmi)) {
if (hdmi->hdmi_data.enc_out_format == RGB) {
if (hdmi->hdmi_data.colorimetry ==
HDMI_COLORIMETRY_ITU_601)
csc_coeff = &csc_coeff_rgb_out_eitu601;
else
csc_coeff = &csc_coeff_rgb_out_eitu709;
} else if (hdmi->hdmi_data.enc_in_format == RGB) {
if (hdmi->hdmi_data.colorimetry ==
HDMI_COLORIMETRY_ITU_601)
csc_coeff = &csc_coeff_rgb_in_eitu601;
else
csc_coeff = &csc_coeff_rgb_in_eitu709;
csc_scale = 0;
}
}
/* The CSC registers are sequential, alternating MSB then LSB */
for (i = 0; i < ARRAY_SIZE(csc_coeff_default[0]); i++) {
u16 coeff_a = (*csc_coeff)[0][i];
u16 coeff_b = (*csc_coeff)[1][i];
u16 coeff_c = (*csc_coeff)[2][i];
hdmi_writeb(hdmi, coeff_a & 0xff, HDMI_CSC_COEF_A1_LSB + i * 2);
hdmi_writeb(hdmi, coeff_a >> 8, HDMI_CSC_COEF_A1_MSB + i * 2);
hdmi_writeb(hdmi, coeff_b & 0xff, HDMI_CSC_COEF_B1_LSB + i * 2);
hdmi_writeb(hdmi, coeff_b >> 8, HDMI_CSC_COEF_B1_MSB + i * 2);
hdmi_writeb(hdmi, coeff_c & 0xff, HDMI_CSC_COEF_C1_LSB + i * 2);
hdmi_writeb(hdmi, coeff_c >> 8, HDMI_CSC_COEF_C1_MSB + i * 2);
}
hdmi_modb(hdmi, csc_scale, HDMI_CSC_SCALE_CSCSCALE_MASK,
HDMI_CSC_SCALE);
}
static void hdmi_video_csc(struct dw_hdmi *hdmi)
{
int color_depth = 0;
int interpolation = HDMI_CSC_CFG_INTMODE_DISABLE;
int decimation = 0;
/* YCC422 interpolation to 444 mode */
if (is_color_space_interpolation(hdmi))
interpolation = HDMI_CSC_CFG_INTMODE_CHROMA_INT_FORMULA1;
else if (is_color_space_decimation(hdmi))
decimation = HDMI_CSC_CFG_DECMODE_CHROMA_INT_FORMULA3;
if (hdmi->hdmi_data.enc_color_depth == 8)
color_depth = HDMI_CSC_SCALE_CSC_COLORDE_PTH_24BPP;
else if (hdmi->hdmi_data.enc_color_depth == 10)
color_depth = HDMI_CSC_SCALE_CSC_COLORDE_PTH_30BPP;
else if (hdmi->hdmi_data.enc_color_depth == 12)
color_depth = HDMI_CSC_SCALE_CSC_COLORDE_PTH_36BPP;
else if (hdmi->hdmi_data.enc_color_depth == 16)
color_depth = HDMI_CSC_SCALE_CSC_COLORDE_PTH_48BPP;
else
return;
/* Configure the CSC registers */
hdmi_writeb(hdmi, interpolation | decimation, HDMI_CSC_CFG);
hdmi_modb(hdmi, color_depth, HDMI_CSC_SCALE_CSC_COLORDE_PTH_MASK,
HDMI_CSC_SCALE);
dw_hdmi_update_csc_coeffs(hdmi);
}
/*
* HDMI video packetizer is used to packetize the data.
* for example, if input is YCC422 mode or repeater is used,
* data should be repacked this module can be bypassed.
*/
static void hdmi_video_packetize(struct dw_hdmi *hdmi)
{
unsigned int color_depth = 0;
unsigned int remap_size = HDMI_VP_REMAP_YCC422_16bit;
unsigned int output_select = HDMI_VP_CONF_OUTPUT_SELECTOR_PP;
struct hdmi_data_info *hdmi_data = &hdmi->hdmi_data;
u8 val, vp_conf;
if (hdmi_data->enc_out_format == RGB ||
hdmi_data->enc_out_format == YCBCR444) {
if (!hdmi_data->enc_color_depth) {
output_select = HDMI_VP_CONF_OUTPUT_SELECTOR_BYPASS;
} else if (hdmi_data->enc_color_depth == 8) {
color_depth = 4;
output_select = HDMI_VP_CONF_OUTPUT_SELECTOR_BYPASS;
} else if (hdmi_data->enc_color_depth == 10) {
color_depth = 5;
} else if (hdmi_data->enc_color_depth == 12) {
color_depth = 6;
} else if (hdmi_data->enc_color_depth == 16) {
color_depth = 7;
} else {
return;
}
} else if (hdmi_data->enc_out_format == YCBCR422_8BITS) {
if (!hdmi_data->enc_color_depth ||
hdmi_data->enc_color_depth == 8)
remap_size = HDMI_VP_REMAP_YCC422_16bit;
else if (hdmi_data->enc_color_depth == 10)
remap_size = HDMI_VP_REMAP_YCC422_20bit;
else if (hdmi_data->enc_color_depth == 12)
remap_size = HDMI_VP_REMAP_YCC422_24bit;
else
return;
output_select = HDMI_VP_CONF_OUTPUT_SELECTOR_YCC422;
} else {
return;
}
/* set the packetizer registers */
val = ((color_depth << HDMI_VP_PR_CD_COLOR_DEPTH_OFFSET) &
HDMI_VP_PR_CD_COLOR_DEPTH_MASK) |
((hdmi_data->pix_repet_factor <<
HDMI_VP_PR_CD_DESIRED_PR_FACTOR_OFFSET) &
HDMI_VP_PR_CD_DESIRED_PR_FACTOR_MASK);
hdmi_writeb(hdmi, val, HDMI_VP_PR_CD);
hdmi_modb(hdmi, HDMI_VP_STUFF_PR_STUFFING_STUFFING_MODE,
HDMI_VP_STUFF_PR_STUFFING_MASK, HDMI_VP_STUFF);
/* Data from pixel repeater block */
if (hdmi_data->pix_repet_factor > 1) {
vp_conf = HDMI_VP_CONF_PR_EN_ENABLE |
HDMI_VP_CONF_BYPASS_SELECT_PIX_REPEATER;
} else { /* data from packetizer block */
vp_conf = HDMI_VP_CONF_PR_EN_DISABLE |
HDMI_VP_CONF_BYPASS_SELECT_VID_PACKETIZER;
}
hdmi_modb(hdmi, vp_conf,
HDMI_VP_CONF_PR_EN_MASK |
HDMI_VP_CONF_BYPASS_SELECT_MASK, HDMI_VP_CONF);
hdmi_modb(hdmi, 1 << HDMI_VP_STUFF_IDEFAULT_PHASE_OFFSET,
HDMI_VP_STUFF_IDEFAULT_PHASE_MASK, HDMI_VP_STUFF);
hdmi_writeb(hdmi, remap_size, HDMI_VP_REMAP);
if (output_select == HDMI_VP_CONF_OUTPUT_SELECTOR_PP) {
vp_conf = HDMI_VP_CONF_BYPASS_EN_DISABLE |
HDMI_VP_CONF_PP_EN_ENABLE |
HDMI_VP_CONF_YCC422_EN_DISABLE;
} else if (output_select == HDMI_VP_CONF_OUTPUT_SELECTOR_YCC422) {
vp_conf = HDMI_VP_CONF_BYPASS_EN_DISABLE |
HDMI_VP_CONF_PP_EN_DISABLE |
HDMI_VP_CONF_YCC422_EN_ENABLE;
} else if (output_select == HDMI_VP_CONF_OUTPUT_SELECTOR_BYPASS) {
vp_conf = HDMI_VP_CONF_BYPASS_EN_ENABLE |
HDMI_VP_CONF_PP_EN_DISABLE |
HDMI_VP_CONF_YCC422_EN_DISABLE;
} else {
return;
}
hdmi_modb(hdmi, vp_conf,
HDMI_VP_CONF_BYPASS_EN_MASK | HDMI_VP_CONF_PP_EN_ENMASK |
HDMI_VP_CONF_YCC422_EN_MASK, HDMI_VP_CONF);
hdmi_modb(hdmi, HDMI_VP_STUFF_PP_STUFFING_STUFFING_MODE |
HDMI_VP_STUFF_YCC422_STUFFING_STUFFING_MODE,
HDMI_VP_STUFF_PP_STUFFING_MASK |
HDMI_VP_STUFF_YCC422_STUFFING_MASK, HDMI_VP_STUFF);
hdmi_modb(hdmi, output_select, HDMI_VP_CONF_OUTPUT_SELECTOR_MASK,
HDMI_VP_CONF);
}
static inline void hdmi_phy_test_clear(struct dw_hdmi *hdmi,
unsigned char bit)
{
hdmi_modb(hdmi, bit << HDMI_PHY_TST0_TSTCLR_OFFSET,
HDMI_PHY_TST0_TSTCLR_MASK, HDMI_PHY_TST0);
}
static inline void hdmi_phy_test_enable(struct dw_hdmi *hdmi,
unsigned char bit)
{
hdmi_modb(hdmi, bit << HDMI_PHY_TST0_TSTEN_OFFSET,
HDMI_PHY_TST0_TSTEN_MASK, HDMI_PHY_TST0);
}
static inline void hdmi_phy_test_clock(struct dw_hdmi *hdmi,
unsigned char bit)
{
hdmi_modb(hdmi, bit << HDMI_PHY_TST0_TSTCLK_OFFSET,
HDMI_PHY_TST0_TSTCLK_MASK, HDMI_PHY_TST0);
}
static inline void hdmi_phy_test_din(struct dw_hdmi *hdmi,
unsigned char bit)
{
hdmi_writeb(hdmi, bit, HDMI_PHY_TST1);
}
static inline void hdmi_phy_test_dout(struct dw_hdmi *hdmi,
unsigned char bit)
{
hdmi_writeb(hdmi, bit, HDMI_PHY_TST2);
}
static bool hdmi_phy_wait_i2c_done(struct dw_hdmi *hdmi, int msec)
{
u32 val;
while ((val = hdmi_readb(hdmi, HDMI_IH_I2CMPHY_STAT0) & 0x3) == 0) {
if (msec-- == 0)
return false;
udelay(1000);
}
hdmi_writeb(hdmi, val, HDMI_IH_I2CMPHY_STAT0);
return true;
}
static void hdmi_phy_i2c_write(struct dw_hdmi *hdmi, unsigned short data,
unsigned char addr)
{
hdmi_writeb(hdmi, 0xFF, HDMI_IH_I2CMPHY_STAT0);
hdmi_writeb(hdmi, addr, HDMI_PHY_I2CM_ADDRESS_ADDR);
hdmi_writeb(hdmi, (unsigned char)(data >> 8),
HDMI_PHY_I2CM_DATAO_1_ADDR);
hdmi_writeb(hdmi, (unsigned char)(data >> 0),
HDMI_PHY_I2CM_DATAO_0_ADDR);
hdmi_writeb(hdmi, HDMI_PHY_I2CM_OPERATION_ADDR_WRITE,
HDMI_PHY_I2CM_OPERATION_ADDR);
hdmi_phy_wait_i2c_done(hdmi, 1000);
}
static void dw_hdmi_phy_enable_powerdown(struct dw_hdmi *hdmi, bool enable)
{
hdmi_mask_writeb(hdmi, !enable, HDMI_PHY_CONF0,
HDMI_PHY_CONF0_PDZ_OFFSET,
HDMI_PHY_CONF0_PDZ_MASK);
}
static void dw_hdmi_phy_enable_tmds(struct dw_hdmi *hdmi, u8 enable)
{
hdmi_mask_writeb(hdmi, enable, HDMI_PHY_CONF0,
HDMI_PHY_CONF0_ENTMDS_OFFSET,
HDMI_PHY_CONF0_ENTMDS_MASK);
}
static void dw_hdmi_phy_enable_svsret(struct dw_hdmi *hdmi, u8 enable)
{
hdmi_mask_writeb(hdmi, enable, HDMI_PHY_CONF0,
HDMI_PHY_CONF0_SVSRET_OFFSET,
HDMI_PHY_CONF0_SVSRET_MASK);
}
static void dw_hdmi_phy_gen2_pddq(struct dw_hdmi *hdmi, u8 enable)
{
hdmi_mask_writeb(hdmi, enable, HDMI_PHY_CONF0,
HDMI_PHY_CONF0_GEN2_PDDQ_OFFSET,
HDMI_PHY_CONF0_GEN2_PDDQ_MASK);
}
static void dw_hdmi_phy_gen2_txpwron(struct dw_hdmi *hdmi, u8 enable)
{
hdmi_mask_writeb(hdmi, enable, HDMI_PHY_CONF0,
HDMI_PHY_CONF0_GEN2_TXPWRON_OFFSET,
HDMI_PHY_CONF0_GEN2_TXPWRON_MASK);
}
static void dw_hdmi_phy_sel_data_en_pol(struct dw_hdmi *hdmi, u8 enable)
{
hdmi_mask_writeb(hdmi, enable, HDMI_PHY_CONF0,
HDMI_PHY_CONF0_SELDATAENPOL_OFFSET,
HDMI_PHY_CONF0_SELDATAENPOL_MASK);
}
static void dw_hdmi_phy_sel_interface_control(struct dw_hdmi *hdmi, u8 enable)
{
hdmi_mask_writeb(hdmi, enable, HDMI_PHY_CONF0,
HDMI_PHY_CONF0_SELDIPIF_OFFSET,
HDMI_PHY_CONF0_SELDIPIF_MASK);
}
static int hdmi_phy_configure(struct dw_hdmi *hdmi, int cscon)
{
u8 val, msec;
const struct dw_hdmi_plat_data *pdata = hdmi->plat_data;
const struct dw_hdmi_mpll_config *mpll_config = pdata->mpll_cfg;
const struct dw_hdmi_curr_ctrl *curr_ctrl = pdata->cur_ctr;
const struct dw_hdmi_phy_config *phy_config = pdata->phy_config;
/* PLL/MPLL Cfg - always match on final entry */
for (; mpll_config->mpixelclock != ~0UL; mpll_config++)
if (hdmi->hdmi_data.video_mode.mpixelclock <=
mpll_config->mpixelclock)
break;
for (; curr_ctrl->mpixelclock != ~0UL; curr_ctrl++)
if (hdmi->hdmi_data.video_mode.mpixelclock <=
curr_ctrl->mpixelclock)
break;
for (; phy_config->mpixelclock != ~0UL; phy_config++)
if (hdmi->hdmi_data.video_mode.mpixelclock <=
phy_config->mpixelclock)
break;
if (mpll_config->mpixelclock == ~0UL ||
curr_ctrl->mpixelclock == ~0UL ||
phy_config->mpixelclock == ~0UL) {
dev_err(hdmi->dev, "Pixel clock %d - unsupported by HDMI\n",
hdmi->hdmi_data.video_mode.mpixelclock);
return -EINVAL;
}
/* Enable csc path */
if (cscon)
val = HDMI_MC_FLOWCTRL_FEED_THROUGH_OFF_CSC_IN_PATH;
else
val = HDMI_MC_FLOWCTRL_FEED_THROUGH_OFF_CSC_BYPASS;
hdmi_writeb(hdmi, val, HDMI_MC_FLOWCTRL);
/* gen2 tx power off */
dw_hdmi_phy_gen2_txpwron(hdmi, 0);
/* gen2 pddq */
dw_hdmi_phy_gen2_pddq(hdmi, 1);
/* Leave low power consumption mode by asserting SVSRET. */
if (hdmi->phy->has_svsret)
dw_hdmi_phy_enable_svsret(hdmi, 1);
/* PHY reset. The reset signal is active high on Gen2 PHYs. */
hdmi_writeb(hdmi, HDMI_MC_PHYRSTZ_PHYRSTZ, HDMI_MC_PHYRSTZ);
hdmi_writeb(hdmi, 0, HDMI_MC_PHYRSTZ);
hdmi_writeb(hdmi, HDMI_MC_HEACPHY_RST_ASSERT, HDMI_MC_HEACPHY_RST);
hdmi_phy_test_clear(hdmi, 1);
hdmi_writeb(hdmi, HDMI_PHY_I2CM_SLAVE_ADDR_PHY_GEN2,
HDMI_PHY_I2CM_SLAVE_ADDR);
hdmi_phy_test_clear(hdmi, 0);
hdmi_phy_i2c_write(hdmi, mpll_config->res[0].cpce,
HDMI_3D_TX_PHY_CPCE_CTRL);
hdmi_phy_i2c_write(hdmi, mpll_config->res[0].gmp,
HDMI_3D_TX_PHY_GMPCTRL);
hdmi_phy_i2c_write(hdmi, curr_ctrl->curr[0],
HDMI_3D_TX_PHY_CURRCTRL);
hdmi_phy_i2c_write(hdmi, 0, HDMI_3D_TX_PHY_PLLPHBYCTRL);
hdmi_phy_i2c_write(hdmi, HDMI_3D_TX_PHY_MSM_CTRL_CKO_SEL_FB_CLK,
HDMI_3D_TX_PHY_MSM_CTRL);
hdmi_phy_i2c_write(hdmi, phy_config->term, HDMI_3D_TX_PHY_TXTERM);
hdmi_phy_i2c_write(hdmi, phy_config->sym_ctr,
HDMI_3D_TX_PHY_CKSYMTXCTRL);
hdmi_phy_i2c_write(hdmi, phy_config->vlev_ctr,
HDMI_3D_TX_PHY_VLEVCTRL);
/* Override and disable clock termination. */
hdmi_phy_i2c_write(hdmi, HDMI_3D_TX_PHY_CKCALCTRL_OVERRIDE,
HDMI_3D_TX_PHY_CKCALCTRL);
dw_hdmi_phy_enable_powerdown(hdmi, false);
/* toggle TMDS enable */
dw_hdmi_phy_enable_tmds(hdmi, 0);
dw_hdmi_phy_enable_tmds(hdmi, 1);
/* gen2 tx power on */
dw_hdmi_phy_gen2_txpwron(hdmi, 1);
dw_hdmi_phy_gen2_pddq(hdmi, 0);
/* Wait for PHY PLL lock */
msec = 5;
do {
val = hdmi_readb(hdmi, HDMI_PHY_STAT0) & HDMI_PHY_TX_PHY_LOCK;
if (!val)
break;
if (msec == 0) {
dev_err(hdmi->dev, "PHY PLL not locked\n");
return -ETIMEDOUT;
}
udelay(1000);
msec--;
} while (1);
return 0;
}
static int dw_hdmi_phy_init(struct dw_hdmi *hdmi)
{
int i, ret;
bool cscon;
/*check csc whether needed activated in HDMI mode */
cscon = hdmi->sink_is_hdmi && is_color_space_conversion(hdmi);
/* HDMI Phy spec says to do the phy initialization sequence twice */
for (i = 0; i < 2; i++) {
dw_hdmi_phy_sel_data_en_pol(hdmi, 1);
dw_hdmi_phy_sel_interface_control(hdmi, 0);
dw_hdmi_phy_enable_tmds(hdmi, 0);
dw_hdmi_phy_enable_powerdown(hdmi, true);
/* Enable CSC */
ret = hdmi_phy_configure(hdmi, cscon);
if (ret)
return ret;
}
hdmi->phy_enabled = true;
return 0;
}
static void hdmi_tx_hdcp_config(struct dw_hdmi *hdmi)
{
u8 de;
if (hdmi->hdmi_data.video_mode.mdataenablepolarity)
de = HDMI_A_VIDPOLCFG_DATAENPOL_ACTIVE_HIGH;
else
de = HDMI_A_VIDPOLCFG_DATAENPOL_ACTIVE_LOW;
/* disable rx detect */
hdmi_modb(hdmi, HDMI_A_HDCPCFG0_RXDETECT_DISABLE,
HDMI_A_HDCPCFG0_RXDETECT_MASK, HDMI_A_HDCPCFG0);
hdmi_modb(hdmi, de, HDMI_A_VIDPOLCFG_DATAENPOL_MASK, HDMI_A_VIDPOLCFG);
hdmi_modb(hdmi, HDMI_A_HDCPCFG1_ENCRYPTIONDISABLE_DISABLE,
HDMI_A_HDCPCFG1_ENCRYPTIONDISABLE_MASK, HDMI_A_HDCPCFG1);
}
static void hdmi_config_AVI(struct dw_hdmi *hdmi, struct drm_display_mode *mode)
{
struct hdmi_avi_infoframe frame;
u8 val;
/* Initialise info frame from DRM mode */
drm_hdmi_avi_infoframe_from_display_mode(&frame, mode);
if (hdmi->hdmi_data.enc_out_format == YCBCR444)
frame.colorspace = HDMI_COLORSPACE_YUV444;
else if (hdmi->hdmi_data.enc_out_format == YCBCR422_8BITS)
frame.colorspace = HDMI_COLORSPACE_YUV422;
else
frame.colorspace = HDMI_COLORSPACE_RGB;
/* Set up colorimetry */
if (hdmi->hdmi_data.enc_out_format == XVYCC444) {
frame.colorimetry = HDMI_COLORIMETRY_EXTENDED;
if (hdmi->hdmi_data.colorimetry == HDMI_COLORIMETRY_ITU_601)
frame.extended_colorimetry =
HDMI_EXTENDED_COLORIMETRY_XV_YCC_601;
else /*hdmi->hdmi_data.colorimetry == HDMI_COLORIMETRY_ITU_709*/
frame.extended_colorimetry =
HDMI_EXTENDED_COLORIMETRY_XV_YCC_709;
} else if (hdmi->hdmi_data.enc_out_format != RGB) {
frame.colorimetry = hdmi->hdmi_data.colorimetry;
frame.extended_colorimetry = HDMI_EXTENDED_COLORIMETRY_XV_YCC_601;
} else { /* Carries no data */
frame.colorimetry = HDMI_COLORIMETRY_NONE;
frame.extended_colorimetry = HDMI_EXTENDED_COLORIMETRY_XV_YCC_601;
}
frame.scan_mode = HDMI_SCAN_MODE_NONE;
/*
* The Designware IP uses a different byte format from standard
* AVI info frames, though generally the bits are in the correct
* bytes.
*/
/*
* AVI data byte 1 differences: Colorspace in bits 0,1 rather than 5,6,
* scan info in bits 4,5 rather than 0,1 and active aspect present in
* bit 6 rather than 4.
*/
val = (frame.scan_mode & 3) << 4 | (frame.colorspace & 3);
if (frame.active_aspect & 15)
val |= HDMI_FC_AVICONF0_ACTIVE_FMT_INFO_PRESENT;
if (frame.top_bar || frame.bottom_bar)
val |= HDMI_FC_AVICONF0_BAR_DATA_HORIZ_BAR;
if (frame.left_bar || frame.right_bar)
val |= HDMI_FC_AVICONF0_BAR_DATA_VERT_BAR;
hdmi_writeb(hdmi, val, HDMI_FC_AVICONF0);
/* AVI data byte 2 differences: none */
val = ((frame.colorimetry & 0x3) << 6) |
((frame.picture_aspect & 0x3) << 4) |
(frame.active_aspect & 0xf);
hdmi_writeb(hdmi, val, HDMI_FC_AVICONF1);
/* AVI data byte 3 differences: none */
val = ((frame.extended_colorimetry & 0x7) << 4) |
((frame.quantization_range & 0x3) << 2) |
(frame.nups & 0x3);
if (frame.itc)
val |= HDMI_FC_AVICONF2_IT_CONTENT_VALID;
hdmi_writeb(hdmi, val, HDMI_FC_AVICONF2);
/* AVI data byte 4 differences: none */
val = frame.video_code & 0x7f;
hdmi_writeb(hdmi, val, HDMI_FC_AVIVID);
/* AVI Data Byte 5- set up input and output pixel repetition */
val = (((hdmi->hdmi_data.video_mode.mpixelrepetitioninput + 1) <<
HDMI_FC_PRCONF_INCOMING_PR_FACTOR_OFFSET) &
HDMI_FC_PRCONF_INCOMING_PR_FACTOR_MASK) |
((hdmi->hdmi_data.video_mode.mpixelrepetitionoutput <<
HDMI_FC_PRCONF_OUTPUT_PR_FACTOR_OFFSET) &
HDMI_FC_PRCONF_OUTPUT_PR_FACTOR_MASK);
hdmi_writeb(hdmi, val, HDMI_FC_PRCONF);
/*
* AVI data byte 5 differences: content type in 0,1 rather than 4,5,
* ycc range in bits 2,3 rather than 6,7
*/
val = ((frame.ycc_quantization_range & 0x3) << 2) |
(frame.content_type & 0x3);
hdmi_writeb(hdmi, val, HDMI_FC_AVICONF3);
/* AVI Data Bytes 6-13 */
hdmi_writeb(hdmi, frame.top_bar & 0xff, HDMI_FC_AVIETB0);
hdmi_writeb(hdmi, (frame.top_bar >> 8) & 0xff, HDMI_FC_AVIETB1);
hdmi_writeb(hdmi, frame.bottom_bar & 0xff, HDMI_FC_AVISBB0);
hdmi_writeb(hdmi, (frame.bottom_bar >> 8) & 0xff, HDMI_FC_AVISBB1);
hdmi_writeb(hdmi, frame.left_bar & 0xff, HDMI_FC_AVIELB0);
hdmi_writeb(hdmi, (frame.left_bar >> 8) & 0xff, HDMI_FC_AVIELB1);
hdmi_writeb(hdmi, frame.right_bar & 0xff, HDMI_FC_AVISRB0);
hdmi_writeb(hdmi, (frame.right_bar >> 8) & 0xff, HDMI_FC_AVISRB1);
}
static void hdmi_av_composer(struct dw_hdmi *hdmi,
const struct drm_display_mode *mode)
{
u8 inv_val;
struct hdmi_vmode *vmode = &hdmi->hdmi_data.video_mode;
int hblank, vblank, h_de_hs, v_de_vs, hsync_len, vsync_len;
unsigned int vdisplay;
vmode->mpixelclock = mode->clock * 1000;
dev_dbg(hdmi->dev, "final pixclk = %d\n", vmode->mpixelclock);
/* Set up HDMI_FC_INVIDCONF */
inv_val = (hdmi->hdmi_data.hdcp_enable ?
HDMI_FC_INVIDCONF_HDCP_KEEPOUT_ACTIVE :
HDMI_FC_INVIDCONF_HDCP_KEEPOUT_INACTIVE);
inv_val |= mode->flags & DRM_MODE_FLAG_PVSYNC ?
HDMI_FC_INVIDCONF_VSYNC_IN_POLARITY_ACTIVE_HIGH :
HDMI_FC_INVIDCONF_VSYNC_IN_POLARITY_ACTIVE_LOW;
inv_val |= mode->flags & DRM_MODE_FLAG_PHSYNC ?
HDMI_FC_INVIDCONF_HSYNC_IN_POLARITY_ACTIVE_HIGH :
HDMI_FC_INVIDCONF_HSYNC_IN_POLARITY_ACTIVE_LOW;
inv_val |= (vmode->mdataenablepolarity ?
HDMI_FC_INVIDCONF_DE_IN_POLARITY_ACTIVE_HIGH :
HDMI_FC_INVIDCONF_DE_IN_POLARITY_ACTIVE_LOW);
if (hdmi->vic == 39)
inv_val |= HDMI_FC_INVIDCONF_R_V_BLANK_IN_OSC_ACTIVE_HIGH;
else
inv_val |= mode->flags & DRM_MODE_FLAG_INTERLACE ?
HDMI_FC_INVIDCONF_R_V_BLANK_IN_OSC_ACTIVE_HIGH :
HDMI_FC_INVIDCONF_R_V_BLANK_IN_OSC_ACTIVE_LOW;
inv_val |= mode->flags & DRM_MODE_FLAG_INTERLACE ?
HDMI_FC_INVIDCONF_IN_I_P_INTERLACED :
HDMI_FC_INVIDCONF_IN_I_P_PROGRESSIVE;
inv_val |= hdmi->sink_is_hdmi ?
HDMI_FC_INVIDCONF_DVI_MODEZ_HDMI_MODE :
HDMI_FC_INVIDCONF_DVI_MODEZ_DVI_MODE;
hdmi_writeb(hdmi, inv_val, HDMI_FC_INVIDCONF);
vdisplay = mode->vdisplay;
vblank = mode->vtotal - mode->vdisplay;
v_de_vs = mode->vsync_start - mode->vdisplay;
vsync_len = mode->vsync_end - mode->vsync_start;
/*
* When we're setting an interlaced mode, we need
* to adjust the vertical timing to suit.
*/
if (mode->flags & DRM_MODE_FLAG_INTERLACE) {
vdisplay /= 2;
vblank /= 2;
v_de_vs /= 2;
vsync_len /= 2;
}
/* Set up horizontal active pixel width */
hdmi_writeb(hdmi, mode->hdisplay >> 8, HDMI_FC_INHACTV1);
hdmi_writeb(hdmi, mode->hdisplay, HDMI_FC_INHACTV0);
/* Set up vertical active lines */
hdmi_writeb(hdmi, vdisplay >> 8, HDMI_FC_INVACTV1);
hdmi_writeb(hdmi, vdisplay, HDMI_FC_INVACTV0);
/* Set up horizontal blanking pixel region width */
hblank = mode->htotal - mode->hdisplay;
hdmi_writeb(hdmi, hblank >> 8, HDMI_FC_INHBLANK1);
hdmi_writeb(hdmi, hblank, HDMI_FC_INHBLANK0);
/* Set up vertical blanking pixel region width */
hdmi_writeb(hdmi, vblank, HDMI_FC_INVBLANK);
/* Set up HSYNC active edge delay width (in pixel clks) */
h_de_hs = mode->hsync_start - mode->hdisplay;
hdmi_writeb(hdmi, h_de_hs >> 8, HDMI_FC_HSYNCINDELAY1);
hdmi_writeb(hdmi, h_de_hs, HDMI_FC_HSYNCINDELAY0);
/* Set up VSYNC active edge delay (in lines) */
hdmi_writeb(hdmi, v_de_vs, HDMI_FC_VSYNCINDELAY);
/* Set up HSYNC active pulse width (in pixel clks) */
hsync_len = mode->hsync_end - mode->hsync_start;
hdmi_writeb(hdmi, hsync_len >> 8, HDMI_FC_HSYNCINWIDTH1);
hdmi_writeb(hdmi, hsync_len, HDMI_FC_HSYNCINWIDTH0);
/* Set up VSYNC active edge delay (in lines) */
hdmi_writeb(hdmi, vsync_len, HDMI_FC_VSYNCINWIDTH);
}
static void dw_hdmi_phy_disable(struct dw_hdmi *hdmi)
{
if (!hdmi->phy_enabled)
return;
dw_hdmi_phy_enable_tmds(hdmi, 0);
dw_hdmi_phy_enable_powerdown(hdmi, true);
hdmi->phy_enabled = false;
}
/* HDMI Initialization Step B.4 */
static void dw_hdmi_enable_video_path(struct dw_hdmi *hdmi)
{
u8 clkdis;
/* control period minimum duration */
hdmi_writeb(hdmi, 12, HDMI_FC_CTRLDUR);
hdmi_writeb(hdmi, 32, HDMI_FC_EXCTRLDUR);
hdmi_writeb(hdmi, 1, HDMI_FC_EXCTRLSPAC);
/* Set to fill TMDS data channels */
hdmi_writeb(hdmi, 0x0B, HDMI_FC_CH0PREAM);
hdmi_writeb(hdmi, 0x16, HDMI_FC_CH1PREAM);
hdmi_writeb(hdmi, 0x21, HDMI_FC_CH2PREAM);
/* Enable pixel clock and tmds data path */
clkdis = 0x7F;
clkdis &= ~HDMI_MC_CLKDIS_PIXELCLK_DISABLE;
hdmi_writeb(hdmi, clkdis, HDMI_MC_CLKDIS);
clkdis &= ~HDMI_MC_CLKDIS_TMDSCLK_DISABLE;
hdmi_writeb(hdmi, clkdis, HDMI_MC_CLKDIS);
/* Enable csc path */
if (is_color_space_conversion(hdmi)) {
clkdis &= ~HDMI_MC_CLKDIS_CSCCLK_DISABLE;
hdmi_writeb(hdmi, clkdis, HDMI_MC_CLKDIS);
}
}
static void hdmi_enable_audio_clk(struct dw_hdmi *hdmi)
{
hdmi_modb(hdmi, 0, HDMI_MC_CLKDIS_AUDCLK_DISABLE, HDMI_MC_CLKDIS);
}
/* Workaround to clear the overflow condition */
static void dw_hdmi_clear_overflow(struct dw_hdmi *hdmi)
{
unsigned int count;
unsigned int i;
u8 val;
/*
* Under some circumstances the Frame Composer arithmetic unit can miss
* an FC register write due to being busy processing the previous one.
* The issue can be worked around by issuing a TMDS software reset and
* then write one of the FC registers several times.
*
* The number of iterations matters and depends on the HDMI TX revision
* (and possibly on the platform). So far only i.MX6Q (v1.30a) and
* i.MX6DL (v1.31a) have been identified as needing the workaround, with
* 4 and 1 iterations respectively.
*/
switch (hdmi->version) {
case 0x130a:
count = 4;
break;
case 0x131a:
count = 1;
break;
default:
return;
}
/* TMDS software reset */
hdmi_writeb(hdmi, (u8)~HDMI_MC_SWRSTZ_TMDSSWRST_REQ, HDMI_MC_SWRSTZ);
val = hdmi_readb(hdmi, HDMI_FC_INVIDCONF);
for (i = 0; i < count; i++)
hdmi_writeb(hdmi, val, HDMI_FC_INVIDCONF);
}
static void hdmi_enable_overflow_interrupts(struct dw_hdmi *hdmi)
{
hdmi_writeb(hdmi, 0, HDMI_FC_MASK2);
hdmi_writeb(hdmi, 0, HDMI_IH_MUTE_FC_STAT2);
}
static void hdmi_disable_overflow_interrupts(struct dw_hdmi *hdmi)
{
hdmi_writeb(hdmi, HDMI_IH_MUTE_FC_STAT2_OVERFLOW_MASK,
HDMI_IH_MUTE_FC_STAT2);
}
static int dw_hdmi_setup(struct dw_hdmi *hdmi, struct drm_display_mode *mode)
{
int ret;
hdmi_disable_overflow_interrupts(hdmi);
hdmi->vic = drm_match_cea_mode(mode);
if (!hdmi->vic) {
dev_dbg(hdmi->dev, "Non-CEA mode used in HDMI\n");
} else {
dev_dbg(hdmi->dev, "CEA mode used vic=%d\n", hdmi->vic);
}
if ((hdmi->vic == 6) || (hdmi->vic == 7) ||
(hdmi->vic == 21) || (hdmi->vic == 22) ||
(hdmi->vic == 2) || (hdmi->vic == 3) ||
(hdmi->vic == 17) || (hdmi->vic == 18))
hdmi->hdmi_data.colorimetry = HDMI_COLORIMETRY_ITU_601;
else
hdmi->hdmi_data.colorimetry = HDMI_COLORIMETRY_ITU_709;
hdmi->hdmi_data.video_mode.mpixelrepetitionoutput = 0;
hdmi->hdmi_data.video_mode.mpixelrepetitioninput = 0;
/* TODO: Get input format from IPU (via FB driver interface) */
hdmi->hdmi_data.enc_in_format = RGB;
hdmi->hdmi_data.enc_out_format = RGB;
hdmi->hdmi_data.enc_color_depth = 8;
hdmi->hdmi_data.pix_repet_factor = 0;
hdmi->hdmi_data.hdcp_enable = 0;
hdmi->hdmi_data.video_mode.mdataenablepolarity = true;
/* HDMI Initialization Step B.1 */
hdmi_av_composer(hdmi, mode);
/* HDMI Initializateion Step B.2 */
ret = dw_hdmi_phy_init(hdmi);
if (ret)
return ret;
/* HDMI Initialization Step B.3 */
dw_hdmi_enable_video_path(hdmi);
if (hdmi->sink_has_audio) {
dev_dbg(hdmi->dev, "sink has audio support\n");
/* HDMI Initialization Step E - Configure audio */
hdmi_clk_regenerator_update_pixel_clock(hdmi);
hdmi_enable_audio_clk(hdmi);
}
/* not for DVI mode */
if (hdmi->sink_is_hdmi) {
dev_dbg(hdmi->dev, "%s HDMI mode\n", __func__);
/* HDMI Initialization Step F - Configure AVI InfoFrame */
hdmi_config_AVI(hdmi, mode);
} else {
dev_dbg(hdmi->dev, "%s DVI mode\n", __func__);
}
hdmi_video_packetize(hdmi);
hdmi_video_csc(hdmi);
hdmi_video_sample(hdmi);
hdmi_tx_hdcp_config(hdmi);
dw_hdmi_clear_overflow(hdmi);
if (hdmi->cable_plugin && hdmi->sink_is_hdmi)
hdmi_enable_overflow_interrupts(hdmi);
return 0;
}
/* Wait until we are registered to enable interrupts */
static int dw_hdmi_fb_registered(struct dw_hdmi *hdmi)
{
hdmi_writeb(hdmi, HDMI_PHY_I2CM_INT_ADDR_DONE_POL,
HDMI_PHY_I2CM_INT_ADDR);
hdmi_writeb(hdmi, HDMI_PHY_I2CM_CTLINT_ADDR_NAC_POL |
HDMI_PHY_I2CM_CTLINT_ADDR_ARBITRATION_POL,
HDMI_PHY_I2CM_CTLINT_ADDR);
/* enable cable hot plug irq */
hdmi_writeb(hdmi, hdmi->phy_mask, HDMI_PHY_MASK0);
/* Clear Hotplug interrupts */
hdmi_writeb(hdmi, HDMI_IH_PHY_STAT0_HPD | HDMI_IH_PHY_STAT0_RX_SENSE,
HDMI_IH_PHY_STAT0);
return 0;
}
static void initialize_hdmi_ih_mutes(struct dw_hdmi *hdmi)
{
u8 ih_mute;
/*
* Boot up defaults are:
* HDMI_IH_MUTE = 0x03 (disabled)
* HDMI_IH_MUTE_* = 0x00 (enabled)
*
* Disable top level interrupt bits in HDMI block
*/
ih_mute = hdmi_readb(hdmi, HDMI_IH_MUTE) |
HDMI_IH_MUTE_MUTE_WAKEUP_INTERRUPT |
HDMI_IH_MUTE_MUTE_ALL_INTERRUPT;
hdmi_writeb(hdmi, ih_mute, HDMI_IH_MUTE);
/* by default mask all interrupts */
hdmi_writeb(hdmi, 0xff, HDMI_VP_MASK);
hdmi_writeb(hdmi, 0xff, HDMI_FC_MASK0);
hdmi_writeb(hdmi, 0xff, HDMI_FC_MASK1);
hdmi_writeb(hdmi, 0xff, HDMI_FC_MASK2);
hdmi_writeb(hdmi, 0xff, HDMI_PHY_MASK0);
hdmi_writeb(hdmi, 0xff, HDMI_PHY_I2CM_INT_ADDR);
hdmi_writeb(hdmi, 0xff, HDMI_PHY_I2CM_CTLINT_ADDR);
hdmi_writeb(hdmi, 0xff, HDMI_AUD_INT);
hdmi_writeb(hdmi, 0xff, HDMI_AUD_SPDIFINT);
hdmi_writeb(hdmi, 0xff, HDMI_AUD_HBR_MASK);
hdmi_writeb(hdmi, 0xff, HDMI_GP_MASK);
hdmi_writeb(hdmi, 0xff, HDMI_A_APIINTMSK);
hdmi_writeb(hdmi, 0xff, HDMI_CEC_MASK);
hdmi_writeb(hdmi, 0xff, HDMI_I2CM_INT);
hdmi_writeb(hdmi, 0xff, HDMI_I2CM_CTLINT);
/* Disable interrupts in the IH_MUTE_* registers */
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_FC_STAT0);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_FC_STAT1);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_FC_STAT2);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_AS_STAT0);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_PHY_STAT0);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_I2CM_STAT0);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_CEC_STAT0);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_VP_STAT0);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_I2CMPHY_STAT0);
hdmi_writeb(hdmi, 0xff, HDMI_IH_MUTE_AHBDMAAUD_STAT0);
/* Enable top level interrupt bits in HDMI block */
ih_mute &= ~(HDMI_IH_MUTE_MUTE_WAKEUP_INTERRUPT |
HDMI_IH_MUTE_MUTE_ALL_INTERRUPT);
hdmi_writeb(hdmi, ih_mute, HDMI_IH_MUTE);
}
static void dw_hdmi_poweron(struct dw_hdmi *hdmi)
{
hdmi->bridge_is_on = true;
dw_hdmi_setup(hdmi, &hdmi->previous_mode);
}
static void dw_hdmi_poweroff(struct dw_hdmi *hdmi)
{
dw_hdmi_phy_disable(hdmi);
hdmi->bridge_is_on = false;
}
static void dw_hdmi_update_power(struct dw_hdmi *hdmi)
{
int force = hdmi->force;
if (hdmi->disabled) {
force = DRM_FORCE_OFF;
} else if (force == DRM_FORCE_UNSPECIFIED) {
if (hdmi->rxsense)
force = DRM_FORCE_ON;
else
force = DRM_FORCE_OFF;
}
if (force == DRM_FORCE_OFF) {
if (hdmi->bridge_is_on)
dw_hdmi_poweroff(hdmi);
} else {
if (!hdmi->bridge_is_on)
dw_hdmi_poweron(hdmi);
}
}
/*
* Adjust the detection of RXSENSE according to whether we have a forced
* connection mode enabled, or whether we have been disabled. There is
* no point processing RXSENSE interrupts if we have a forced connection
* state, or DRM has us disabled.
*
* We also disable rxsense interrupts when we think we're disconnected
* to avoid floating TDMS signals giving false rxsense interrupts.
*
* Note: we still need to listen for HPD interrupts even when DRM has us
* disabled so that we can detect a connect event.
*/
static void dw_hdmi_update_phy_mask(struct dw_hdmi *hdmi)
{
u8 old_mask = hdmi->phy_mask;
if (hdmi->force || hdmi->disabled || !hdmi->rxsense)
hdmi->phy_mask |= HDMI_PHY_RX_SENSE;
else
hdmi->phy_mask &= ~HDMI_PHY_RX_SENSE;
if (old_mask != hdmi->phy_mask)
hdmi_writeb(hdmi, hdmi->phy_mask, HDMI_PHY_MASK0);
}
static enum drm_connector_status
dw_hdmi_connector_detect(struct drm_connector *connector, bool force)
{
struct dw_hdmi *hdmi = container_of(connector, struct dw_hdmi,
connector);
mutex_lock(&hdmi->mutex);
hdmi->force = DRM_FORCE_UNSPECIFIED;
dw_hdmi_update_power(hdmi);
dw_hdmi_update_phy_mask(hdmi);
mutex_unlock(&hdmi->mutex);
return hdmi_readb(hdmi, HDMI_PHY_STAT0) & HDMI_PHY_HPD ?
connector_status_connected : connector_status_disconnected;
}
static int dw_hdmi_connector_get_modes(struct drm_connector *connector)
{
struct dw_hdmi *hdmi = container_of(connector, struct dw_hdmi,
connector);
struct edid *edid;
int ret = 0;
if (!hdmi->ddc)
return 0;
edid = drm_get_edid(connector, hdmi->ddc);
if (edid) {
dev_dbg(hdmi->dev, "got edid: width[%d] x height[%d]\n",
edid->width_cm, edid->height_cm);
hdmi->sink_is_hdmi = drm_detect_hdmi_monitor(edid);
hdmi->sink_has_audio = drm_detect_monitor_audio(edid);
drm_mode_connector_update_edid_property(connector, edid);
ret = drm_add_edid_modes(connector, edid);
/* Store the ELD */
drm_edid_to_eld(connector, edid);
kfree(edid);
} else {
dev_dbg(hdmi->dev, "failed to get edid\n");
}
return ret;
}
static enum drm_mode_status
dw_hdmi_connector_mode_valid(struct drm_connector *connector,
struct drm_display_mode *mode)
{
struct dw_hdmi *hdmi = container_of(connector,
struct dw_hdmi, connector);
enum drm_mode_status mode_status = MODE_OK;
/* We don't support double-clocked modes */
if (mode->flags & DRM_MODE_FLAG_DBLCLK)
return MODE_BAD;
if (hdmi->plat_data->mode_valid)
mode_status = hdmi->plat_data->mode_valid(connector, mode);
return mode_status;
}
static void dw_hdmi_connector_force(struct drm_connector *connector)
{
struct dw_hdmi *hdmi = container_of(connector, struct dw_hdmi,
connector);
mutex_lock(&hdmi->mutex);
hdmi->force = connector->force;
dw_hdmi_update_power(hdmi);
dw_hdmi_update_phy_mask(hdmi);
mutex_unlock(&hdmi->mutex);
}
static const struct drm_connector_funcs dw_hdmi_connector_funcs = {
.dpms = drm_atomic_helper_connector_dpms,
.fill_modes = drm_helper_probe_single_connector_modes,
.detect = dw_hdmi_connector_detect,
.destroy = drm_connector_cleanup,
.force = dw_hdmi_connector_force,
.reset = drm_atomic_helper_connector_reset,
.atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state,
.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
};
static const struct drm_connector_helper_funcs dw_hdmi_connector_helper_funcs = {
.get_modes = dw_hdmi_connector_get_modes,
.mode_valid = dw_hdmi_connector_mode_valid,
.best_encoder = drm_atomic_helper_best_encoder,
};
static int dw_hdmi_bridge_attach(struct drm_bridge *bridge)
{
struct dw_hdmi *hdmi = bridge->driver_private;
struct drm_encoder *encoder = bridge->encoder;
struct drm_connector *connector = &hdmi->connector;
connector->interlace_allowed = 1;
connector->polled = DRM_CONNECTOR_POLL_HPD;
drm_connector_helper_add(connector, &dw_hdmi_connector_helper_funcs);
drm_connector_init(bridge->dev, connector, &dw_hdmi_connector_funcs,
DRM_MODE_CONNECTOR_HDMIA);
drm_mode_connector_attach_encoder(connector, encoder);
return 0;
}
static void dw_hdmi_bridge_mode_set(struct drm_bridge *bridge,
struct drm_display_mode *orig_mode,
struct drm_display_mode *mode)
{
struct dw_hdmi *hdmi = bridge->driver_private;
mutex_lock(&hdmi->mutex);
/* Store the display mode for plugin/DKMS poweron events */
memcpy(&hdmi->previous_mode, mode, sizeof(hdmi->previous_mode));
mutex_unlock(&hdmi->mutex);
}
static void dw_hdmi_bridge_disable(struct drm_bridge *bridge)
{
struct dw_hdmi *hdmi = bridge->driver_private;
mutex_lock(&hdmi->mutex);
hdmi->disabled = true;
dw_hdmi_update_power(hdmi);
dw_hdmi_update_phy_mask(hdmi);
mutex_unlock(&hdmi->mutex);
}
static void dw_hdmi_bridge_enable(struct drm_bridge *bridge)
{
struct dw_hdmi *hdmi = bridge->driver_private;
mutex_lock(&hdmi->mutex);
hdmi->disabled = false;
dw_hdmi_update_power(hdmi);
dw_hdmi_update_phy_mask(hdmi);
mutex_unlock(&hdmi->mutex);
}
static const struct drm_bridge_funcs dw_hdmi_bridge_funcs = {
.attach = dw_hdmi_bridge_attach,
.enable = dw_hdmi_bridge_enable,
.disable = dw_hdmi_bridge_disable,
.mode_set = dw_hdmi_bridge_mode_set,
};
static irqreturn_t dw_hdmi_i2c_irq(struct dw_hdmi *hdmi)
{
struct dw_hdmi_i2c *i2c = hdmi->i2c;
unsigned int stat;
stat = hdmi_readb(hdmi, HDMI_IH_I2CM_STAT0);
if (!stat)
return IRQ_NONE;
hdmi_writeb(hdmi, stat, HDMI_IH_I2CM_STAT0);
i2c->stat = stat;
complete(&i2c->cmp);
return IRQ_HANDLED;
}
static irqreturn_t dw_hdmi_hardirq(int irq, void *dev_id)
{
struct dw_hdmi *hdmi = dev_id;
u8 intr_stat;
irqreturn_t ret = IRQ_NONE;
if (hdmi->i2c)
ret = dw_hdmi_i2c_irq(hdmi);
intr_stat = hdmi_readb(hdmi, HDMI_IH_PHY_STAT0);
if (intr_stat) {
hdmi_writeb(hdmi, ~0, HDMI_IH_MUTE_PHY_STAT0);
return IRQ_WAKE_THREAD;
}
return ret;
}
static irqreturn_t dw_hdmi_irq(int irq, void *dev_id)
{
struct dw_hdmi *hdmi = dev_id;
u8 intr_stat, phy_int_pol, phy_pol_mask, phy_stat;
intr_stat = hdmi_readb(hdmi, HDMI_IH_PHY_STAT0);
phy_int_pol = hdmi_readb(hdmi, HDMI_PHY_POL0);
phy_stat = hdmi_readb(hdmi, HDMI_PHY_STAT0);
phy_pol_mask = 0;
if (intr_stat & HDMI_IH_PHY_STAT0_HPD)
phy_pol_mask |= HDMI_PHY_HPD;
if (intr_stat & HDMI_IH_PHY_STAT0_RX_SENSE0)
phy_pol_mask |= HDMI_PHY_RX_SENSE0;
if (intr_stat & HDMI_IH_PHY_STAT0_RX_SENSE1)
phy_pol_mask |= HDMI_PHY_RX_SENSE1;
if (intr_stat & HDMI_IH_PHY_STAT0_RX_SENSE2)
phy_pol_mask |= HDMI_PHY_RX_SENSE2;
if (intr_stat & HDMI_IH_PHY_STAT0_RX_SENSE3)
phy_pol_mask |= HDMI_PHY_RX_SENSE3;
if (phy_pol_mask)
hdmi_modb(hdmi, ~phy_int_pol, phy_pol_mask, HDMI_PHY_POL0);
/*
* RX sense tells us whether the TDMS transmitters are detecting
* load - in other words, there's something listening on the
* other end of the link. Use this to decide whether we should
* power on the phy as HPD may be toggled by the sink to merely
* ask the source to re-read the EDID.
*/
if (intr_stat &
(HDMI_IH_PHY_STAT0_RX_SENSE | HDMI_IH_PHY_STAT0_HPD)) {
mutex_lock(&hdmi->mutex);
if (!hdmi->disabled && !hdmi->force) {
/*
* If the RX sense status indicates we're disconnected,
* clear the software rxsense status.
*/
if (!(phy_stat & HDMI_PHY_RX_SENSE))
hdmi->rxsense = false;
/*
* Only set the software rxsense status when both
* rxsense and hpd indicates we're connected.
* This avoids what seems to be bad behaviour in
* at least iMX6S versions of the phy.
*/
if (phy_stat & HDMI_PHY_HPD)
hdmi->rxsense = true;
dw_hdmi_update_power(hdmi);
dw_hdmi_update_phy_mask(hdmi);
}
mutex_unlock(&hdmi->mutex);
}
if (intr_stat & HDMI_IH_PHY_STAT0_HPD) {
dev_dbg(hdmi->dev, "EVENT=%s\n",
phy_int_pol & HDMI_PHY_HPD ? "plugin" : "plugout");
if (hdmi->bridge.dev)
drm_helper_hpd_irq_event(hdmi->bridge.dev);
}
hdmi_writeb(hdmi, intr_stat, HDMI_IH_PHY_STAT0);
hdmi_writeb(hdmi, ~(HDMI_IH_PHY_STAT0_HPD | HDMI_IH_PHY_STAT0_RX_SENSE),
HDMI_IH_MUTE_PHY_STAT0);
return IRQ_HANDLED;
}
static const struct dw_hdmi_phy_data dw_hdmi_phys[] = {
{
.type = DW_HDMI_PHY_DWC_HDMI_TX_PHY,
.name = "DWC HDMI TX PHY",
}, {
.type = DW_HDMI_PHY_DWC_MHL_PHY_HEAC,
.name = "DWC MHL PHY + HEAC PHY",
.has_svsret = true,
}, {
.type = DW_HDMI_PHY_DWC_MHL_PHY,
.name = "DWC MHL PHY",
.has_svsret = true,
}, {
.type = DW_HDMI_PHY_DWC_HDMI_3D_TX_PHY_HEAC,
.name = "DWC HDMI 3D TX PHY + HEAC PHY",
}, {
.type = DW_HDMI_PHY_DWC_HDMI_3D_TX_PHY,
.name = "DWC HDMI 3D TX PHY",
}, {
.type = DW_HDMI_PHY_DWC_HDMI20_TX_PHY,
.name = "DWC HDMI 2.0 TX PHY",
.has_svsret = true,
}
};
static int dw_hdmi_detect_phy(struct dw_hdmi *hdmi)
{
unsigned int i;
u8 phy_type;
phy_type = hdmi_readb(hdmi, HDMI_CONFIG2_ID);
for (i = 0; i < ARRAY_SIZE(dw_hdmi_phys); ++i) {
if (dw_hdmi_phys[i].type == phy_type) {
hdmi->phy = &dw_hdmi_phys[i];
return 0;
}
}
if (phy_type == DW_HDMI_PHY_VENDOR_PHY)
dev_err(hdmi->dev, "Unsupported vendor HDMI PHY\n");
else
dev_err(hdmi->dev, "Unsupported HDMI PHY type (%02x)\n",
phy_type);
return -ENODEV;
}
static struct dw_hdmi *
__dw_hdmi_probe(struct platform_device *pdev,
const struct dw_hdmi_plat_data *plat_data)
{
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
struct platform_device_info pdevinfo;
struct device_node *ddc_node;
struct dw_hdmi *hdmi;
struct resource *iores;
int irq;
int ret;
u32 val = 1;
u8 prod_id0;
u8 prod_id1;
u8 config0;
u8 config3;
hdmi = devm_kzalloc(dev, sizeof(*hdmi), GFP_KERNEL);
if (!hdmi)
return ERR_PTR(-ENOMEM);
hdmi->plat_data = plat_data;
hdmi->dev = dev;
hdmi->dev_type = plat_data->dev_type;
hdmi->sample_rate = 48000;
hdmi->disabled = true;
hdmi->rxsense = true;
hdmi->phy_mask = (u8)~(HDMI_PHY_HPD | HDMI_PHY_RX_SENSE);
mutex_init(&hdmi->mutex);
mutex_init(&hdmi->audio_mutex);
spin_lock_init(&hdmi->audio_lock);
of_property_read_u32(np, "reg-io-width", &val);
switch (val) {
case 4:
hdmi->write = dw_hdmi_writel;
hdmi->read = dw_hdmi_readl;
break;
case 1:
hdmi->write = dw_hdmi_writeb;
hdmi->read = dw_hdmi_readb;
break;
default:
dev_err(dev, "reg-io-width must be 1 or 4\n");
return ERR_PTR(-EINVAL);
}
ddc_node = of_parse_phandle(np, "ddc-i2c-bus", 0);
if (ddc_node) {
hdmi->ddc = of_get_i2c_adapter_by_node(ddc_node);
of_node_put(ddc_node);
if (!hdmi->ddc) {
dev_dbg(hdmi->dev, "failed to read ddc node\n");
return ERR_PTR(-EPROBE_DEFER);
}
} else {
dev_dbg(hdmi->dev, "no ddc property found\n");
}
iores = platform_get_resource(pdev, IORESOURCE_MEM, 0);
hdmi->regs = devm_ioremap_resource(dev, iores);
if (IS_ERR(hdmi->regs)) {
ret = PTR_ERR(hdmi->regs);
goto err_res;
}
hdmi->isfr_clk = devm_clk_get(hdmi->dev, "isfr");
if (IS_ERR(hdmi->isfr_clk)) {
ret = PTR_ERR(hdmi->isfr_clk);
dev_err(hdmi->dev, "Unable to get HDMI isfr clk: %d\n", ret);
goto err_res;
}
ret = clk_prepare_enable(hdmi->isfr_clk);
if (ret) {
dev_err(hdmi->dev, "Cannot enable HDMI isfr clock: %d\n", ret);
goto err_res;
}
hdmi->iahb_clk = devm_clk_get(hdmi->dev, "iahb");
if (IS_ERR(hdmi->iahb_clk)) {
ret = PTR_ERR(hdmi->iahb_clk);
dev_err(hdmi->dev, "Unable to get HDMI iahb clk: %d\n", ret);
goto err_isfr;
}
ret = clk_prepare_enable(hdmi->iahb_clk);
if (ret) {
dev_err(hdmi->dev, "Cannot enable HDMI iahb clock: %d\n", ret);
goto err_isfr;
}
/* Product and revision IDs */
hdmi->version = (hdmi_readb(hdmi, HDMI_DESIGN_ID) << 8)
| (hdmi_readb(hdmi, HDMI_REVISION_ID) << 0);
prod_id0 = hdmi_readb(hdmi, HDMI_PRODUCT_ID0);
prod_id1 = hdmi_readb(hdmi, HDMI_PRODUCT_ID1);
if (prod_id0 != HDMI_PRODUCT_ID0_HDMI_TX ||
(prod_id1 & ~HDMI_PRODUCT_ID1_HDCP) != HDMI_PRODUCT_ID1_HDMI_TX) {
dev_err(dev, "Unsupported HDMI controller (%04x:%02x:%02x)\n",
hdmi->version, prod_id0, prod_id1);
ret = -ENODEV;
goto err_iahb;
}
ret = dw_hdmi_detect_phy(hdmi);
if (ret < 0)
goto err_iahb;
dev_info(dev, "Detected HDMI TX controller v%x.%03x %s HDCP (%s)\n",
hdmi->version >> 12, hdmi->version & 0xfff,
prod_id1 & HDMI_PRODUCT_ID1_HDCP ? "with" : "without",
hdmi->phy->name);
initialize_hdmi_ih_mutes(hdmi);
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
ret = irq;
goto err_iahb;
}
ret = devm_request_threaded_irq(dev, irq, dw_hdmi_hardirq,
dw_hdmi_irq, IRQF_SHARED,
dev_name(dev), hdmi);
if (ret)
goto err_iahb;
/*
* To prevent overflows in HDMI_IH_FC_STAT2, set the clk regenerator
* N and cts values before enabling phy
*/
hdmi_init_clk_regenerator(hdmi);
/* If DDC bus is not specified, try to register HDMI I2C bus */
if (!hdmi->ddc) {
hdmi->ddc = dw_hdmi_i2c_adapter(hdmi);
if (IS_ERR(hdmi->ddc))
hdmi->ddc = NULL;
}
/*
* Configure registers related to HDMI interrupt
* generation before registering IRQ.
*/
hdmi_writeb(hdmi, HDMI_PHY_HPD | HDMI_PHY_RX_SENSE, HDMI_PHY_POL0);
/* Clear Hotplug interrupts */
hdmi_writeb(hdmi, HDMI_IH_PHY_STAT0_HPD | HDMI_IH_PHY_STAT0_RX_SENSE,
HDMI_IH_PHY_STAT0);
hdmi->bridge.driver_private = hdmi;
hdmi->bridge.funcs = &dw_hdmi_bridge_funcs;
#ifdef CONFIG_OF
hdmi->bridge.of_node = pdev->dev.of_node;
#endif
ret = dw_hdmi_fb_registered(hdmi);
if (ret)
goto err_iahb;
/* Unmute interrupts */
hdmi_writeb(hdmi, ~(HDMI_IH_PHY_STAT0_HPD | HDMI_IH_PHY_STAT0_RX_SENSE),
HDMI_IH_MUTE_PHY_STAT0);
memset(&pdevinfo, 0, sizeof(pdevinfo));
pdevinfo.parent = dev;
pdevinfo.id = PLATFORM_DEVID_AUTO;
config0 = hdmi_readb(hdmi, HDMI_CONFIG0_ID);
config3 = hdmi_readb(hdmi, HDMI_CONFIG3_ID);
if (config3 & HDMI_CONFIG3_AHBAUDDMA) {
struct dw_hdmi_audio_data audio;
audio.phys = iores->start;
audio.base = hdmi->regs;
audio.irq = irq;
audio.hdmi = hdmi;
audio.eld = hdmi->connector.eld;
pdevinfo.name = "dw-hdmi-ahb-audio";
pdevinfo.data = &audio;
pdevinfo.size_data = sizeof(audio);
pdevinfo.dma_mask = DMA_BIT_MASK(32);
hdmi->audio = platform_device_register_full(&pdevinfo);
} else if (config0 & HDMI_CONFIG0_I2S) {
struct dw_hdmi_i2s_audio_data audio;
audio.hdmi = hdmi;
audio.write = hdmi_writeb;
audio.read = hdmi_readb;
pdevinfo.name = "dw-hdmi-i2s-audio";
pdevinfo.data = &audio;
pdevinfo.size_data = sizeof(audio);
pdevinfo.dma_mask = DMA_BIT_MASK(32);
hdmi->audio = platform_device_register_full(&pdevinfo);
}
/* Reset HDMI DDC I2C master controller and mute I2CM interrupts */
if (hdmi->i2c)
dw_hdmi_i2c_init(hdmi);
platform_set_drvdata(pdev, hdmi);
return hdmi;
err_iahb:
if (hdmi->i2c) {
i2c_del_adapter(&hdmi->i2c->adap);
hdmi->ddc = NULL;
}
clk_disable_unprepare(hdmi->iahb_clk);
err_isfr:
clk_disable_unprepare(hdmi->isfr_clk);
err_res:
i2c_put_adapter(hdmi->ddc);
return ERR_PTR(ret);
}
static void __dw_hdmi_remove(struct dw_hdmi *hdmi)
{
if (hdmi->audio && !IS_ERR(hdmi->audio))
platform_device_unregister(hdmi->audio);
/* Disable all interrupts */
hdmi_writeb(hdmi, ~0, HDMI_IH_MUTE_PHY_STAT0);
clk_disable_unprepare(hdmi->iahb_clk);
clk_disable_unprepare(hdmi->isfr_clk);
if (hdmi->i2c)
i2c_del_adapter(&hdmi->i2c->adap);
else
i2c_put_adapter(hdmi->ddc);
}
/* -----------------------------------------------------------------------------
* Probe/remove API, used from platforms based on the DRM bridge API.
*/
int dw_hdmi_probe(struct platform_device *pdev,
const struct dw_hdmi_plat_data *plat_data)
{
struct dw_hdmi *hdmi;
int ret;
hdmi = __dw_hdmi_probe(pdev, plat_data);
if (IS_ERR(hdmi))
return PTR_ERR(hdmi);
ret = drm_bridge_add(&hdmi->bridge);
if (ret < 0) {
__dw_hdmi_remove(hdmi);
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(dw_hdmi_probe);
void dw_hdmi_remove(struct platform_device *pdev)
{
struct dw_hdmi *hdmi = platform_get_drvdata(pdev);
drm_bridge_remove(&hdmi->bridge);
__dw_hdmi_remove(hdmi);
}
EXPORT_SYMBOL_GPL(dw_hdmi_remove);
/* -----------------------------------------------------------------------------
* Bind/unbind API, used from platforms based on the component framework.
*/
int dw_hdmi_bind(struct platform_device *pdev, struct drm_encoder *encoder,
const struct dw_hdmi_plat_data *plat_data)
{
struct dw_hdmi *hdmi;
int ret;
hdmi = __dw_hdmi_probe(pdev, plat_data);
if (IS_ERR(hdmi))
return PTR_ERR(hdmi);
ret = drm_bridge_attach(encoder, &hdmi->bridge, NULL);
if (ret) {
dw_hdmi_remove(pdev);
DRM_ERROR("Failed to initialize bridge with drm\n");
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(dw_hdmi_bind);
void dw_hdmi_unbind(struct device *dev)
{
struct dw_hdmi *hdmi = dev_get_drvdata(dev);
__dw_hdmi_remove(hdmi);
}
EXPORT_SYMBOL_GPL(dw_hdmi_unbind);
MODULE_AUTHOR("Sascha Hauer <s.hauer@pengutronix.de>");
MODULE_AUTHOR("Andy Yan <andy.yan@rock-chips.com>");
MODULE_AUTHOR("Yakir Yang <ykk@rock-chips.com>");
MODULE_AUTHOR("Vladimir Zapolskiy <vladimir_zapolskiy@mentor.com>");
MODULE_DESCRIPTION("DW HDMI transmitter driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:dw-hdmi");
| 27.486499 | 81 | 0.733066 | [
"3d"
] |
9a9f47f1038de4aeb02cb5926bd3a6ad884d531c | 15,941 | h | C | velox/exec/HashTable.h | pzhzqt/velox | 951a8bcf815763c2e9c939bc72f7d23a1a1045c3 | [
"Apache-2.0"
] | null | null | null | velox/exec/HashTable.h | pzhzqt/velox | 951a8bcf815763c2e9c939bc72f7d23a1a1045c3 | [
"Apache-2.0"
] | null | null | null | velox/exec/HashTable.h | pzhzqt/velox | 951a8bcf815763c2e9c939bc72f7d23a1a1045c3 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "velox/common/memory/MappedMemory.h"
#include "velox/exec/Aggregate.h"
#include "velox/exec/Operator.h"
#include "velox/exec/RowContainer.h"
#include "velox/exec/VectorHasher.h"
namespace facebook::velox::exec {
struct HashLookup {
explicit HashLookup(const std::vector<std::unique_ptr<VectorHasher>>& h)
: hashers(h) {}
void reset(vector_size_t size) {
rows.resize(size);
hashes.resize(size);
hits.resize(size);
std::fill(hits.begin(), hits.end(), nullptr);
newGroups.clear();
}
// One entry per aggregation or join key
const std::vector<std::unique_ptr<VectorHasher>>& hashers;
raw_vector<vector_size_t> rows;
// Hash number for all input rows.
raw_vector<uint64_t> hashes;
// If using valueIds, list of concatenated valueIds. 1:1 with 'hashes'.
raw_vector<uint64_t> normalizedKeys;
// Hit for each row of input. nullptr if no hit. Points to the
// corresponding group row.
raw_vector<char*> hits;
std::vector<vector_size_t> newGroups;
};
class BaseHashTable {
public:
using normalized_key_t = uint64_t;
using TagVector = __m128i;
using MaskType = uint16_t;
// 2M entries, i.e. 16MB is the largest array based hash table.
static constexpr uint64_t kArrayHashMaxSize = 2L << 20;
enum class HashMode { kHash, kArray, kNormalizedKey };
// Keeps track of results returned from a join table. One batch of
// keys can produce multiple batches of results. This is initialized
// from HashLookup, which is expected to stay constant while 'this'
// is being used.
struct JoinResultIterator {
void reset(const HashLookup& lookup) {
rows = &lookup.rows;
hits = &lookup.hits;
nextHit = nullptr;
lastRowIndex = 0;
}
bool atEnd() const {
return lastRowIndex == rows->size();
}
const raw_vector<vector_size_t>* rows;
const raw_vector<char*>* hits;
char* nextHit{nullptr};
vector_size_t lastRowIndex{0};
};
struct NotProbedRowsIterator {
int32_t hashTableIndex_{-1};
RowContainerIterator rowContainerIterator_;
};
/// Takes ownership of 'hashers'. These are used to keep key-level
/// encodings like distinct values, ranges. These are stateful for
/// kArray and kNormalizedKey hash modes and track the data
/// population while adding payload for either aggregation or join
/// build.
explicit BaseHashTable(std::vector<std::unique_ptr<VectorHasher>>&& hashers)
: hashers_(std::move(hashers)) {}
virtual ~BaseHashTable() = default;
virtual HashStringAllocator* stringAllocator() = 0;
/// Finds or creates a group for each key in 'lookup'. The keys are
/// returned in 'lookup.hits'.
virtual void groupProbe(HashLookup& lookup) = 0;
/// Returns the first hit for each key in 'lookup'. The keys are in
/// 'lookup.hits' with a nullptr representing a miss. This is for use in hash
/// join probe. Use listJoinResults to iterate over the results.
virtual void joinProbe(HashLookup& lookup) = 0;
/// Fills 'hits' with consecutive hash join results. The corresponding element
/// of 'inputRows' is set to the corresponding row number in probe keys.
/// Returns the number of hits produced. If this s less than hits.size() then
/// all the hits have been produced.
/// Adds input rows without a match to 'inputRows' with corresponding hit
/// set to nullptr if 'includeMisses' is true. Otherwise, skips input rows
/// without a match. 'includeMisses' is set to true when listing results for
/// the LEFT join.
virtual int32_t listJoinResults(
JoinResultIterator& iter,
bool includeMisses,
folly::Range<vector_size_t*> inputRows,
folly::Range<char**> hits) = 0;
/// Returns rows with 'probed' flag unset. Used by the right join.
virtual int32_t listNotProbedRows(
NotProbedRowsIterator* iter,
int32_t maxRows,
uint64_t maxBytes,
char** rows) = 0;
virtual void prepareJoinTable(
std::vector<std::unique_ptr<BaseHashTable>> tables) = 0;
/// Returns the memory footprint in bytes for any data structures
/// owned by 'this'.
virtual int64_t allocatedBytes() const = 0;
/// Deletes any content of 'this' but does not free the memory. Can
/// be used for flushing a partial group by, for example.
virtual void clear() = 0;
/// Returns the number of rows in a group by or hash join build
/// side. This is used for sizing the internal hash table.
virtual uint64_t numDistinct() const = 0;
/// Returns true if the hash table contains rows with duplicate keys.
virtual bool hasDuplicateKeys() const = 0;
/// Returns the hash mode. This is needed for the caller to calculate
/// the hash numbers using the appropriate method of the
/// VectorHashers of 'this'.
virtual HashMode hashMode() const = 0;
/// Disables use of array or normalized key hash modes.
void forceGenericHashMode() {
setHashMode(HashMode::kHash, 0);
}
/// Decides the hash table representation based on the statistics in
/// VectorHashers of 'this'. This must be called if we are in
/// normalized key or array based hash mode and some new keys are not
/// compatible with the encoding. This is notably the case on first
/// insert where there are no encodings in place. Rehashes the table
/// based on the statistics in Vectorhashers if the table is not
/// empty. After calling this, the caller must recompute the hash of
/// the key columns as the mappings in VectorHashers will have
/// changed. The table is set up so as to take at least 'numNew'
/// distinct entries before needing to rehash.
virtual void decideHashMode(int32_t numNew) = 0;
// Removes 'rows' from the hash table and its RowContainer. 'rows' must exist
// and be unique.
virtual void erase(folly::Range<char**> rows) = 0;
/// Returns a brief description for use in debugging.
virtual std::string toString() = 0;
static void storeTag(uint8_t* tags, int32_t index, uint8_t tag) {
tags[index] = tag;
}
const std::vector<std::unique_ptr<VectorHasher>>& hashers() const {
return hashers_;
}
RowContainer* rows() const {
return rows_.get();
}
// Static functions for processing internals. Public because used in
// structs that define probe and insert algorithms. These are
// concentrated here to abstract away data layout, e.g tags and
// payload pointers separate/interleaved.
/// Extracts a 7 bit tag from a hash number. The high bit is always set.
static uint8_t hashTag(uint64_t hash) {
return static_cast<uint8_t>(hash >> 32) | 0x80;
}
/// Loads a vector of tags for bulk comparison.
template <typename T>
static TagVector loadTags(T* tags, int32_t tagIndex) {
auto tagPtr =
reinterpret_cast<TagVector*>(reinterpret_cast<char*>(tags) + tagIndex);
return _mm_load_si128(tagPtr);
}
/// Loads the payload row pointer corresponding to the tag at 'index'.
static char* loadRow(char** table, int32_t index) {
return table[index];
}
protected:
virtual void setHashMode(HashMode mode, int32_t numNew) = 0;
std::vector<std::unique_ptr<VectorHasher>> hashers_;
std::unique_ptr<RowContainer> rows_;
};
class ProbeState;
template <bool ignoreNullKeys>
class HashTable : public BaseHashTable {
public:
// Can be used for aggregation or join. An aggregation hash table
// can also double as a join build side. 'isJoinBuild' is true if
// this is a build side. 'allowDuplicates' is false for a build side if
// second occurrences of a key are to be silently ignored or will
// not occur. In this case the row does not need a link to the next
// match. 'hasProbedFlag' adds an extra bit in every row for tracking rows
// that matches join condition for right and full outer joins.
HashTable(
std::vector<std::unique_ptr<VectorHasher>>&& hashers,
const std::vector<std::unique_ptr<Aggregate>>& aggregates,
const std::vector<TypePtr>& dependentTypes,
bool allowDuplicates,
bool isJoinBuild,
bool hasProbedFlag,
memory::MappedMemory* memory);
static std::unique_ptr<HashTable> createForAggregation(
std::vector<std::unique_ptr<VectorHasher>>&& hashers,
const std::vector<std::unique_ptr<Aggregate>>& aggregates,
memory::MappedMemory* memory) {
return std::make_unique<HashTable>(
std::move(hashers),
aggregates,
std::vector<TypePtr>{},
false, // allowDuplicates
false, // isJoinBuild
false, // hasProbedFlag
memory);
}
static std::unique_ptr<HashTable> createForJoin(
std::vector<std::unique_ptr<VectorHasher>>&& hashers,
const std::vector<TypePtr>& dependentTypes,
bool allowDuplicates,
bool hasProbedFlag,
memory::MappedMemory* memory) {
static const std::vector<std::unique_ptr<Aggregate>> kNoAggregates;
return std::make_unique<HashTable>(
std::move(hashers),
kNoAggregates,
dependentTypes,
allowDuplicates,
true, // isJoinBuild
hasProbedFlag,
memory);
}
virtual ~HashTable() override {
allocateTables(0);
}
void groupProbe(HashLookup& lookup) override;
void joinProbe(HashLookup& lookup) override;
int32_t listJoinResults(
JoinResultIterator& iter,
bool includeMisses,
folly::Range<vector_size_t*> inputRows,
folly::Range<char**> hits) override;
int32_t listNotProbedRows(
NotProbedRowsIterator* iter,
int32_t maxRows,
uint64_t maxBytes,
char** rows) override;
void clear() override;
int64_t allocatedBytes() const override {
// for each row: 1 byte per tag + sizeof(Entry) per table entry + memory
// allocated with MappedMemory for fixed-width rows and strings.
return (1 + sizeof(char*)) * size_ + rows_->allocatedBytes();
}
HashStringAllocator* stringAllocator() override {
return &rows_->stringAllocator();
}
uint64_t numDistinct() const override {
return numDistinct_;
}
bool hasDuplicateKeys() const override {
return hasDuplicates_;
}
HashMode hashMode() const override {
return hashMode_;
}
void decideHashMode(int32_t numNew) override;
void erase(folly::Range<char**> rows) override;
// Moves the contents of 'tables' into 'this' and prepares 'this'
// for use in hash join probe. A hash join build side is prepared as
// follows: 1. Each build side thread gets a random selection of the
// build stream. Each accumulates rows into its own
// HashTable'sRowContainer and updates the VectorHashers of the
// table to reflect the data as long as the data shows promise for
// kArray or kNormalizedKey representation. After all the build
// tables are filled, they are combined into one top level table
// with prepareJoinTable. This then takes ownership of all the data
// and VectorHashers and decides the hash mode and representation.
void prepareJoinTable(
std::vector<std::unique_ptr<BaseHashTable>> tables) override;
std::string toString() override;
private:
char*& nextRow(char* row) {
return *reinterpret_cast<char**>(row + nextOffset_);
}
void arrayGroupProbe(HashLookup& lookup);
void setHashMode(HashMode mode, int32_t numNew) override;
/// Adds extra values for value id ranges for group by hash tables in
/// kArray or kNormalizedKey mode. Identity for join tables since all
/// keys are known at build time.
int64_t addReserve(int64_t count, TypeKind kind);
/// Tries to use as many range hashers as can in a normalized key situation.
void enableRangeWhereCan(
const std::vector<uint64_t>& rangeSizes,
const std::vector<uint64_t>& distinctSizes,
std::vector<bool>& useRange);
/// Sets value ranges or distinct value ids mode for
/// VectorHashers in a kArray or kNormalizedKeys mode table.
uint64_t setHasherMode(
const std::vector<std::unique_ptr<VectorHasher>>& hashers,
const std::vector<bool>& useRange,
const std::vector<uint64_t>& rangeSizes,
const std::vector<uint64_t>& distinctSizes);
void rehash();
void initializeNewGroups(HashLookup& lookup);
void storeKeys(HashLookup& lookup, vector_size_t row);
void storeRowPointer(int32_t index, uint64_t hash, char* row);
// Allocates new tables for tags and payload pointers. The size must
// a power of 2.
void allocateTables(uint64_t size);
void checkSize(int32_t numNew);
// Computes hash numbers of the appropriate hash mode for 'groups',
// stores these in 'hashes' and inserts the groups using
// insertForJoin or insertForGroupBy.
bool
insertBatch(char** groups, int32_t numGroups, raw_vector<uint64_t>& hashes);
// Inserts 'numGroups' entries into 'this'. 'groups' point to
// contents in a RowContainer owned by 'this'. 'hashes' are te hash
// numbers or array indices (if kArray mode) for each
// group. Duplicate key rows are chained via their next link.
void insertForJoin(char** groups, uint64_t* hashes, int32_t numGroups);
// Inserts 'numGroups' entries into 'this'. 'groups' point to
// contents in a RowContainer owned by 'this'. 'hashes' are te hash
// numbers or array indices (if kArray mode) for each
// group. 'groups' is expectedd to have no duplicate keys.
void insertForGroupBy(char** groups, uint64_t* hashes, int32_t numGroups);
char* insertEntry(HashLookup& lookup, int32_t index, vector_size_t row);
bool compareKeys(const char* group, HashLookup& lookup, vector_size_t row);
bool compareKeys(const char* group, const char* inserted);
template <bool isJoin>
void fullProbe(HashLookup& lookup, ProbeState& state, bool extraCheck);
// Adds a row to a hash join table in kArray hash mode. Returns true
// if a new entry was made and false if the row was added to an
// existing set of rows with the same key.
bool arrayPushRow(char* row, int32_t index);
// Adds a row to a hash join build side entry with multiple rows
// with the same key.
void pushNext(char* row, char* next);
// Finishes inserting an entry into a join hash table.
void
buildFullProbe(ProbeState& state, uint64_t hash, char* row, bool extraCheck);
// Updates 'hashers_' to correspond to the keys in the
// content. Returns true if all hashers offer a mapping to value ids
// for array or normalized key.
bool analyze();
// Erases the entries of rows from the hash table and its RowContainer.
// 'hashes' must be computed according to 'hashMode_'.
void eraseWithHashes(folly::Range<char**> rows, uint64_t* hashes);
const std::vector<std::unique_ptr<Aggregate>>& aggregates_;
int8_t sizeBits_;
bool isJoinBuild_ = false;
// Set at join build time if the table has duplicates, meaning
// that the join can be cardinality increasing.
bool hasDuplicates_ = false;
// Offset of next row link for join build side, 0 if none. Copied
// from 'rows_'.
int32_t nextOffset_;
uint8_t* tags_ = nullptr;
char** table_ = nullptr;
int64_t size_ = 0;
int64_t sizeMask_ = 0;
int64_t numDistinct_ = 0;
HashMode hashMode_ = HashMode::kArray;
// Owns the memory of multiple build side hash join tables that are
// combined into a single probe hash table.
std::vector<std::unique_ptr<HashTable<ignoreNullKeys>>> otherTables_;
};
} // namespace facebook::velox::exec
| 35.742152 | 80 | 0.70993 | [
"vector"
] |
9a9f4f3d2f5a48dc540607daf85f38b1a9b0194d | 3,577 | h | C | DeferredShading/app.h | colintan95/DX12Techniques | 421192fae0d4ddc8450cfeeaa5913c2aacf8fce7 | [
"MIT"
] | null | null | null | DeferredShading/app.h | colintan95/DX12Techniques | 421192fae0d4ddc8450cfeeaa5913c2aacf8fce7 | [
"MIT"
] | null | null | null | DeferredShading/app.h | colintan95/DX12Techniques | 421192fae0d4ddc8450cfeeaa5913c2aacf8fce7 | [
"MIT"
] | null | null | null | #ifndef APP_H_
#define APP_H_
#include <d3d12.h>
#include <dxgi1_6.h>
#include <wrl/client.h>
#include <memory>
#include <vector>
#include "d3dx12.h"
#include "DirectXMath.h"
// TODO: See if this can be removed. Currently needed so that "Model.h" doesn't error out.
#include <stdexcept>
#include "GraphicsMemory.h"
#include "Model.h"
#include "constants.h"
#include "geometry_pass.h"
#include "lighting_pass.h"
#include "shadow_pass.h"
struct Material {
DirectX::XMFLOAT4 ambient_color;
DirectX::XMFLOAT4 diffuse_color;
};
class App {
public:
App(HWND window_hwnd, int window_width, int window_height);
void Initialize();
void Cleanup();
void RenderFrame();
private:
friend class GeometryPass;
friend class LightingPass;
friend class ShadowPass;
void InitDeviceAndSwapChain();
void InitCommandAllocators();
void InitFence();
void InitPipelines();
void InitDescriptorHeaps();
void InitResources();
void CreateSharedBuffers();
void LoadModelData();
void InitMatrices();
void UploadDataToBuffer(const void* data, UINT64 data_size, ID3D12Resource* dst_buffer);
void MoveToNextFrame();
void WaitForGpu();
ShadowPass shadow_pass_;
GeometryPass geometry_pass_;
LightingPass lighting_pass_;
HWND window_hwnd_;
int window_width_;
int window_height_;
int frame_index_ = 0;
D3D_ROOT_SIGNATURE_VERSION root_signature_version_;
CD3DX12_VIEWPORT viewport_;
CD3DX12_RECT scissor_rect_;
Microsoft::WRL::ComPtr<ID3D12Device> device_;
Microsoft::WRL::ComPtr<ID3D12CommandQueue> command_queue_;
Microsoft::WRL::ComPtr<IDXGISwapChain3> swap_chain_;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> command_list_;
Microsoft::WRL::ComPtr<ID3D12Fence> fence_;
UINT64 latest_fence_value_ = 0;
HANDLE fence_event_;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtv_heap_;
UINT rtv_descriptor_size_ = 0;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> dsv_heap_;
UINT dsv_descriptor_size_ = 0;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> cbv_srv_heap_;
UINT cbv_srv_descriptor_size_ = 0;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> sampler_heap_;
UINT sampler_descriptor_size_ = 0;
std::vector<Microsoft::WRL::ComPtr<ID3D12Resource>> upload_buffers_;
Microsoft::WRL::ComPtr<ID3D12Resource> depth_stencil_;
struct Frame {
Microsoft::WRL::ComPtr<ID3D12CommandAllocator> command_allocator;
Microsoft::WRL::ComPtr<ID3D12Resource> swap_chain_buffer;
Microsoft::WRL::ComPtr<ID3D12Resource> gbuffer;
Microsoft::WRL::ComPtr<ID3D12Resource> pos_gbuffer;
Microsoft::WRL::ComPtr<ID3D12Resource> diffuse_gbuffer;
Microsoft::WRL::ComPtr<ID3D12Resource> normal_gbuffer;
Microsoft::WRL::ComPtr<ID3D12Resource> shadow_cubemap;
UINT64 fence_value = 0;
};
Frame frames_[kNumFrames];
std::unique_ptr<DirectX::GraphicsMemory> graphics_memory_;
std::unique_ptr<DirectX::Model> model_;
struct DrawCallArgs {
D3D12_PRIMITIVE_TOPOLOGY primitive_type;
D3D12_VERTEX_BUFFER_VIEW vertex_buffer_view;
D3D12_INDEX_BUFFER_VIEW index_buffer_view;
uint32_t index_count;
uint32_t start_index;
int32_t vertex_offset;
uint32_t material_index;
};
float camera_yaw_ = 0.f;
float camera_pitch_ = 0.f;
float camera_roll_ = 0.f;
std::vector<DrawCallArgs> draw_call_args_;
DirectX::XMFLOAT4X4 world_view_mat_;
DirectX::XMFLOAT4X4 world_view_proj_mat_;
DirectX::XMFLOAT4X4 shadow_mats_[6];
std::vector<Material> materials_;
DirectX::XMFLOAT4 light_pos_;
DirectX::XMFLOAT4 light_view_pos_;
};
#endif // APP_H_ | 23.532895 | 90 | 0.762091 | [
"vector",
"model"
] |
9aa14bbdbb33508c608445ec4a1909d30d434888 | 12,273 | h | C | sys/include/c++/task.h | henesy/plan9-1e | 47575dc4a4638a1ee0d9eed78d88a9f1720a4430 | [
"MIT"
] | 1 | 2021-03-23T22:40:43.000Z | 2021-03-23T22:40:43.000Z | sys/include/c++/task.h | henesy/plan9-1e | 47575dc4a4638a1ee0d9eed78d88a9f1720a4430 | [
"MIT"
] | null | null | null | sys/include/c++/task.h | henesy/plan9-1e | 47575dc4a4638a1ee0d9eed78d88a9f1720a4430 | [
"MIT"
] | 1 | 2021-12-21T06:19:58.000Z | 2021-12-21T06:19:58.000Z | /*ident "@(#)C++env:incl-master/const-headers/task.h 1.6" */
/**************************************************************************
Copyright (c) 1984 AT&T
All Rights Reserved
THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T
The copyright notice above does not evidence any
actual or intended publication of such source code.
*****************************************************************************/
#ifndef TASKH
#define TASKH
#pragma "ape/libap.a"
#pragma "c++/libC.a"
#pragma "c++/libtask.a"
/* HEADER FILE FOR THE TASK SYSTEM */
#include <stdio.h>
#include "label.h" /* like setjmp, but really works */
class object;
class sched; /* : public object */
class timer; /* : public sched */
class task; /* : public sched */
class qhead; /* : public object */
class qtail; /* : public object */
class team;
#if defined(_SHARED_ONLY)
#define DEFAULT_MODE SHARED
#else
#define DEFAULT_MODE DEDICATED
#endif
/* error codes */
#define task_error_messages \
macro_start \
macro(0,E_ERROR,"") \
macro(1,E_OLINK,"object::delete(): has chain") \
macro(2,E_ONEXT,"object::delete(): on chain") \
macro(3,E_GETEMPTY,"qhead::get(): empty") \
macro(4,E_PUTOBJ,"qtail::put(): object on other queue") \
macro(5,E_PUTFULL,"qtail::put(): full") \
macro(6,E_BACKOBJ,"qhead::putback(): object on other queue") \
macro(7,E_BACKFULL,"qhead::putback(): full") \
macro(8,E_SETCLOCK,"sched::setclock(): clock!=0") \
macro(9,E_CLOCKIDLE,"sched::schedule(): clock_task not idle") \
macro(10,E_RESTERM,"sched::insert(): cannot schedule terminated sched") \
macro(11,E_RESRUN,"sched::schedule(): running") \
macro(12,E_NEGTIME,"sched::schedule(): clock<0") \
macro(13,E_RESOBJ,"sched::schedule(): task or timer on other queue") \
macro(14,E_HISTO,"histogram::histogram(): bad arguments") \
macro(15,E_STACK,"task::restore() or task::task(): stack overflow") \
macro(16,E_STORE,"new: free store exhausted") \
macro(17,E_TASKMODE,"task::task(): bad mode") \
macro(18,E_TASKDEL,"task::~task(): not terminated") \
macro(19,E_TASKPRE,"task::preempt(): not running") \
macro(20,E_TIMERDEL,"timer::~timer(): not terminated") \
macro(21,E_SCHTIME,"sched::schedule(): runchain corrupted: bad time") \
macro(22,E_SCHOBJ,"sched object used directly (not as base)") \
macro(23,E_QDEL,"queue::~queue(): not empty") \
macro(24,E_RESULT,"task::result(): thistask->result()") \
macro(25,E_WAIT,"task::wait(): wait for self") \
macro(26,E_FUNCS,"FrameLayout::FrameLayout(): function start") \
macro(27,E_FRAMES,"FrameLayout::FrameLayout(): frame size") \
macro(28,E_REGMASK,"task::fudge_return(): unexpected register mask") \
macro(29,E_FUDGE_SIZE,"task::fudge_return(): frame too big") \
macro(30,E_NO_HNDLR,"sigFunc - no handler for signal") \
macro(31,E_BADSIG,"illegal signal number") \
macro(32,E_LOSTHNDLR,"Interrupt_handler::~Interrupt_handler(): signal handler not on chain") \
macro_end(E_LOSTHNDLR)
#define macro_start
#define macro(num,name,string) const name = num ;
#define macro_end(last_name) const MAXERR = last_name;
task_error_messages
#undef macro_start
#undef macro
#undef macro_end
typedef int (*PFIO)(int,object*);
typedef void (*PFV)();
/* print flags, used as arguments to class print functions */
#define CHAIN 1
#define VERBOSE 2
#define STACK 4
/* DATA STRUCTURES */
/*
object --> olink --> olink ...
| | |
... V V
| task task
V
object --> ...
*/
class olink
/* the building block for chains of task pointers */
{
friend object;
olink* l_next;
task* l_task;
olink(task* t, olink* l) { l_task=t; l_next=l; };
};
class object
{
friend sched;
friend task;
public:
enum objtype { OBJECT, TIMER, TASK, QHEAD, QTAIL, INTHANDLER };
private:
olink* o_link;
static task* thxstxsk;
public:
object* o_next;
virtual objtype o_type() { return OBJECT; }
object() { o_link=0; o_next=0; }
virtual ~object();
void remember(task*); // save for alert
void forget(task*); // remove all occurrences of task from chain
void alert(); // prepare IDLE tasks for scheduling
virtual int pending(); // TRUE if this object should be waited for
virtual void print(int, int =0); // 1st arg VERBOSE, CHAIN, or STACK
static int task_error(int, object*);
// the central error function
int task_error(int); // obsolete; use static version
static task* this_task() { return thxstxsk; }
static PFIO error_fct; // user-supplied error function
};
// fake compatibility with previous version
#define thistask (object::this_task())
void _print_error(int);
class sched : public object { // only instances of subclasses are used
friend timer;
friend task;
friend object;
friend void _print_error(int n);
//friend SIG_FUNC_TYP sigFunc;
public:
enum statetype { IDLE=1, RUNNING=2, TERMINATED=4 };
private:
static int keep_waiting_count;
static sched* runchain; // list of ready-to-run scheds (by s_time)
static sched* priority_sched; // if non-zero, sched to run next
static long clxck;
static int exit_status;
long s_time; /* time to sched; result after cancel() */
statetype s_state; /* IDLE, RUNNING, TERMINATED */
void schedule(); /* sched clock_task or front of runchain */
virtual void resume();
void insert(long,object*); /* sched for long time units, t_alert=obj */
void remove(); /* remove from runchain & make IDLE */
protected:
sched() : s_time(0), s_state(IDLE) {}
public:
static void setclock(long);
static long get_clock() { return clxck; }
static sched* get_run_chain() { return runchain; }
static int get_exit_status() { return exit_status; }
static void set_exit_status( int i ) { exit_status = i; }
sched* get_priority_sched() { return priority_sched; }
static task* clock_task; // awoken at each clock tick
long rdtime() { return s_time; };
statetype rdstate() { return s_state; };
int pending() { return s_state != TERMINATED; }
int keep_waiting() { return keep_waiting_count++; }
int dont_wait() { return keep_waiting_count--; }
void cancel(int);
int result();
virtual void setwho(object* t); // who alerted me
void print(int, int =0);
static PFV exit_fct; // user-supplied exit function
};
// for compatibility with pre-2.0 releases,
// but conflicts with time.h
//#define clock (sched::get_clock())
inline void setclock(long i) { sched::setclock(i); }
// for compatibility with pre-2.0 releases
#define run_chain (sched::get_run_chain())
class timer : public sched {
void resume();
public:
timer(long);
~timer();
void reset(long);
object::objtype o_type() { return TIMER; }
void setwho(object*) { } // do nothing
void print(int, int =0);
};
/* check stack size if set */
extern _hwm;
class task : public sched {
friend sched;
friend void __task__init();
public:
enum modetype { DEDICATED=1, SHARED=2 };
private:
static task* txsk_chxin; // list of all tasks
static team* team_to_delete; // delete this team after task switch
int curr_hwm(); // "high water mark"
// (how high stack has risen)
int swap_stack(int*,int*); // initialize child stack */
void fudge_return(int*); //used in starting new tasks
void copy_share(); // used in starting shared tasks
void get_size(); // ditto -- saves size of active stack
void resume();
void swap(int);
void swapjmp();
void doswap(task *, int);
Label copy_task(Label, unsigned long *, unsigned long *);
// simple check for stack overflow--not used for main task
void settrap();
void checktrap();
/* WARNING: t_framep, th, and t_ap are manipulated as offsets from
* task by swap(); those, and t_basep, t_size, and t_savearea are
* manipulated as offsets by sswap().
* Do not insert new data members before these.
*/
Label t_env; // stuff needed to restore process
unsigned long t_size; // size of active stack (used for SHARED)
// holds hwm after cancel()
long t_trap; // used for stack overflow check
team *t_team; // stack and info for sharing
char *t_savearea; // area SHARED stack saved
char *t_save; // area SHARED stack saved
modetype t_mode; /* DEDICATED/SHARED stack */
int t_stacksize;
object* t_alert; /* object that inserted you */
protected:
task(char *name=0, modetype mode=DEFAULT_MODE, int stacksize=0);
public:
~task();
object::objtype o_type() { return TASK; }
task* t_next; /* insertion in "task_chain" */
char* t_name;
static task* get_task_chain() { return txsk_chxin; }
int waitvec(object**);
int waitlist(object* ...);
void wait(object* ob);
void delay(long);
long preempt();
void sleep(object* t =0); // t is remembered
void resultis(int);
void cancel(int);
void setwho(object* t) { t_alert = t; }
void print(int, int =0);
object* who_alerted_me() { return t_alert; }
};
// for compatibility
#define task_chain (task::get_task_chain())
// an Interrupt_handler supplies an interrupt routine that runs when the
// interrupt occurs (real time). Also the Interrupt_handler can be waited for.
class Interrupt_handler : public object {
friend class Interrupt_alerter;
//friend SIG_FUNC_TYP sigFunc;
int id; // signal or interrupt number
int got_interrupt; // an interrupt has been received
// but not alerted
Interrupt_handler *old; // previous handler for this signal
virtual void interrupt(); // runs at real time
public:
Interrupt_handler(int sig_num);
~Interrupt_handler();
object::objtype o_type() { return INTHANDLER; }
int pending(); // FALSE once after interrupt
};
/* QUEUE MANIPULATION (see queue.c) */
/*
qhead <--> oqueue <--> qtail (qhead, qtail independent)
oqueue ->> circular queue of objects
*/
/* qh_modes */
enum qmodetype { EMODE, WMODE, ZMODE };
class oqueue
{
friend qhead;
friend qtail;
int q_max;
int q_count;
object* q_ptr;
qhead* q_head;
qtail* q_tail;
oqueue(int m) { q_max=m; q_count=0; q_head=0; q_tail=0; };
~oqueue() { (q_count)?object::task_error(E_QDEL,0):0; };
void print(int);
};
class qhead : public object
{
friend qtail;
qmodetype qh_mode; /* EMODE,WMODE,ZMODE */
oqueue* qh_queue;
public:
qhead(qmodetype = WMODE, int = 10000);
~qhead();
object::objtype o_type() { return QHEAD; }
object* get();
int putback(object*);
int rdcount() { return qh_queue->q_count; }
int rdmax() { return qh_queue->q_max; }
qmodetype rdmode() { return qh_mode; }
qtail* tail();
qhead* cut();
void splice(qtail*);
void setmode(qmodetype m) { qh_mode = m; };
void setmax(int m) { qh_queue->q_max = m; };
int pending() { return rdcount() == 0; }
void print(int, int =0);
};
class qtail : public object
{
friend qhead;
qmodetype qt_mode;
oqueue* qt_queue;
public:
qtail(qmodetype = WMODE, int = 10000);
~qtail();
object::objtype o_type() { return QTAIL; }
int put(object*);
int rdspace()
{ return qt_queue->q_max - qt_queue->q_count; };
int rdmax() { return qt_queue->q_max; };
qmodetype rdmode() { return qt_mode; };
qtail* cut();
void splice(qhead*);
qhead* head();
void setmode(qmodetype m) { qt_mode = m; };
void setmax(int m) { qt_queue->q_max = m; };
int pending() { return rdspace() == 0; }
void print(int, int =0);
};
struct histogram
/*
"nbin" bins covering the range [l:r] uniformly
nbin*binsize == r-l
*/
{
int l, r;
int binsize;
int nbin;
int* h;
long sum;
long sqsum;
histogram(int=16, int=0, int=16);
void add(int);
void print();
};
/* the result of randint() is always >= 0 */
#define DRAW (randx = randx*1103515245 + 12345)
#define ABS(x) (x&0x7fffffff)
#define MASK(x) ABS(x)
class randint
/* uniform distribution in the interval [0,MAXINT_AS_FLOAT] */
{
long randx;
public:
randint(long s = 0) { randx=s; }
void seed(long s) { randx=s; }
int draw() { return MASK(DRAW); }
float fdraw();
};
class urand : public randint
/* uniform distribution in the interval [low,high] */
{
public:
int low, high;
urand(int l, int h) { low=l; high=h; }
int draw();
};
class erand : public randint
/* exponential distribution random number generator */
{
public:
int mean;
erand(int m) { mean=m; };
int draw();
};
// This task will alert Interrupt_handler objects.
class Interrupt_alerter : public task {
public:
Interrupt_alerter();
~Interrupt_alerter() { cancel (0); }
};
extern Interrupt_alerter interrupt_alerter;
#endif
| 27.829932 | 96 | 0.676037 | [
"object"
] |
9aa58df47aa694ab00d65074a98a924a8ef8e8ca | 10,930 | h | C | Modules/Registration/GPUPDEDeformable/include/itkGPUPDEDeformableRegistrationFilter.h | hendradarwin/ITK | 12f11d1f408680d24b6380856dd28dbe43582285 | [
"Apache-2.0"
] | null | null | null | Modules/Registration/GPUPDEDeformable/include/itkGPUPDEDeformableRegistrationFilter.h | hendradarwin/ITK | 12f11d1f408680d24b6380856dd28dbe43582285 | [
"Apache-2.0"
] | null | null | null | Modules/Registration/GPUPDEDeformable/include/itkGPUPDEDeformableRegistrationFilter.h | hendradarwin/ITK | 12f11d1f408680d24b6380856dd28dbe43582285 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkGPUPDEDeformableRegistrationFilter_h
#define itkGPUPDEDeformableRegistrationFilter_h
#include "itkGPUDenseFiniteDifferenceImageFilter.h"
#include "itkGPUPDEDeformableRegistrationFunction.h"
#include "itkPDEDeformableRegistrationFilter.h"
namespace itk
{
/**
* \class GPUPDEDeformableRegistrationFilter
* \brief Deformably register two images using a PDE algorithm.
*
* GPUPDEDeformableRegistrationFilter is a base case for filter implementing
* a PDE deformable algorithm that register two images by computing the
* deformation field which will map a moving image onto a fixed image.
*
* A deformation field is represented as a image whose pixel type is some
* vector type with at least N elements, where N is the dimension of
* the fixed image. The vector type must support element access via operator
* []. It is assumed that the vector elements behave like floating point
* scalars.
*
* This class is templated over the fixed image type, moving image type
* and the deformation Field type.
*
* The input fixed and moving images are set via methods SetFixedImage
* and SetMovingImage respectively. An initial deformation field maybe set via
* SetInitialDisplacementField or SetInput. If no initial field is set,
* a zero field is used as the initial condition.
*
* The output deformation field can be obtained via methods GetOutput
* or GetDisplacementField.
*
* The PDE algorithm is run for a user defined number of iterations.
* Typically the PDE algorithm requires period Gaussin smoothing of the
* deformation field to enforce an elastic-like condition. The amount
* of smoothing is governed by a set of user defined standard deviations
* (one for each dimension).
*
* In terms of memory, this filter keeps two internal buffers: one for storing
* the intermediate updates to the field and one for double-buffering when
* smoothing the deformation field. Both buffers are the same type and size as the
* output deformation field.
*
* This class make use of the finite difference solver hierarchy. Update
* for each iteration is computed using a PDEDeformableRegistrationFunction.
*
* \warning This filter assumes that the fixed image type, moving image type
* and deformation field type all have the same number of dimensions.
*
* \sa PDEDeformableRegistrationFunction.
* \ingroup DeformableImageRegistration
* \ingroup ITKPDEDeformableRegistration
* \ingroup ITKGPUPDEDeformableRegistration
*/
/** Create a helper GPU Kernel class for GPUPDEDeformableRegistrationFilter */
itkGPUKernelClassMacro(GPUPDEDeformableRegistrationFilterKernel);
template< typename TFixedImage, typename TMovingImage, typename TDisplacementField,
typename TParentImageFilter = PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField >
>
class GPUPDEDeformableRegistrationFilter :
public GPUDenseFiniteDifferenceImageFilter< TDisplacementField, TDisplacementField, TParentImageFilter >
{
public:
/** Standard class typedefs. */
typedef GPUPDEDeformableRegistrationFilter Self;
typedef GPUDenseFiniteDifferenceImageFilter< TDisplacementField, TDisplacementField, TParentImageFilter > GPUSuperclass;
typedef TParentImageFilter CPUSuperclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods) */
itkTypeMacro(GPUPDEDeformableRegistrationFilter,
GPUDenseFiniteDifferenceImageFilter);
/** FixedImage image type. */
typedef TFixedImage FixedImageType;
typedef typename FixedImageType::Pointer FixedImagePointer;
typedef typename FixedImageType::ConstPointer FixedImageConstPointer;
/** MovingImage image type. */
typedef TMovingImage MovingImageType;
typedef typename MovingImageType::Pointer MovingImagePointer;
typedef typename MovingImageType::ConstPointer MovingImageConstPointer;
/** Deformation field type. */
typedef TDisplacementField DisplacementFieldType;
typedef typename DisplacementFieldType::Pointer DisplacementFieldPointer;
typedef typename TDisplacementField::PixelType DeformationVectorType;
typedef typename TDisplacementField::PixelType::ValueType
DeformationScalarType;
/** Types inherithed from the GPUSuperclass */
typedef typename GPUSuperclass::OutputImageType OutputImageType;
/** FiniteDifferenceFunction type. */
typedef typename GPUSuperclass::FiniteDifferenceFunctionType
FiniteDifferenceFunctionType;
/** PDEDeformableRegistrationFilterFunction type. */
/** GPUPDEDeformableRegistrationFilterFunction type. */
typedef GPUPDEDeformableRegistrationFunction< FixedImageType, MovingImageType,
DisplacementFieldType > GPUPDEDeformableRegistrationFunctionType;
/** Inherit some enums and typedefs from the GPUSuperclass. */
itkStaticConstMacro(ImageDimension, unsigned int,
GPUSuperclass::ImageDimension);
/** Get OpenCL Kernel source as a string, creates a GetOpenCLSource method */
itkGetOpenCLSourceFromKernelMacro(GPUPDEDeformableRegistrationFilterKernel);
/** Set the fixed image. */
void SetFixedImage(const FixedImageType *ptr);
/** Get the fixed image. */
const FixedImageType * GetFixedImage() const;
/** Set the moving image. */
void SetMovingImage(const MovingImageType *ptr);
/** Get the moving image. */
const MovingImageType * GetMovingImage() const;
/** Set initial deformation field. */
void SetInitialDisplacementField(const DisplacementFieldType *ptr)
{
this->SetInput(ptr);
}
/** Get output deformation field. */
DisplacementFieldType * GetDisplacementField()
{
return this->GetOutput();
}
/** Get the number of valid inputs. For PDEDeformableRegistration,
* this checks whether the fixed and moving images have been
* set. While PDEDeformableRegistration can take a third input as an
* initial deformation field, this input is not a required input.
*/
virtual std::vector< SmartPointer< DataObject > >::size_type GetNumberOfValidRequiredInputs() const;
typedef FixedArray< double, ImageDimension > StandardDeviationsType;
protected:
GPUPDEDeformableRegistrationFilter();
~GPUPDEDeformableRegistrationFilter() {
}
void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;
/** A simple method to copy the data from the input to the output.
* If the input does not exist, a zero field is written to the output. */
virtual void CopyInputToOutput();
/** Initialize the state of filter and equation before each iteration.
* Progress feeback is implemented as part of this method. */
virtual void InitializeIteration();
/** Utility to smooth the deformation field (represented in the Output)
* using a Guassian operator. The amount of smoothing can be specified
* by setting the StandardDeviations. */
virtual void SmoothDisplacementField();
/** Smooth a vector field, which may be m_DisplacementField or
* m_UpdateBuffer. */
virtual void GPUSmoothVectorField(DisplacementFieldPointer field,
typename GPUDataManager::Pointer GPUSmoothingKernels[],
int GPUSmoothingKernelSizes[]);
virtual void AllocateSmoothingBuffer();
/** Utility to smooth the UpdateBuffer using a Gaussian operator.
* The amount of smoothing can be specified by setting the
* UpdateFieldStandardDeviations. */
virtual void SmoothUpdateField();
/** This method is called after the solution has been generated. In this case,
* the filter release the memory of the internal buffers. */
virtual void PostProcessOutput();
/** This method is called before iterating the solution. */
virtual void Initialize();
/** By default the output deformation field has the same Spacing, Origin
* and LargestPossibleRegion as the input/initial deformation field. If
* the initial deformation field is not set, the output information is
* copied from the fixed image. */
virtual void GenerateOutputInformation();
/** It is difficult to compute in advance the input moving image region
* required to compute the requested output region. Thus the safest
* thing to do is to request for the whole moving image.
*
* For the fixed image and deformation field, the input requested region
* set to be the same as that of the output requested region. */
virtual void GenerateInputRequestedRegion();
private:
GPUPDEDeformableRegistrationFilter(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
/** Temporary deformation field use for smoothing the
* the deformation field. */
DisplacementFieldPointer m_TempField;
private:
/** Memory buffer for smoothing kernels of the displacement field. */
int m_SmoothingKernelSizes[ImageDimension];
DeformationScalarType* m_SmoothingKernels[ImageDimension];
typename GPUDataManager::Pointer m_GPUSmoothingKernels[ImageDimension];
/** Memory buffer for smoothing kernels of the update field. */
int m_UpdateFieldSmoothingKernelSizes[ImageDimension];
DeformationScalarType* m_UpdateFieldSmoothingKernels[ImageDimension];
typename GPUDataManager::Pointer m_UpdateFieldGPUSmoothingKernels[ImageDimension];
int* m_ImageSizes;
typename GPUDataManager::Pointer m_GPUImageSizes;
/* GPU kernel handle for GPUSmoothDisplacementField */
int m_SmoothDisplacementFieldGPUKernelHandle;
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkGPUPDEDeformableRegistrationFilter.hxx"
#endif
#endif
| 43.031496 | 122 | 0.725618 | [
"object",
"vector"
] |
9aa97a11c8bafbc3fdfd43c0f893f3783e440ad9 | 3,784 | h | C | UnrealEngine-4.11.2-release/Engine/Source/Developer/MessageLog/Private/Presentation/MessageLogViewModel.h | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2016-10-01T21:35:52.000Z | 2016-10-01T21:35:52.000Z | UnrealEngine-4.11.2-release/Engine/Source/Developer/MessageLog/Private/Presentation/MessageLogViewModel.h | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | null | null | null | UnrealEngine-4.11.2-release/Engine/Source/Developer/MessageLog/Private/Presentation/MessageLogViewModel.h | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2021-04-27T08:48:33.000Z | 2021-04-27T08:48:33.000Z | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
/** Presentation logic for the message log */
class FMessageLogViewModel : public TSharedFromThis< FMessageLogViewModel >
{
public:
/** Broadcasts whenever we are informed of a change in the MessageLogModel */
DECLARE_EVENT( FMessageLogViewModel, FChangedEvent )
FChangedEvent& OnChanged() { return ChangedEvent; }
/** Broadcasts whenever selection state changes */
DECLARE_EVENT( FMessageLogViewModel, FOnSelectionChangedEvent )
FOnSelectionChangedEvent& OnSelectionChanged() { return SelectionChangedEvent; }
public:
/** Constructor */
FMessageLogViewModel( const TSharedPtr< class FMessageLogModel >& InMessageLogModel );
/** Destructor */
virtual ~FMessageLogViewModel();
/** Initializes the FMessageLogViewModel for use */
virtual void Initialize();
/** Called when data is changed changed/updated in the model */
virtual void Update();
/**
* Registers a log listing view model.
* It is not necessary to call this function before outputting to a log via AddMessage etc. This call simply
* registers a UI to view the log data.
*
* @param LogName The name of the log to register
* @param LogLabel The label to display for the log
* @param InitializationOptions Initialization options for this message log
*/
TSharedRef<class FMessageLogListingViewModel> RegisterLogListingViewModel( const FName& LogName, const FText& LogLabel, const struct FMessageLogInitializationOptions& InitializationOptions );
/**
* Unregisters a log listing view model.
*
* @param LogName The name of the log to unregister.
* @returns true if successful.
*/
bool UnregisterLogListingViewModel( const FName& LogName );
/**
* Checks to see if a log listing view model is already registered
*
* @param LogName The name of the log to check.
* @returns true if the log listing is already registered.
*/
bool IsRegisteredLogListingViewModel( const FName& LogName ) const;
/** Finds the LogListing ViewModel, given its name. Returns null if not found. */
TSharedPtr< class FMessageLogListingViewModel > FindLogListingViewModel( const FName& LogName ) const;
/** Gets a log listing ViewModel, if it does not exist it is created. */
TSharedRef< class FMessageLogListingViewModel > GetLogListingViewModel( const FName& LogName );
/** Changes the currently selected log listing */
void ChangeCurrentListingViewModel( const FName& LogName );
/** Gets the currently selected log listing */
TSharedPtr<class FMessageLogListingViewModel> GetCurrentListingViewModel() const;
/** Gets the currently selected log listing's name */
FName GetCurrentListingName() const;
/** Gets the currently selectd log listing's label */
FString GetCurrentListingLabel() const;
/** Get the linearized array of ViewModels */
const TArray<IMessageLogListingPtr>& GetLogListingViewModels() const { return ViewModelArray; }
private:
/** Updates the linearized array of ViewModels */
void UpdateListingViewModelArray();
private:
/* The model we are getting display info from */
TSharedPtr< class FMessageLogModel > MessageLogModel;
/** A map from a log listings' Name->ViewModel */
TMap< FName, TSharedPtr< class FMessageLogListingViewModel > > NameToViewModelMap;
/** A linearized array of the ViewModels - we need this for the data to display in a SComboBox */
TArray<IMessageLogListingPtr> ViewModelArray;
/** The currently selected log listing */
TSharedPtr< class FMessageLogListingViewModel > SelectedLogListingViewModel;
/** The event that broadcasts whenever a change occurs to the data */
FChangedEvent ChangedEvent;
/** The event that broadcasts whenever selection state is changed */
FOnSelectionChangedEvent SelectionChangedEvent;
}; | 35.698113 | 192 | 0.762949 | [
"model"
] |
9aa99b99fff0b42171cbf37e9cd70adcf81b6855 | 871 | h | C | iOSOpenDev/frameworks/WebCore.framework/Headers/AccessibilityTextMarker.h | bzxy/cydia | f8c838cdbd86e49dddf15792e7aa56e2af80548d | [
"MIT"
] | 678 | 2017-11-17T08:33:19.000Z | 2022-03-26T10:40:20.000Z | iOSOpenDev/frameworks/WebCore.framework/Headers/AccessibilityTextMarker.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 22 | 2019-04-16T05:51:53.000Z | 2021-11-08T06:18:45.000Z | iOSOpenDev/frameworks/WebCore.framework/Headers/AccessibilityTextMarker.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 170 | 2018-06-10T07:59:20.000Z | 2022-03-22T16:19:33.000Z | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/WebCore.framework/WebCore
*/
#import <WebCore/WebCore-Structs.h>
#import <WebCore/XXUnknownSuperclass.h>
__attribute__((visibility("hidden")))
@interface AccessibilityTextMarker : XXUnknownSuperclass {
@private
AXObjectCache *_cache; // 4 = 0x4
TextMarkerData _textMarkerData; // 8 = 0x8
}
+ (id)textMarkerWithVisiblePosition:(VisiblePosition *)visiblePosition cache:(AXObjectCache *)cache; // 0x27b52d
- (id)initWithTextMarker:(TextMarkerData *)textMarker cache:(AXObjectCache *)cache; // 0x27b4cd
- (id)initWithData:(id)data cache:(AXObjectCache *)cache; // 0x27b67d
- (id)initWithData:(id)data accessibilityObject:(id)object; // 0x27b639
- (id)dataRepresentation; // 0x27b5fd
- (VisiblePosition)visiblePosition; // 0x27b5d1
- (id)description; // 0x27b585
@end
| 34.84 | 112 | 0.760046 | [
"object"
] |
9aa9eaa0117e22b81156f8be7c795e866cbeacaf | 2,552 | h | C | include/pcx/pcx_mem.h | raminudelman/pcx | afa22233ed5ba3cfe01f205219e19f48c55146b7 | [
"Apache-2.0"
] | 2 | 2020-05-14T03:49:11.000Z | 2020-05-14T03:49:51.000Z | include/pcx/pcx_mem.h | raminudelman/pcx | afa22233ed5ba3cfe01f205219e19f48c55146b7 | [
"Apache-2.0"
] | null | null | null | include/pcx/pcx_mem.h | raminudelman/pcx | afa22233ed5ba3cfe01f205219e19f48c55146b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019-present, Mellanox Technologies Ltd.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
// Used for registering the UMR
#include "pcx_verbs_ctx.h"
// Used for ibv_mr, ibv_sge, etc.
#include <infiniband/verbs.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <vector>
enum PCX_MEMORY_TYPE {
PCX_MEMORY_TYPE_HOST,
PCX_MEMORY_TYPE_MEMIC,
PCX_MEMORY_TYPE_REMOTE,
PCX_MEMORY_TYPE_NIM,
PCX_MEMORY_TYPE_USER,
};
// Network Memory
class NetMem { // TODO: Change class name to "PcxMem" or "PcxBaseMem"
public:
NetMem(){};
virtual ~NetMem() = 0;
struct ibv_sge *sg() {
return &sge;
};
struct ibv_mr *getMr() {
return mr;
};
protected:
// Scatter-Gather Element
struct ibv_sge sge;
// Memory Region
struct ibv_mr *mr;
};
// Host Memory
class HostMem : public NetMem {
public:
HostMem(size_t length, VerbCtx *ctx);
~HostMem();
private:
void *buf;
};
class Memic : public NetMem {
/*
* This is ConnectX-5 device memory mapped to the host memory.
* Using this memory is about 200ns faster than using host memory.
* So it should reduce latency in around 0.2us per step.
*/
public:
Memic(size_t length, VerbCtx *ctx);
~Memic();
private:
PcxDeviceMemory pcx_dm;
};
class UsrMem : public NetMem {
public:
UsrMem(void *buf, size_t length, VerbCtx *ctx);
~UsrMem();
};
class RefMem : public NetMem {
public:
RefMem(NetMem *mem, uint64_t byte_offset, uint32_t length);
RefMem(const RefMem &srcRef);
~RefMem();
};
class UmrMem : public NetMem {
public:
UmrMem(std::vector<NetMem *> &mem_reg, VerbCtx *ctx);
~UmrMem();
};
class RemoteMem : public NetMem {
public:
RemoteMem(uint64_t addr, uint32_t rkey);
~RemoteMem();
};
class PipeMem {
public:
PipeMem(size_t length_, size_t depth_, VerbCtx *ctx,
int mem_type_ = PCX_MEMORY_TYPE_HOST);
PipeMem(size_t length_, size_t depth_, RemoteMem *remote);
PipeMem(void *buf, size_t length_, size_t depth_, VerbCtx *ctx);
~PipeMem();
RefMem operator[](size_t idx);
RefMem next();
void print();
size_t getLength() { return length; };
size_t getDepth() { return depth; };
private:
NetMem *mem;
size_t length;
size_t depth;
int mem_type;
size_t cur;
};
| 20.747967 | 72 | 0.653997 | [
"vector"
] |
9aaa95db0c6b9cc1e44a5137a3a6426f32917ac9 | 28,446 | h | C | cegui/include/CEGUI/widgets/ListHeader.h | bolry/cegui | 58b776a157409cb13092b77d68ab2618cf5c6e05 | [
"MIT"
] | 15 | 2019-05-07T11:26:13.000Z | 2022-01-12T18:26:45.000Z | cegui/include/CEGUI/widgets/ListHeader.h | bolry/cegui | 58b776a157409cb13092b77d68ab2618cf5c6e05 | [
"MIT"
] | 16 | 2021-10-04T17:15:31.000Z | 2022-03-20T09:34:29.000Z | cegui/include/CEGUI/widgets/ListHeader.h | bolry/cegui | 58b776a157409cb13092b77d68ab2618cf5c6e05 | [
"MIT"
] | 2 | 2019-04-28T23:27:48.000Z | 2019-05-07T11:26:18.000Z | /***********************************************************************
created: 13/4/2004
author: Paul D Turner
purpose: Interface to base class for ListHeader widget
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 _CEGUIListHeader_h_
#define _CEGUIListHeader_h_
#include "../Base.h"
#include "../Window.h"
#include "./ListHeaderSegment.h"
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
/*!
\brief
EventArgs class used for segment move (sequence changed) events.
*/
class CEGUIEXPORT HeaderSequenceEventArgs : public WindowEventArgs
{
public:
HeaderSequenceEventArgs(Window* wnd, unsigned int old_idx, unsigned int new_idx) : WindowEventArgs(wnd), d_oldIdx(old_idx), d_newIdx(new_idx) {}
unsigned int d_oldIdx; //!< The original column index of the segment that has moved.
unsigned int d_newIdx; //!< The new column index of the segment that has moved.
};
/*!
\brief
Base class for the multi column list header window renderer.
*/
class CEGUIEXPORT ListHeaderWindowRenderer : public WindowRenderer
{
public:
/*!
\brief
Constructor
*/
ListHeaderWindowRenderer(const String& name);
/*!
\brief
Create and return a pointer to a new ListHeaderSegment based object.
\param name
String object holding the name that should be given to the new Window.
\return
Pointer to an ListHeaderSegment based object of whatever type is appropriate for
this ListHeader.
*/
virtual ListHeaderSegment* createNewSegment(const String& name) const = 0;
/*!
\brief
Cleanup and destroy the given ListHeaderSegment that was created via the
createNewSegment method.
\param segment
Pointer to a ListHeaderSegment based object to be destroyed.
\return
Nothing.
*/
virtual void destroyListSegment(ListHeaderSegment* segment) const = 0;
};
/*!
\brief
Base class for the multi column list header widget.
*/
class CEGUIEXPORT ListHeader : public Window
{
public:
static const String EventNamespace; //!< Namespace for global events
static const String WidgetTypeName; //!< Window factory name
/*************************************************************************
Constants
*************************************************************************/
// Event names
/** Event fired when the current sort column of the header is changed.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader whose sort column has
* been changed.
*/
static const String EventSortColumnChanged;
/** Event fired when the sort direction of the header is changed.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader whose sort direction had
* been changed.
*/
static const String EventSortDirectionChanged;
/** Event fired when a segment of the header is sized by the user.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeaderSegment that has been sized.
*/
static const String EventSegmentSized;
/** Event fired when a segment of the header is clicked by the user.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeaderSegment that was clicked.
*/
static const String EventSegmentClicked;
/** Event fired when a segment splitter of the header is double-clicked.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeaderSegment whose splitter area
* was double-clicked.
*/
static const String EventSplitterDoubleClicked;
/** Event fired when the order of the segments in the header has changed.
* Handlers are passed a const HeaderSequenceEventArgs reference with
* WindowEventArgs::window set to the ListHeader whose segments have changed
* sequence, HeaderSequenceEventArgs::d_oldIdx is the original index of the
* segment that has moved, and HeaderSequenceEventArgs::d_newIdx is the new
* index of the segment that has moved.
*/
static const String EventSegmentSequenceChanged;
/** Event fired when a segment is added to the header.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader that has had a new segment
* added.
*/
static const String EventSegmentAdded;
/** Event fired when a segment is removed from the header.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader that has had a segment
* removed.
*/
static const String EventSegmentRemoved;
/** Event fired when setting that controls user modification to sort
* configuration is changed.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader whose user sort control
* setting has been changed.
*/
static const String EventSortSettingChanged;
/** Event fired when setting that controls user drag & drop of segments is
* changed.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader whose drag & drop enabled
* setting has changed.
*/
static const String EventDragMoveSettingChanged;
/** Event fired when setting that controls user sizing of segments is
* changed.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader whose user sizing setting
* has changed.
*/
static const String EventDragSizeSettingChanged;
/** Event fired when the rendering offset for the segments changes.
* Handlers are passed a const WindowEventArgs reference with
* WindowEventArgs::window set to the ListHeader whose segment rendering
* offset has changed.
*/
static const String EventSegmentRenderOffsetChanged;
// values
static const float ScrollSpeed; //!< Speed to scroll at when dragging outside header.
static const float MinimumSegmentPixelWidth; //!< Miniumum width of a segment in pixels.
/*************************************************************************
Child Widget name suffix constants
*************************************************************************/
//! Widget name suffix for header segments.
static const String SegmentNameSuffix;
/*************************************************************************
Accessor Methods
*************************************************************************/
/*!
\brief
Return the number of columns or segments attached to the header.
\return
unsigned int value equal to the number of columns / segments currently in the header.
*/
unsigned int getColumnCount(void) const;
/*!
\brief
Return the ListHeaderSegment object for the specified column
\param column
zero based column index of the ListHeaderSegment to be returned.
\return
ListHeaderSegment object at the requested index.
\exception InvalidRequestException thrown if column is out of range.
*/
ListHeaderSegment& getSegmentFromColumn(unsigned int column) const;
/*!
\brief
Return the ListHeaderSegment object with the specified ID.
\param id
id code of the ListHeaderSegment to be returned.
\return
ListHeaderSegment object with the ID \a id. If more than one segment has the same ID, only the first one will
ever be returned.
\exception InvalidRequestException thrown if no segment with the requested ID is attached.
*/
ListHeaderSegment& getSegmentFromID(unsigned int id) const;
/*!
\brief
Return the ListHeaderSegment that is marked as being the 'sort key' segment. There must be at least one segment
to successfully call this method.
\return
ListHeaderSegment object which is the sort-key segment.
\exception InvalidRequestException thrown if no segments are attached to the ListHeader.
*/
ListHeaderSegment& getSortSegment(void) const;
/*!
\brief
Return the ListHeaderSegment ID that is marked as being the 'sort key' segment. There should be at least one segment.
\return
unsigned int which is the sort-key segment ID.
*/
unsigned int getSortSegmentID(void) const;
/*!
\brief
Return the zero based column index of the specified segment.
\param segment
ListHeaderSegment whos zero based index is to be returned.
\return
Zero based column index of the ListHeaderSegment \a segment.
\exception InvalidRequestException thrown if \a segment is not attached to this ListHeader.
*/
unsigned int getColumnFromSegment(const ListHeaderSegment& segment) const;
/*!
\brief
Return the zero based column index of the segment with the specified ID.
\param id
ID code of the segment whos column index is to be returned.
\return
Zero based column index of the first ListHeaderSegment whos ID matches \a id.
\exception InvalidRequestException thrown if no attached segment has the requested ID.
*/
unsigned int getColumnFromID(unsigned int id) const;
/*!
\brief
Return the zero based index of the current sort column. There must be at least one segment/column to successfully call this
method.
\return
Zero based column index that is the current sort column.
\exception InvalidRequestException thrown if there are no segments / columns in this ListHeader.
*/
unsigned int getSortColumn(void) const;
/*!
\brief
Return the zero based column index of the segment with the specified text.
\param text
String object containing the text to be searched for.
\return
Zero based column index of the segment with the specified text.
\exception InvalidRequestException thrown if no attached segments have the requested text.
*/
unsigned int getColumnWithText(const String& text) const;
/*!
\brief
Return the pixel offset to the given ListHeaderSegment.
\param segment
ListHeaderSegment object that the offset to is to be returned.
\return
The number of pixels up-to the beginning of the ListHeaderSegment described by \a segment.
\exception InvalidRequestException thrown if \a segment is not attached to the ListHeader.
*/
float getPixelOffsetToSegment(const ListHeaderSegment& segment) const;
/*!
\brief
Return the pixel offset to the ListHeaderSegment at the given zero based column index.
\param column
Zero based column index of the ListHeaderSegment whos pixel offset it to be returned.
\return
The number of pixels up-to the beginning of the ListHeaderSegment located at zero based column
index \a column.
\exception InvalidRequestException thrown if \a column is out of range.
*/
float getPixelOffsetToColumn(unsigned int column) const;
/*!
\brief
Return the total pixel width of all attached segments.
\return
Sum of the pixel widths of all attached ListHeaderSegment objects.
*/
float getTotalSegmentsPixelExtent(void) const;
/*!
\brief
Return the width of the specified column.
\param column
Zero based column index of the segment whose width is to be returned.
\return
UDim describing the width of the ListHeaderSegment at the zero based
column index specified by \a column.
\exception InvalidRequestException thrown if \a column is out of range.
*/
UDim getColumnWidth(unsigned int column) const;
/*!
\brief
Return the currently set sort direction.
\return
One of the ListHeaderSegment::SortDirection enumerated values specifying the current sort direction.
*/
ListHeaderSegment::SortDirection getSortDirection(void) const;
/*!
\brief
Return whether user manipulation of the sort column & direction are enabled.
\return
true if the user may interactively modify the sort column and direction. false if the user may not
modify the sort column and direction (these can still be set programmatically).
*/
bool isSortingEnabled(void) const;
/*!
\brief
Return whether the user may size column segments.
\return
true if the user may interactively modify the width of column segments, false if they may not.
*/
bool isColumnSizingEnabled(void) const;
/*!
\brief
Return whether the user may modify the order of the segments.
\return
true if the user may interactively modify the order of the column segments, false if they may not.
*/
bool isColumnDraggingEnabled(void) const;
/*!
\brief
Return the current segment offset value. This value is used to implement scrolling of the header segments within
the ListHeader area.
\return
float value specifying the current segment offset value in whatever metrics system is active for the ListHeader.
*/
float getSegmentOffset(void) const {return d_segmentOffset;}
/*************************************************************************
Manipulator Methods
*************************************************************************/
/*!
\brief
Set whether user manipulation of the sort column and direction is enabled.
\param setting
- true to allow interactive user manipulation of the sort column and direction.
- false to disallow interactive user manipulation of the sort column and direction.
\return
Nothing.
*/
void setSortingEnabled(bool setting);
/*!
\brief
Set the current sort direction.
\param direction
One of the ListHeaderSegment::SortDirection enumerated values indicating the sort direction to be used.
\return
Nothing.
*/
void setSortDirection(ListHeaderSegment::SortDirection direction);
/*!
\brief
Set the column segment to be used as the sort column.
\param segment
ListHeaderSegment object indicating the column to be sorted.
\return
Nothing.
\exception InvalidRequestException thrown if \a segment is not attached to this ListHeader.
*/
void setSortSegment(const ListHeaderSegment& segment);
/*!
\brief
Set the column to be used as the sort column.
\param column
Zero based column index indicating the column to be sorted.
\return
Nothing.
\exception InvalidRequestException thrown if \a column is out of range for this ListHeader.
*/
void setSortColumn(unsigned int column);
/*!
\brief
Set the column to to be used for sorting via its ID code.
\param id
ID code of the column segment that is to be used as the sort column.
\return
Nothing.
\exception InvalidRequestException thrown if no segment with ID \a id is attached to the ListHeader.
*/
void setSortColumnFromID(unsigned int id);
/*!
\brief
Set whether columns may be sized by the user.
\param setting
- true to indicate that the user may interactively size segments.
- false to indicate that the user may not interactively size segments.
\return
Nothing.
*/
void setColumnSizingEnabled(bool setting);
/*!
\brief
Set whether columns may be reordered by the user via drag and drop.
\param setting
- true to indicate the user may change the order of the column segments via drag and drop.
- false to indicate the user may not change the column segment order.
\return
Nothing.
*/
void setColumnDraggingEnabled(bool setting);
/*!
\brief
Add a new column segment to the end of the header.
\param text
String object holding the initial text for the new segment
\param id
Client specified ID code to be assigned to the new segment.
\param width
UDim describing the initial width of the new segment.
\return
Nothing.
*/
void addColumn(const String& text, unsigned int id, const UDim& width);
/*!
\brief
Insert a new column segment at the specified position.
\param text
String object holding the initial text for the new segment
\param id
Client specified ID code to be assigned to the new segment.
\param width
UDim describing the initial width of the new segment.
\param position
Zero based column index indicating the desired position for the new column. If this is greater than
the current number of columns, the new segment is added to the end if the header.
\return
Nothing.
*/
void insertColumn(const String& text, unsigned int id, const UDim& width, unsigned int position);
/*!
\brief
Insert a new column segment at the specified position.
\param text
String object holding the initial text for the new segment
\param id
Client specified ID code to be assigned to the new segment.
\param width
UDim describing the initial width of the new segment.
\param position
ListHeaderSegment object indicating the insert position for the new segment. The new segment will be
inserted before the segment indicated by \a position.
\return
Nothing.
\exception InvalidRequestException thrown if ListHeaderSegment \a position is not attached to the ListHeader.
*/
void insertColumn(const String& text, unsigned int id, const UDim& width, const ListHeaderSegment& position);
/*!
\brief
Removes a column segment from the ListHeader.
\param column
Zero based column index indicating the segment to be removed.
\return
Nothing.
\exception InvalidRequestException thrown if \a column is out of range.
*/
void removeColumn(unsigned int column);
/*!
\brief
Remove the specified segment from the ListHeader.
\param segment
ListHeaderSegment object that is to be removed from the ListHeader.
\return
Nothing.
\exception InvalidRequestException thrown if \a segment is not attached to this ListHeader.
*/
void removeSegment(const ListHeaderSegment& segment);
/*!
\brief
Moves a column segment into a new position.
\param column
Zero based column index indicating the column segment to be moved.
\param position
Zero based column index indicating the new position for the segment. If this is greater than the current number of segments,
the segment is moved to the end of the header.
\return
Nothing.
\exception InvalidRequestException thrown if \a column is out of range for this ListHeader.
*/
void moveColumn(unsigned int column, unsigned int position);
/*!
\brief
Move a column segment to a new position.
\param column
Zero based column index indicating the column segment to be moved.
\param position
ListHeaderSegment object indicating the new position for the segment. The segment at \a column
will be moved behind segment \a position (that is, segment \a column will appear to the right of
segment \a position).
\return
Nothing.
\exception InvalidRequestException thrown if \a column is out of range for this ListHeader, or if \a position
is not attached to this ListHeader.
*/
void moveColumn(unsigned int column, const ListHeaderSegment& position);
/*!
\brief
Moves a segment into a new position.
\param segment
ListHeaderSegment object that is to be moved.
\param position
Zero based column index indicating the new position for the segment. If this is greater than the current number of segments,
the segment is moved to the end of the header.
\return
Nothing.
\exception InvalidRequestException thrown if \a segment is not attached to this ListHeader.
*/
void moveSegment(const ListHeaderSegment& segment, unsigned int position);
/*!
\brief
Move a segment to a new position.
\param segment
ListHeaderSegment object that is to be moved.
\param position
ListHeaderSegment object indicating the new position for the segment. The segment \a segment
will be moved behind segment \a position (that is, segment \a segment will appear to the right of
segment \a position).
\return
Nothing.
\exception InvalidRequestException thrown if either \a segment or \a position are not attached to this ListHeader.
*/
void moveSegment(const ListHeaderSegment& segment, const ListHeaderSegment& position);
/*!
\brief
Set the current base segment offset. (This implements scrolling of the header segments within
the header area).
\param offset
New base offset for the first segment. The segments will of offset to the left by the amount specified.
\a offset should be specified using the active metrics system for the ListHeader.
\return
Nothing.
*/
void setSegmentOffset(float offset);
/*!
\brief
Set the width of the specified column.
\param column
Zero based column index of the segment whose width is to be set.
\param width
UDim value specifying the new width to set for the ListHeaderSegment at the zero based column
index specified by \a column.
\return
Nothing
\exception InvalidRequestException thrown if \a column is out of range.
*/
void setColumnWidth(unsigned int column, const UDim& width);
/*************************************************************************
Construction and Destruction
*************************************************************************/
/*!
\brief
Constructor for the list header base class.
*/
ListHeader(const String& type, const String& name);
/*!
\brief
Destructor for the list header base class.
*/
virtual ~ListHeader(void);
protected:
/*************************************************************************
Abstract Implementation Methods
*************************************************************************/
/*!
\brief
Create and return a pointer to a new ListHeaderSegment based object.
\param name
String object holding the name that should be given to the new Window.
\return
Pointer to an ListHeaderSegment based object of whatever type is appropriate for
this ListHeader.
*/
//virtual ListHeaderSegment* createNewSegment_impl(const String& name) const = 0;
/*!
\brief
Cleanup and destroy the given ListHeaderSegment that was created via the
createNewSegment method.
\param segment
Pointer to a ListHeaderSegment based object to be destroyed.
\return
Nothing.
*/
//virtual void destroyListSegment_impl(ListHeaderSegment* segment) const = 0;
/*************************************************************************
Implementation Methods
*************************************************************************/
/*!
\brief
Create initialise and return a ListHeaderSegment object, with all events subscribed and ready to use.
*/
ListHeaderSegment* createInitialisedSegment(const String& text, unsigned int id, const UDim& width);
/*!
\brief
Layout the attached segments
*/
void layoutSegments(void);
/*!
\brief
Create and return a pointer to a new ListHeaderSegment based object.
\param name
String object holding the name that should be given to the new Window.
\return
Pointer to an ListHeaderSegment based object of whatever type is appropriate for
this ListHeader.
*/
ListHeaderSegment* createNewSegment(const String& name) const;
/*!
\brief
Cleanup and destroy the given ListHeaderSegment that was created via the
createNewSegment method.
\param segment
Pointer to a ListHeaderSegment based object to be destroyed.
\return
Nothing.
*/
void destroyListSegment(ListHeaderSegment* segment) const;
// validate window renderer
bool validateWindowRenderer(const WindowRenderer* renderer) const override;
/*************************************************************************
New List header event handlers
*************************************************************************/
/*!
\brief
Handler called when the sort column is changed.
*/
virtual void onSortColumnChanged(WindowEventArgs& e);
/*!
\brief
Handler called when the sort direction is changed.
*/
virtual void onSortDirectionChanged(WindowEventArgs& e);
/*!
\brief
Handler called when a segment is sized by the user. e.window points to the segment.
*/
virtual void onSegmentSized(WindowEventArgs& e);
/*!
\brief
Handler called when a segment is clicked by the user. e.window points to the segment.
*/
virtual void onSegmentClicked(WindowEventArgs& e);
/*!
\brief
Handler called when a segment splitter / sizer is double-clicked. e.window points to the segment.
*/
virtual void onSplitterDoubleClicked(WindowEventArgs& e);
/*!
\brief
Handler called when the segment / column order changes.
*/
virtual void onSegmentSequenceChanged(WindowEventArgs& e);
/*!
\brief
Handler called when a new segment is added to the header.
*/
virtual void onSegmentAdded(WindowEventArgs& e);
/*!
\brief
Handler called when a segment is removed from the header.
*/
virtual void onSegmentRemoved(WindowEventArgs& e);
/*!
\brief
Handler called then setting that controls the users ability to modify the search column & direction changes.
*/
virtual void onSortSettingChanged(WindowEventArgs& e);
/*!
\brief
Handler called when the setting that controls the users ability to drag and drop segments changes.
*/
virtual void onDragMoveSettingChanged(WindowEventArgs& e);
/*!
\brief
Handler called when the setting that controls the users ability to size segments changes.
*/
virtual void onDragSizeSettingChanged(WindowEventArgs& e);
/*!
\brief
Handler called when the base rendering offset for the segments (scroll position) changes.
*/
virtual void onSegmentOffsetChanged(WindowEventArgs& e);
/*************************************************************************
handlers for events we subscribe to from segments
*************************************************************************/
bool segmentSizedHandler(const EventArgs& e);
bool segmentMovedHandler(const EventArgs& e);
bool segmentClickedHandler(const EventArgs& e);
bool segmentDoubleClickHandler(const EventArgs& e);
bool segmentDragHandler(const EventArgs& e);
/*************************************************************************
Implementation Data
*************************************************************************/
typedef std::vector<ListHeaderSegment*> SegmentList;
SegmentList d_segments; //!< Attached segment windows in header order.
ListHeaderSegment* d_sortSegment; //!< Pointer to the segment that is currently set as the sork-key,
bool d_sizingEnabled; //!< true if segments can be sized by the user.
bool d_sortingEnabled; //!< true if the sort criteria modifications by user are enabled (no sorting is actuall done)
bool d_movingEnabled; //!< true if drag & drop moving of columns / segments is enabled.
unsigned int d_uniqueIDNumber; //!< field used to create unique names.
float d_segmentOffset; //!< Base offset used to layout the segments (allows scrolling within the window area)
ListHeaderSegment::SortDirection d_sortDir; //!< Brief copy of the current sort direction.
private:
/*************************************************************************
Private methods
*************************************************************************/
void addHeaderProperties(void);
};
} // End of CEGUI namespace section
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // end of guard _CEGUIListHeader_h_
| 29.386364 | 145 | 0.694368 | [
"object",
"vector"
] |
9aaeaec7be41d98fc9f380f2a44d5903b87a519f | 9,733 | h | C | chrome/browser/sync/internal_api/base_node.h | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | chrome/browser/sync/internal_api/base_node.h | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | chrome/browser/sync/internal_api/base_node.h | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SYNC_INTERNAL_API_BASE_NODE_H_
#define CHROME_BROWSER_SYNC_INTERNAL_API_BASE_NODE_H_
#pragma once
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h"
#include "googleurl/src/gurl.h"
#include "sync/protocol/sync.pb.h"
#include "sync/syncable/model_type.h"
// Forward declarations of internal class types so that sync API objects
// may have opaque pointers to these types.
namespace base {
class DictionaryValue;
}
namespace syncable {
class BaseTransaction;
class Entry;
}
namespace sync_pb {
class AppSpecifics;
class AutofillSpecifics;
class AutofillProfileSpecifics;
class BookmarkSpecifics;
class EntitySpecifics;
class ExtensionSpecifics;
class SessionSpecifics;
class NigoriSpecifics;
class PreferenceSpecifics;
class PasswordSpecificsData;
class ThemeSpecifics;
class TypedUrlSpecifics;
}
namespace sync_api {
class BaseTransaction;
// A valid BaseNode will never have an ID of zero.
static const int64 kInvalidId = 0;
// BaseNode wraps syncable::Entry, and corresponds to a single object's state.
// This, like syncable::Entry, is intended for use on the stack. A valid
// transaction is necessary to create a BaseNode or any of its children.
// Unlike syncable::Entry, a sync API BaseNode is identified primarily by its
// int64 metahandle, which we call an ID here.
class BaseNode {
public:
// All subclasses of BaseNode must provide a way to initialize themselves by
// doing an ID lookup. Returns false on failure. An invalid or deleted
// ID will result in failure.
virtual bool InitByIdLookup(int64 id) = 0;
// All subclasses of BaseNode must also provide a way to initialize themselves
// by doing a client tag lookup. Returns false on failure. A deleted node
// will return FALSE.
virtual bool InitByClientTagLookup(syncable::ModelType model_type,
const std::string& tag) = 0;
// Each object is identified by a 64-bit id (internally, the syncable
// metahandle). These ids are strictly local handles. They will persist
// on this client, but the same object on a different client may have a
// different ID value.
virtual int64 GetId() const;
// Returns the modification time of the object.
const base::Time& GetModificationTime() const;
// Nodes are hierarchically arranged into a single-rooted tree.
// InitByRootLookup on ReadNode allows access to the root. GetParentId is
// how you find a node's parent.
int64 GetParentId() const;
// Nodes are either folders or not. This corresponds to the IS_DIR property
// of syncable::Entry.
bool GetIsFolder() const;
// Returns the title of the object.
// Uniqueness of the title is not enforced on siblings -- it is not an error
// for two children to share a title.
std::string GetTitle() const;
// Returns the model type of this object. The model type is set at node
// creation time and is expected never to change.
syncable::ModelType GetModelType() const;
// Getter specific to the BOOKMARK datatype. Returns protobuf
// data. Can only be called if GetModelType() == BOOKMARK.
const sync_pb::BookmarkSpecifics& GetBookmarkSpecifics() const;
// Legacy, bookmark-specific getter that wraps GetBookmarkSpecifics() above.
// Returns the URL of a bookmark object.
// TODO(ncarter): Remove this datatype-specific accessor.
GURL GetURL() const;
// Legacy, bookmark-specific getter that wraps GetBookmarkSpecifics() above.
// Fill in a vector with the byte data of this node's favicon. Assumes
// that the node is a bookmark.
// Favicons are expected to be PNG images, and though no verification is
// done on the syncapi client of this, the server may reject favicon updates
// that are invalid for whatever reason.
// TODO(ncarter): Remove this datatype-specific accessor.
void GetFaviconBytes(std::vector<unsigned char>* output) const;
// Getter specific to the APPS datatype. Returns protobuf
// data. Can only be called if GetModelType() == APPS.
const sync_pb::AppSpecifics& GetAppSpecifics() const;
// Getter specific to the AUTOFILL datatype. Returns protobuf
// data. Can only be called if GetModelType() == AUTOFILL.
const sync_pb::AutofillSpecifics& GetAutofillSpecifics() const;
virtual const sync_pb::AutofillProfileSpecifics&
GetAutofillProfileSpecifics() const;
// Getter specific to the NIGORI datatype. Returns protobuf
// data. Can only be called if GetModelType() == NIGORI.
const sync_pb::NigoriSpecifics& GetNigoriSpecifics() const;
// Getter specific to the PASSWORD datatype. Returns protobuf
// data. Can only be called if GetModelType() == PASSWORD.
const sync_pb::PasswordSpecificsData& GetPasswordSpecifics() const;
// Getter specific to the PREFERENCE datatype. Returns protobuf
// data. Can only be called if GetModelType() == PREFERENCE.
const sync_pb::PreferenceSpecifics& GetPreferenceSpecifics() const;
// Getter specific to the THEME datatype. Returns protobuf
// data. Can only be called if GetModelType() == THEME.
const sync_pb::ThemeSpecifics& GetThemeSpecifics() const;
// Getter specific to the TYPED_URLS datatype. Returns protobuf
// data. Can only be called if GetModelType() == TYPED_URLS.
const sync_pb::TypedUrlSpecifics& GetTypedUrlSpecifics() const;
// Getter specific to the EXTENSIONS datatype. Returns protobuf
// data. Can only be called if GetModelType() == EXTENSIONS.
const sync_pb::ExtensionSpecifics& GetExtensionSpecifics() const;
// Getter specific to the SESSIONS datatype. Returns protobuf
// data. Can only be called if GetModelType() == SESSIONS.
const sync_pb::SessionSpecifics& GetSessionSpecifics() const;
const sync_pb::EntitySpecifics& GetEntitySpecifics() const;
// Returns the local external ID associated with the node.
int64 GetExternalId() const;
// Returns true iff this node has children.
bool HasChildren() const;
// Return the ID of the node immediately before this in the sibling order.
// For the first node in the ordering, return 0.
int64 GetPredecessorId() const;
// Return the ID of the node immediately after this in the sibling order.
// For the last node in the ordering, return 0.
int64 GetSuccessorId() const;
// Return the ID of the first child of this node. If this node has no
// children, return 0.
int64 GetFirstChildId() const;
// These virtual accessors provide access to data members of derived classes.
virtual const syncable::Entry* GetEntry() const = 0;
virtual const BaseTransaction* GetTransaction() const = 0;
// Dumps a summary of node info into a DictionaryValue and returns it.
// Transfers ownership of the DictionaryValue to the caller.
base::DictionaryValue* GetSummaryAsValue() const;
// Dumps all node details into a DictionaryValue and returns it.
// Transfers ownership of the DictionaryValue to the caller.
base::DictionaryValue* GetDetailsAsValue() const;
protected:
BaseNode();
virtual ~BaseNode();
// The server has a size limit on client tags, so we generate a fixed length
// hash locally. This also ensures that ModelTypes have unique namespaces.
static std::string GenerateSyncableHash(syncable::ModelType model_type,
const std::string& client_tag);
// Determines whether part of the entry is encrypted, and if so attempts to
// decrypt it. Unless decryption is necessary and fails, this will always
// return |true|. If the contents are encrypted, the decrypted data will be
// stored in |unencrypted_data_|.
// This method is invoked once when the BaseNode is initialized.
bool DecryptIfNecessary();
// Returns the unencrypted specifics associated with |entry|. If |entry| was
// not encrypted, it directly returns |entry|'s EntitySpecifics. Otherwise,
// returns |unencrypted_data_|.
const sync_pb::EntitySpecifics& GetUnencryptedSpecifics(
const syncable::Entry* entry) const;
// Copy |specifics| into |unencrypted_data_|.
void SetUnencryptedSpecifics(const sync_pb::EntitySpecifics& specifics);
private:
// Have to friend the test class as well to allow member functions to access
// protected/private BaseNode methods.
friend class SyncManagerTest;
FRIEND_TEST_ALL_PREFIXES(SyncApiTest, GenerateSyncableHash);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, UpdateEntryWithEncryption);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest,
UpdatePasswordSetEntitySpecificsNoChange);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, UpdatePasswordSetPasswordSpecifics);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, UpdatePasswordNewPassphrase);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, UpdatePasswordReencryptEverything);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, SetBookmarkTitle);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, SetBookmarkTitleWithEncryption);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, SetNonBookmarkTitle);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, SetNonBookmarkTitleWithEncryption);
FRIEND_TEST_ALL_PREFIXES(SyncManagerTest, SetPreviouslyEncryptedSpecifics);
void* operator new(size_t size); // Node is meant for stack use only.
// A holder for the unencrypted data stored in an encrypted node.
sync_pb::EntitySpecifics unencrypted_data_;
// Same as |unencrypted_data_|, but for legacy password encryption.
scoped_ptr<sync_pb::PasswordSpecificsData> password_data_;
DISALLOW_COPY_AND_ASSIGN(BaseNode);
};
} // namespace sync_api
#endif // CHROME_BROWSER_SYNC_INTERNAL_API_BASE_NODE_H_
| 40.385892 | 80 | 0.762663 | [
"object",
"vector",
"model"
] |
9ab1dd71a57c4ceafdc54cb578cb39cb6b72c339 | 81,244 | c | C | usr/src/cmd/sgs/libld/common/map_core.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/sgs/libld/common/map_core.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/sgs/libld/common/map_core.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1988 AT&T
* All Rights Reserved
*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
*
* Copyright 2019 Joyent, Inc.
*/
/*
* Map file parsing (Shared Core Code).
*/
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <dirent.h>
#include <ctype.h>
#include <debug.h>
#include "msg.h"
#include "_libld.h"
#include "_map.h"
/*
* There are two styles of mapfile supported by the link-editor:
*
* 1) The original System V defined syntax, as augmented at Sun
* from Solaris 2.0 through Solaris 10. This style is also known
* as version 1.
*
* 2) A newer syntax, currently at version 2.
*
* The original syntax uses special characters (=, :, -, |, etc) as
* operators to indicate the operation being specified. Over the years,
* this syntax has been problematic:
*
* 1) Too cryptic: It's hard for people to remember which character
* means what.
*
* 2) Limited expansion potential: There only a few special characters
* available on the keyboard for new features, and it is difficult to
* add options to existing ones.
*
* Adding new features into this framework (2) have the effect of
* making the syntax even more cryptic (1). The newer syntax addresses
* these issues by moving to an extendible identifier based syntax that
* allows new features to be added without complicating old ones.
*
* The new syntax uses the following terminology:
*
* - Control directives are the directives that start with a '$'.
* They control how the mapfile is interpreted. We use the 'cdir_'
* prefix on functions and variables related to these directives.
*
* - Conditional Expressions are the expressions found in $if and $elif
* control directives. They evaluate to boolean true/false values.
* We use the 'cexp_' prefix for functions and variables related to
* these expressions.
*
* - Regular Directives are names (SYMBOL, VERSION, etc) that convey
* directions to the link-editor for building the output object.
*
* This file contains core code used by both mapfile styles: File management,
* lexical analysis, and other shared core functionality. It also contains
* the code for control directives, as they are intrinsically part of
* lexical analysis --- this is disabled when processing Sysv mapfiles.
*/
/*
* We use a stack of cdir_level_t structs to manage $if/$elif/$else/$endif
* processing. At each level, we keep track of the information needed to
* determine whether or not to process nested input lines or skip them,
* along with information needed to report errors.
*/
typedef struct {
Lineno cdl_if_lineno; /* Line number of opening $if */
Lineno cdl_else_lineno; /* 0, or line on which $else seen */
int cdl_done; /* True if no longer accepts input */
int cdl_pass; /* True if currently accepting input */
} cdir_level_t;
/* Operators in the expressions accepted by $if/$elif */
typedef enum {
CEXP_OP_NONE, /* Not an operator */
CEXP_OP_AND, /* && */
CEXP_OP_OR, /* || */
CEXP_OP_NEG, /* ! */
CEXP_OP_OPAR, /* ( */
CEXP_OP_CPAR /* ) */
} cexp_op_t;
/*
* Type of conditional expression identifier AVL tree nodes
*/
typedef struct cexp_name_node {
avl_node_t ceid_avlnode; /* AVL book-keeping */
const char *ceid_name; /* boolean identifier name */
} cexp_id_node_t;
/*
* Declare a "stack" type, containing a pointer to data, a count of
* allocated, and currently used items in the stack. The data type
* is specified as the _type argument.
*/
#define STACK(_type) \
struct { \
_type *stk_s; /* Stack array */ \
size_t stk_n; /* Current stack depth */ \
size_t stk_n_alloc; /* # of elements pointed at by s */ \
}
/*
* The following type represents a "generic" stack, where the data
* type is (void). This type is never instantiated. However, it has
* the same struct layout as any other STACK(), and is therefore a good
* generic type that can be used for stack_resize().
*/
typedef STACK(void) generic_stack_t;
/*
* Ensure that the stack has enough room to push one more item
*/
#define STACK_RESERVE(_stack, _n_default) \
(((_stack).stk_n < (_stack).stk_n_alloc) || \
stack_resize((generic_stack_t *)&(_stack).stk_s, _n_default, \
sizeof (*(_stack).stk_s)))
/*
* Reset a stack to empty.
*/
#define STACK_RESET(_stack) (_stack).stk_n = 0;
/*
* True if stack is empty, False otherwise.
*/
#define STACK_IS_EMPTY(_stack) ((_stack).stk_n == 0)
/*
* Push a value onto a stack. Caller must ensure that stack has room.
* This macro is intended to be used as the LHS of an assignment, the
* RHS of which is the value:
*
* STACK_PUSH(stack) = value;
*/
#define STACK_PUSH(_stack) (_stack).stk_s[(_stack).stk_n++]
/*
* Pop a value off a stack. Caller must ensure
* that stack is not empty.
*/
#define STACK_POP(_stack) ((_stack).stk_s[--(_stack).stk_n])
/*
* Access top element on stack without popping. Caller must ensure
* that stack is not empty.
*/
#define STACK_TOP(_stack) (((_stack).stk_s)[(_stack).stk_n - 1])
/*
* Initial sizes used for the stacks: The stacks are allocated on demand
* to these sizes, and then doubled as necessary until they are large enough.
*
* The ideal size would be large enough that only a single allocation
* occurs, and our defaults should generally have that effect. However,
* in doing so, we run the risk of a latent error in the resize code going
* undetected until triggered by a large task in the field. For this reason,
* we set the sizes to the smallest size possible when compiled for debug.
*/
#ifdef DEBUG
#define CDIR_STACK_INIT 1
#define CEXP_OP_STACK_INIT 1
#define CEXP_VAL_STACK_INIT 1
#else
#define CDIR_STACK_INIT 16
#define CEXP_OP_STACK_INIT 8
#define CEXP_VAL_STACK_INIT (CEXP_OP_STACK_INIT * 2) /* 2 vals per binop */
#endif
/*
* Persistent state maintained by map module in between calls.
*
* This is kept as static file scope data, because it is only used
* when libld is called by ld, and not by rtld. If that should change,
* the code is designed so that it can become reentrant easily:
*
* - Add a pointer to the output descriptor to a structure of this type,
* allocated dynamically on the first call to ld_map_parse().
* - Change all references to lms to instead reference the pointer in
* the output descriptor.
*
* Until then, it is simpler not to expose these details.
*/
typedef struct {
int lms_cdir_valid; /* Allow control dir. on entry to gettoken() */
STACK(cdir_level_t) lms_cdir_stack; /* Conditional input level */
STACK(cexp_op_t) lms_cexp_op_stack; /* Cond. expr operators */
STACK(uchar_t) lms_cexp_val_stack; /* Cond. expr values */
avl_tree_t *lms_cexp_id;
} ld_map_state_t;
static ld_map_state_t lms;
/*
* Version 1 (SysV) syntax dispatch table for ld_map_gettoken(). For each
* of the 7-bit ASCII characters, determine how the lexical analyzer
* should behave.
*
* This table must be kept in sync with tkid_attr[] below.
*
* Identifier Note:
* The Linker and Libraries Guide states that the original syntax uses
* C identifier rules, allowing '.' to be treated as a letter. However,
* the implementation is considerably looser than that: Any character
* with an ASCII code (0-127) which is printable and not used to start
* another token is allowed to start an identifier, and they are terminated
* by any of: space, double quote, tab, newline, ':', ';', '=', or '#'.
* The original code has been replaced, but this table encodes the same
* rules, to ensure backward compatibility.
*/
static const mf_tokdisp_t gettok_dispatch_v1 = {
TK_OP_EOF, /* 0 - NUL */
TK_OP_ILLCHR, /* 1 - SOH */
TK_OP_ILLCHR, /* 2 - STX */
TK_OP_ILLCHR, /* 3 - ETX */
TK_OP_ILLCHR, /* 4 - EOT */
TK_OP_ILLCHR, /* 5 - ENQ */
TK_OP_ILLCHR, /* 6 - ACK */
TK_OP_ILLCHR, /* 7 - BEL */
TK_OP_ILLCHR, /* 8 - BS */
TK_OP_WS, /* 9 - HT */
TK_OP_NL, /* 10 - NL */
TK_OP_WS, /* 11 - VT */
TK_OP_WS, /* 12 - FF */
TK_OP_WS, /* 13 - CR */
TK_OP_ILLCHR, /* 14 - SO */
TK_OP_ILLCHR, /* 15 - SI */
TK_OP_ILLCHR, /* 16 - DLE */
TK_OP_ILLCHR, /* 17 - DC1 */
TK_OP_ILLCHR, /* 18 - DC2 */
TK_OP_ILLCHR, /* 19 - DC3 */
TK_OP_ILLCHR, /* 20 - DC4 */
TK_OP_ILLCHR, /* 21 - NAK */
TK_OP_ILLCHR, /* 22 - SYN */
TK_OP_ILLCHR, /* 23 - ETB */
TK_OP_ILLCHR, /* 24 - CAN */
TK_OP_ILLCHR, /* 25 - EM */
TK_OP_ILLCHR, /* 26 - SUB */
TK_OP_ILLCHR, /* 27 - ESC */
TK_OP_ILLCHR, /* 28 - FS */
TK_OP_ILLCHR, /* 29 - GS */
TK_OP_ILLCHR, /* 30 - RS */
TK_OP_ILLCHR, /* 31 - US */
TK_OP_WS, /* 32 - SP */
TK_OP_ID, /* 33 - ! */
TK_OP_SIMQUOTE, /* 34 - " */
TK_OP_CMT, /* 35 - # */
TK_OP_ID, /* 36 - $ */
TK_OP_ID, /* 37 - % */
TK_OP_ID, /* 38 - & */
TK_OP_ID, /* 39 - ' */
TK_OP_ID, /* 40 - ( */
TK_OP_ID, /* 41 - ) */
TK_OP_ID, /* 42 - * */
TK_OP_ID, /* 43 - + */
TK_OP_ID, /* 44 - , */
TK_DASH, /* 45 - - */
TK_OP_ID, /* 46 - . */
TK_OP_ID, /* 47 - / */
TK_OP_ID, /* 48 - 0 */
TK_OP_ID, /* 49 - 1 */
TK_OP_ID, /* 50 - 2 */
TK_OP_ID, /* 51 - 3 */
TK_OP_ID, /* 52 - 4 */
TK_OP_ID, /* 53 - 5 */
TK_OP_ID, /* 54 - 6 */
TK_OP_ID, /* 55 - 7 */
TK_OP_ID, /* 56 - 8 */
TK_OP_ID, /* 57 - 9 */
TK_COLON, /* 58 - : */
TK_SEMICOLON, /* 59 - ; */
TK_OP_ID, /* 60 - < */
TK_EQUAL, /* 61 - = */
TK_OP_ID, /* 62 - > */
TK_OP_ID, /* 63 - ? */
TK_ATSIGN, /* 64 - @ */
TK_OP_ID, /* 65 - A */
TK_OP_ID, /* 66 - B */
TK_OP_ID, /* 67 - C */
TK_OP_ID, /* 68 - D */
TK_OP_ID, /* 69 - E */
TK_OP_ID, /* 70 - F */
TK_OP_ID, /* 71 - G */
TK_OP_ID, /* 72 - H */
TK_OP_ID, /* 73 - I */
TK_OP_ID, /* 74 - J */
TK_OP_ID, /* 75 - K */
TK_OP_ID, /* 76 - L */
TK_OP_ID, /* 77 - M */
TK_OP_ID, /* 78 - N */
TK_OP_ID, /* 79 - O */
TK_OP_ID, /* 80 - P */
TK_OP_ID, /* 81 - Q */
TK_OP_ID, /* 82 - R */
TK_OP_ID, /* 83 - S */
TK_OP_ID, /* 84 - T */
TK_OP_ID, /* 85 - U */
TK_OP_ID, /* 86 - V */
TK_OP_ID, /* 87 - W */
TK_OP_ID, /* 88 - X */
TK_OP_ID, /* 89 - Y */
TK_OP_ID, /* 90 - Z */
TK_OP_ID, /* 91 - [ */
TK_OP_ID, /* 92 - \ */
TK_OP_ID, /* 93 - ] */
TK_OP_ID, /* 94 - ^ */
TK_OP_ID, /* 95 - _ */
TK_OP_ID, /* 96 - ` */
TK_OP_ID, /* 97 - a */
TK_OP_ID, /* 98 - b */
TK_OP_ID, /* 99 - c */
TK_OP_ID, /* 100 - d */
TK_OP_ID, /* 101 - e */
TK_OP_ID, /* 102 - f */
TK_OP_ID, /* 103 - g */
TK_OP_ID, /* 104 - h */
TK_OP_ID, /* 105 - i */
TK_OP_ID, /* 106 - j */
TK_OP_ID, /* 107 - k */
TK_OP_ID, /* 108 - l */
TK_OP_ID, /* 109 - m */
TK_OP_ID, /* 110 - n */
TK_OP_ID, /* 111 - o */
TK_OP_ID, /* 112 - p */
TK_OP_ID, /* 113 - q */
TK_OP_ID, /* 114 - r */
TK_OP_ID, /* 115 - s */
TK_OP_ID, /* 116 - t */
TK_OP_ID, /* 117 - u */
TK_OP_ID, /* 118 - v */
TK_OP_ID, /* 119 - w */
TK_OP_ID, /* 120 - x */
TK_OP_ID, /* 121 - y */
TK_OP_ID, /* 122 - z */
TK_LEFTBKT, /* 123 - { */
TK_PIPE, /* 124 - | */
TK_RIGHTBKT, /* 125 - } */
TK_OP_ID, /* 126 - ~ */
TK_OP_ILLCHR, /* 127 - DEL */
};
/*
* Version 2 syntax dispatch table for ld_map_gettoken(). For each of the
* 7-bit ASCII characters, determine how the lexical analyzer should behave.
*
* This table must be kept in sync with tkid_attr[] below.
*
* Identifier Note:
* We define a letter as being one of the character [A-Z], [a-z], or [_%/.]
* A digit is the numbers [0-9], or [$-]. An unquoted identifier is defined
* as a letter, followed by any number of letters or digits. This is a loosened
* version of the C definition of an identifier. The extra characters not
* allowed by C are common in section names and/or file paths.
*/
static const mf_tokdisp_t gettok_dispatch_v2 = {
TK_OP_EOF, /* 0 - NUL */
TK_OP_ILLCHR, /* 1 - SOH */
TK_OP_ILLCHR, /* 2 - STX */
TK_OP_ILLCHR, /* 3 - ETX */
TK_OP_ILLCHR, /* 4 - EOT */
TK_OP_ILLCHR, /* 5 - ENQ */
TK_OP_ILLCHR, /* 6 - ACK */
TK_OP_ILLCHR, /* 7 - BEL */
TK_OP_ILLCHR, /* 8 - BS */
TK_OP_WS, /* 9 - HT */
TK_OP_NL, /* 10 - NL */
TK_OP_WS, /* 11 - VT */
TK_OP_WS, /* 12 - FF */
TK_OP_WS, /* 13 - CR */
TK_OP_ILLCHR, /* 14 - SO */
TK_OP_ILLCHR, /* 15 - SI */
TK_OP_ILLCHR, /* 16 - DLE */
TK_OP_ILLCHR, /* 17 - DC1 */
TK_OP_ILLCHR, /* 18 - DC2 */
TK_OP_ILLCHR, /* 19 - DC3 */
TK_OP_ILLCHR, /* 20 - DC4 */
TK_OP_ILLCHR, /* 21 - NAK */
TK_OP_ILLCHR, /* 22 - SYN */
TK_OP_ILLCHR, /* 23 - ETB */
TK_OP_ILLCHR, /* 24 - CAN */
TK_OP_ILLCHR, /* 25 - EM */
TK_OP_ILLCHR, /* 26 - SUB */
TK_OP_ILLCHR, /* 27 - ESC */
TK_OP_ILLCHR, /* 28 - FS */
TK_OP_ILLCHR, /* 29 - GS */
TK_OP_ILLCHR, /* 30 - RS */
TK_OP_ILLCHR, /* 31 - US */
TK_OP_WS, /* 32 - SP */
TK_BANG, /* 33 - ! */
TK_OP_CQUOTE, /* 34 - " */
TK_OP_CMT, /* 35 - # */
TK_OP_CDIR, /* 36 - $ */
TK_OP_ID, /* 37 - % */
TK_OP_BADCHR, /* 38 - & */
TK_OP_SIMQUOTE, /* 39 - ' */
TK_OP_BADCHR, /* 40 - ( */
TK_OP_BADCHR, /* 41 - ) */
TK_STAR, /* 42 - * */
TK_OP_CEQUAL, /* 43 - + */
TK_OP_BADCHR, /* 44 - , */
TK_OP_CEQUAL, /* 45 - - */
TK_OP_ID, /* 46 - . */
TK_OP_ID, /* 47 - / */
TK_OP_NUM, /* 48 - 0 */
TK_OP_NUM, /* 49 - 1 */
TK_OP_NUM, /* 50 - 2 */
TK_OP_NUM, /* 51 - 3 */
TK_OP_NUM, /* 52 - 4 */
TK_OP_NUM, /* 53 - 5 */
TK_OP_NUM, /* 54 - 6 */
TK_OP_NUM, /* 55 - 7 */
TK_OP_NUM, /* 56 - 8 */
TK_OP_NUM, /* 57 - 9 */
TK_COLON, /* 58 - : */
TK_SEMICOLON, /* 59 - ; */
TK_OP_BADCHR, /* 60 - < */
TK_EQUAL, /* 61 - = */
TK_OP_BADCHR, /* 62 - > */
TK_OP_BADCHR, /* 63 - ? */
TK_OP_BADCHR, /* 64 - @ */
TK_OP_ID, /* 65 - A */
TK_OP_ID, /* 66 - B */
TK_OP_ID, /* 67 - C */
TK_OP_ID, /* 68 - D */
TK_OP_ID, /* 69 - E */
TK_OP_ID, /* 70 - F */
TK_OP_ID, /* 71 - G */
TK_OP_ID, /* 72 - H */
TK_OP_ID, /* 73 - I */
TK_OP_ID, /* 74 - J */
TK_OP_ID, /* 75 - K */
TK_OP_ID, /* 76 - L */
TK_OP_ID, /* 77 - M */
TK_OP_ID, /* 78 - N */
TK_OP_ID, /* 79 - O */
TK_OP_ID, /* 80 - P */
TK_OP_ID, /* 81 - Q */
TK_OP_ID, /* 82 - R */
TK_OP_ID, /* 83 - S */
TK_OP_ID, /* 84 - T */
TK_OP_ID, /* 85 - U */
TK_OP_ID, /* 86 - V */
TK_OP_ID, /* 87 - W */
TK_OP_ID, /* 88 - X */
TK_OP_ID, /* 89 - Y */
TK_OP_ID, /* 90 - Z */
TK_OP_BADCHR, /* 91 - [ */
TK_OP_BADCHR, /* 92 - \ */
TK_OP_BADCHR, /* 93 - ] */
TK_OP_BADCHR, /* 94 - ^ */
TK_OP_ID, /* 95 - _ */
TK_OP_BADCHR, /* 96 - ` */
TK_OP_ID, /* 97 - a */
TK_OP_ID, /* 98 - b */
TK_OP_ID, /* 99 - c */
TK_OP_ID, /* 100 - d */
TK_OP_ID, /* 101 - e */
TK_OP_ID, /* 102 - f */
TK_OP_ID, /* 103 - g */
TK_OP_ID, /* 104 - h */
TK_OP_ID, /* 105 - i */
TK_OP_ID, /* 106 - j */
TK_OP_ID, /* 107 - k */
TK_OP_ID, /* 108 - l */
TK_OP_ID, /* 109 - m */
TK_OP_ID, /* 110 - n */
TK_OP_ID, /* 111 - o */
TK_OP_ID, /* 112 - p */
TK_OP_ID, /* 113 - q */
TK_OP_ID, /* 114 - r */
TK_OP_ID, /* 115 - s */
TK_OP_ID, /* 116 - t */
TK_OP_ID, /* 117 - u */
TK_OP_ID, /* 118 - v */
TK_OP_ID, /* 119 - w */
TK_OP_ID, /* 120 - x */
TK_OP_ID, /* 121 - y */
TK_OP_ID, /* 122 - z */
TK_LEFTBKT, /* 123 - { */
TK_OP_BADCHR, /* 124 - | */
TK_RIGHTBKT, /* 125 - } */
TK_OP_BADCHR, /* 126 - ~ */
TK_OP_ILLCHR, /* 127 - DEL */
};
/*
* Table used to identify unquoted identifiers. Each element of this array
* contains a bitmask indicating whether the character it represents starts,
* or continues an identifier, for each supported mapfile syntax version.
*/
static const char tkid_attr[128] = {
0, /* 0 - NUL */
TKID_ATTR_CONT(1), /* 1 - SOH */
TKID_ATTR_CONT(1), /* 2 - STX */
TKID_ATTR_CONT(1), /* 3 - ETX */
TKID_ATTR_CONT(1), /* 4 - EOT */
TKID_ATTR_CONT(1), /* 5 - ENQ */
TKID_ATTR_CONT(1), /* 6 - ACK */
TKID_ATTR_CONT(1), /* 7 - BEL */
TKID_ATTR_CONT(1), /* 8 - BS */
0, /* 9 - HT */
0, /* 10 - NL */
TKID_ATTR_CONT(1), /* 11 - VT */
TKID_ATTR_CONT(1), /* 12 - FF */
TKID_ATTR_CONT(1), /* 13 - CR */
TKID_ATTR_CONT(1), /* 14 - SO */
TKID_ATTR_CONT(1), /* 15 - SI */
TKID_ATTR_CONT(1), /* 16 - DLE */
TKID_ATTR_CONT(1), /* 17 - DC1 */
TKID_ATTR_CONT(1), /* 18 - DC2 */
TKID_ATTR_CONT(1), /* 19 - DC3 */
TKID_ATTR_CONT(1), /* 20 - DC4 */
TKID_ATTR_CONT(1), /* 21 - NAK */
TKID_ATTR_CONT(1), /* 22 - SYN */
TKID_ATTR_CONT(1), /* 23 - ETB */
TKID_ATTR_CONT(1), /* 24 - CAN */
TKID_ATTR_CONT(1), /* 25 - EM */
TKID_ATTR_CONT(1), /* 26 - SUB */
TKID_ATTR_CONT(1), /* 27 - ESC */
TKID_ATTR_CONT(1), /* 28 - FS */
TKID_ATTR_CONT(1), /* 29 - GS */
TKID_ATTR_CONT(1), /* 30 - RS */
TKID_ATTR_CONT(1), /* 31 - US */
0, /* 32 - SP */
TKID_ATTR(1), /* 33 - ! */
0, /* 34 - " */
0, /* 35 - # */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 36 - $ */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 37 - % */
TKID_ATTR(1), /* 38 - & */
TKID_ATTR(1), /* 39 - ' */
TKID_ATTR(1), /* 40 - ( */
TKID_ATTR(1), /* 41 - ) */
TKID_ATTR(1), /* 42 - * */
TKID_ATTR(1), /* 43 - + */
TKID_ATTR(1), /* 44 - , */
TKID_ATTR_CONT(1) | TKID_ATTR_CONT(2), /* 45 - - */
TKID_ATTR(1) | TKID_ATTR(2), /* 46 - . */
TKID_ATTR(1) | TKID_ATTR(2), /* 47 - / */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 48 - 0 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 49 - 1 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 50 - 2 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 51 - 3 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 52 - 4 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 53 - 5 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 54 - 6 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 55 - 7 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 56 - 8 */
TKID_ATTR(1) | TKID_ATTR_CONT(2), /* 57 - 9 */
0, /* 58 - : */
0, /* 59 - ; */
TKID_ATTR(1), /* 60 - < */
0, /* 61 - = */
TKID_ATTR(1), /* 62 - > */
TKID_ATTR(1), /* 63 - ? */
TKID_ATTR_CONT(1), /* 64 - @ */
TKID_ATTR(1) | TKID_ATTR(2), /* 65 - A */
TKID_ATTR(1) | TKID_ATTR(2), /* 66 - B */
TKID_ATTR(1) | TKID_ATTR(2), /* 67 - C */
TKID_ATTR(1) | TKID_ATTR(2), /* 68 - D */
TKID_ATTR(1) | TKID_ATTR(2), /* 69 - E */
TKID_ATTR(1) | TKID_ATTR(2), /* 70 - F */
TKID_ATTR(1) | TKID_ATTR(2), /* 71 - G */
TKID_ATTR(1) | TKID_ATTR(2), /* 72 - H */
TKID_ATTR(1) | TKID_ATTR(2), /* 73 - I */
TKID_ATTR(1) | TKID_ATTR(2), /* 74 - J */
TKID_ATTR(1) | TKID_ATTR(2), /* 75 - K */
TKID_ATTR(1) | TKID_ATTR(2), /* 76 - L */
TKID_ATTR(1) | TKID_ATTR(2), /* 77 - M */
TKID_ATTR(1) | TKID_ATTR(2), /* 78 - N */
TKID_ATTR(1) | TKID_ATTR(2), /* 79 - O */
TKID_ATTR(1) | TKID_ATTR(2), /* 80 - P */
TKID_ATTR(1) | TKID_ATTR(2), /* 81 - Q */
TKID_ATTR(1) | TKID_ATTR(2), /* 82 - R */
TKID_ATTR(1) | TKID_ATTR(2), /* 83 - S */
TKID_ATTR(1) | TKID_ATTR(2), /* 84 - T */
TKID_ATTR(1) | TKID_ATTR(2), /* 85 - U */
TKID_ATTR(1) | TKID_ATTR(2), /* 86 - V */
TKID_ATTR(1) | TKID_ATTR(2), /* 87 - W */
TKID_ATTR(1) | TKID_ATTR(2), /* 88 - X */
TKID_ATTR(1) | TKID_ATTR(2), /* 89 - Y */
TKID_ATTR(1) | TKID_ATTR(2), /* 90 - Z */
TKID_ATTR(1), /* 91 - [ */
TKID_ATTR(1), /* 92 - \ */
TKID_ATTR(1), /* 93 - ] */
TKID_ATTR(1), /* 94 - ^ */
TKID_ATTR(1) | TKID_ATTR(2), /* 95 - _ */
TKID_ATTR(1), /* 96 - ` */
TKID_ATTR(1) | TKID_ATTR(2), /* 97 - a */
TKID_ATTR(1) | TKID_ATTR(2), /* 98 - b */
TKID_ATTR(1) | TKID_ATTR(2), /* 99 - c */
TKID_ATTR(1) | TKID_ATTR(2), /* 100 - d */
TKID_ATTR(1) | TKID_ATTR(2), /* 101 - e */
TKID_ATTR(1) | TKID_ATTR(2), /* 102 - f */
TKID_ATTR(1) | TKID_ATTR(2), /* 103 - g */
TKID_ATTR(1) | TKID_ATTR(2), /* 104 - h */
TKID_ATTR(1) | TKID_ATTR(2), /* 105 - i */
TKID_ATTR(1) | TKID_ATTR(2), /* 106 - j */
TKID_ATTR(1) | TKID_ATTR(2), /* 107 - k */
TKID_ATTR(1) | TKID_ATTR(2), /* 108 - l */
TKID_ATTR(1) | TKID_ATTR(2), /* 109 - m */
TKID_ATTR(1) | TKID_ATTR(2), /* 110 - n */
TKID_ATTR(1) | TKID_ATTR(2), /* 111 - o */
TKID_ATTR(1) | TKID_ATTR(2), /* 112 - p */
TKID_ATTR(1) | TKID_ATTR(2), /* 113 - q */
TKID_ATTR(1) | TKID_ATTR(2), /* 114 - r */
TKID_ATTR(1) | TKID_ATTR(2), /* 115 - s */
TKID_ATTR(1) | TKID_ATTR(2), /* 116 - t */
TKID_ATTR(1) | TKID_ATTR(2), /* 117 - u */
TKID_ATTR(1) | TKID_ATTR(2), /* 118 - v */
TKID_ATTR(1) | TKID_ATTR(2), /* 119 - w */
TKID_ATTR(1) | TKID_ATTR(2), /* 120 - x */
TKID_ATTR(1) | TKID_ATTR(2), /* 121 - y */
TKID_ATTR(1) | TKID_ATTR(2), /* 122 - z */
TKID_ATTR_CONT(1), /* 123 - { */
TKID_ATTR_CONT(1), /* 124 - | */
TKID_ATTR_CONT(1), /* 125 - } */
TKID_ATTR(1), /* 126 - ~ */
TKID_ATTR_CONT(1), /* 127 - DEL */
};
/*
* Advance the given string pointer to the next newline character,
* or the terminating NULL if there is none.
*/
inline static void
advance_to_eol(char **str)
{
char *s = *str;
while ((*s != '\n') && (*s != '\0'))
s++;
*str = s;
}
/*
* Insert a NULL patch at the given address
*/
inline static void
null_patch_set(char *str, ld_map_npatch_t *np)
{
np->np_ptr = str;
np->np_ch = *str;
*str = '\0';
}
/*
* Undo a NULL patch
*/
inline static void
null_patch_undo(ld_map_npatch_t *np)
{
*np->np_ptr = np->np_ch;
}
/*
* Insert a NULL patch at the end of the line containing str.
*/
static void
null_patch_eol(char *str, ld_map_npatch_t *np)
{
advance_to_eol(&str);
null_patch_set(str, np);
}
/*
* Locate the end of an unquoted identifier.
*
* entry:
* mf - Mapfile descriptor, positioned to first character
* of identifier.
*
* exit:
* If the item pointed at by mf is not an identifier, returns NULL.
* Otherwise, returns pointer to character after the last character
* of the identifier.
*/
inline static char *
ident_delimit(Mapfile *mf)
{
char *str = mf->mf_next;
ld_map_npatch_t np;
int c = *str++;
/* If not a valid start character, report the error */
if ((c & 0x80) || !(tkid_attr[c] & mf->mf_tkid_start)) {
null_patch_set(str, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_BADCHAR), str);
null_patch_undo(&np);
return (NULL);
}
/* Keep going until we hit a non-continuing character */
for (c = *str; !(c & 0x80) && (tkid_attr[c] & mf->mf_tkid_cont);
c = *++str)
;
return (str);
}
/*
* Allocate memory for a stack.
*
* entry:
* stack - Pointer to stack for which memory is required, cast
* to the generic stack type.
* n_default - Size to use for initial allocation.
* elt_size - sizeof(elt), where elt is the actual stack data type.
*
* exit:
* Returns (1) on success. On error (memory allocation), a message
* is printed and False (0) is returned.
*
* note:
* The caller casts the pointer to their actual datatype-specific stack
* to be a (generic_stack_t *). The C language will give all stack
* structs the same size and layout as long as the underlying platform
* uses a single integral type for pointers. Hence, this cast is safe,
* and lets a generic routine modify data-specific types without being
* aware of those types.
*/
static Boolean
stack_resize(generic_stack_t *stack, size_t n_default, size_t elt_size)
{
size_t new_n_alloc;
void *newaddr;
/* Use initial size first, and double the allocation on each call */
new_n_alloc = (stack->stk_n_alloc == 0) ?
n_default : (stack->stk_n_alloc * 2);
newaddr = libld_realloc(stack->stk_s, new_n_alloc * elt_size);
if (newaddr == NULL)
return (FALSE);
stack->stk_s = newaddr;
stack->stk_n_alloc = new_n_alloc;
return (TRUE);
}
/*
* AVL comparison function for cexp_id_node_t items.
*
* entry:
* n1, n2 - pointers to nodes to be compared
*
* exit:
* Returns -1 if (n1 < n2), 0 if they are equal, and 1 if (n1 > n2)
*/
static int
cexp_ident_cmp(const void *n1, const void *n2)
{
int rc;
rc = strcmp(((cexp_id_node_t *)n1)->ceid_name,
((cexp_id_node_t *)n2)->ceid_name);
if (rc > 0)
return (1);
if (rc < 0)
return (-1);
return (0);
}
/*
* Returns True (1) if name is in the conditional expression identifier
* AVL tree, and False (0) otherwise.
*/
static int
cexp_ident_test(const char *name)
{
cexp_id_node_t node;
node.ceid_name = name;
return (avl_find(lms.lms_cexp_id, &node, 0) != NULL);
}
/*
* Add a new boolean identifier to the conditional expression identifier
* AVL tree.
*
* entry:
* mf - If non-NULL, the mapfile descriptor for the mapfile
* containing the $add directive. NULL if this is an
* initialization call.
* name - Name of identifier. Must point at stable storage that will
* not be moved or modified by the caller following this call.
*
* exit:
* On success, True (1) is returned and name has been entered.
* On failure, False (0) is returned and an error has been printed.
*/
static int
cexp_ident_add(Mapfile *mf, const char *name)
{
cexp_id_node_t *node;
if (mf != NULL) {
DBG_CALL(Dbg_map_cexp_id(mf->mf_ofl->ofl_lml, 1,
mf->mf_name, mf->mf_lineno, name));
/* If is already known, don't do it again */
if (cexp_ident_test(name))
return (1);
}
if ((node = libld_calloc(sizeof (*node), 1)) == NULL)
return (0);
node->ceid_name = name;
avl_add(lms.lms_cexp_id, node);
return (1);
}
/*
* Remove a boolean identifier from the conditional expression identifier
* AVL tree.
*
* entry:
* mf - Mapfile descriptor
* name - Name of identifier.
*
* exit:
* If the name was in the tree, it has been removed. If not,
* then this routine quietly returns.
*/
static void
cexp_ident_clear(Mapfile *mf, const char *name)
{
cexp_id_node_t node;
cexp_id_node_t *real_node;
DBG_CALL(Dbg_map_cexp_id(mf->mf_ofl->ofl_lml, 0,
mf->mf_name, mf->mf_lineno, name));
node.ceid_name = name;
real_node = avl_find(lms.lms_cexp_id, &node, 0);
if (real_node != NULL)
avl_remove(lms.lms_cexp_id, real_node);
}
/*
* Initialize the AVL tree that holds the names of the currently defined
* boolean identifiers for conditional expressions ($if/$elif).
*
* entry:
* ofl - Output file descriptor
*
* exit:
* On success, TRUE (1) is returned and lms.lms_cexp_id is ready for use.
* On failure, FALSE (0) is returned.
*/
static Boolean
cexp_ident_init(void)
{
/* If already done, use it */
if (lms.lms_cexp_id != NULL)
return (TRUE);
lms.lms_cexp_id = libld_calloc(sizeof (*lms.lms_cexp_id), 1);
if (lms.lms_cexp_id == NULL)
return (FALSE);
avl_create(lms.lms_cexp_id, cexp_ident_cmp, sizeof (cexp_id_node_t),
SGSOFFSETOF(cexp_id_node_t, ceid_avlnode));
/* ELFCLASS */
if (cexp_ident_add(NULL, (ld_targ.t_m.m_class == ELFCLASS32) ?
MSG_ORIG(MSG_STR_UELF32) : MSG_ORIG(MSG_STR_UELF64)) == 0)
return (FALSE);
/* Machine */
switch (ld_targ.t_m.m_mach) {
case EM_386:
case EM_AMD64:
if (cexp_ident_add(NULL, MSG_ORIG(MSG_STR_UX86)) == 0)
return (FALSE);
break;
case EM_SPARC:
case EM_SPARCV9:
if (cexp_ident_add(NULL, MSG_ORIG(MSG_STR_USPARC)) == 0)
return (FALSE);
break;
}
/* true is always defined */
if (cexp_ident_add(NULL, MSG_ORIG(MSG_STR_TRUE)) == 0)
return (FALSE);
return (TRUE);
}
/*
* Validate the string starting at mf->mf_next as being a
* boolean conditional expression identifier.
*
* entry:
* mf - Mapfile descriptor
* len - NULL, or address of variable to receive strlen() of identifier
* directive - If (len == NULL), string giving name of directive being
* processed. Ignored if (len != NULL).
*
* exit:
* On success:
* - If len is NULL, a NULL is inserted following the final
* character of the identifier, and the remainder of the string
* is tested to ensure it is empty, or only contains whitespace.
* - If len is non-NULL, *len is set to the number of characters
* in the identifier, and the rest of the string is not modified.
* - TRUE (1) is returned
*
* On failure, returns FALSE (0).
*/
static Boolean
cexp_ident_validate(Mapfile *mf, size_t *len, const char *directive)
{
char *tail;
if ((tail = ident_delimit(mf)) == NULL)
return (FALSE);
/*
* If len is non-NULL, we simple count the number of characters
* consumed by the identifier and are done. If len is NULL, then
* ensure there's nothing left but whitespace, and NULL terminate
* the identifier to remove it.
*/
if (len != NULL) {
*len = tail - mf->mf_next;
} else if (*tail != '\0') {
*tail++ = '\0';
while (isspace(*tail))
tail++;
if (*tail != '\0') {
mf_fatal(mf, MSG_INTL(MSG_MAP_BADEXTRA), directive);
return (FALSE);
}
}
return (TRUE);
}
/*
* Push a new operator onto the conditional expression operator stack.
*
* entry:
* mf - Mapfile descriptor
* op - Operator to push
*
* exit:
* On success, TRUE (1) is returned, otherwise FALSE (0).
*/
static Boolean
cexp_push_op(cexp_op_t op)
{
if (STACK_RESERVE(lms.lms_cexp_op_stack, CEXP_OP_STACK_INIT) == 0)
return (FALSE);
STACK_PUSH(lms.lms_cexp_op_stack) = op;
return (TRUE);
}
/*
* Evaluate the basic operator (non-paren) at the top of lms.lms_cexp_op_stack,
* and push the results on lms.lms_cexp_val_stack.
*
* exit:
* On success, returns TRUE (1). On error, FALSE (0) is returned,
* and the caller is responsible for issuing the error.
*/
static Boolean
cexp_eval_op(void)
{
cexp_op_t op;
uchar_t val;
op = STACK_POP(lms.lms_cexp_op_stack);
switch (op) {
case CEXP_OP_AND:
if (lms.lms_cexp_val_stack.stk_n < 2)
return (FALSE);
val = STACK_POP(lms.lms_cexp_val_stack);
STACK_TOP(lms.lms_cexp_val_stack) = val &&
STACK_TOP(lms.lms_cexp_val_stack);
break;
case CEXP_OP_OR:
if (lms.lms_cexp_val_stack.stk_n < 2)
return (FALSE);
val = STACK_POP(lms.lms_cexp_val_stack);
STACK_TOP(lms.lms_cexp_val_stack) = val ||
STACK_TOP(lms.lms_cexp_val_stack);
break;
case CEXP_OP_NEG:
if (lms.lms_cexp_val_stack.stk_n < 1)
return (FALSE);
STACK_TOP(lms.lms_cexp_val_stack) =
!STACK_TOP(lms.lms_cexp_val_stack);
break;
default:
return (FALSE);
}
return (TRUE);
}
/*
* Evaluate an expression for a $if/$elif control directive.
*
* entry:
* mf - Mapfile descriptor for NULL terminated string
* containing the expression.
*
* exit:
* The contents of str are modified by this routine.
* One of the following values are returned:
* -1 Syntax error encountered (an error is printed)
* 0 The expression evaluates to False
* 1 The expression evaluates to True.
*
* note:
* A simplified version of Dijkstra's Shunting Yard algorithm is used
* to convert this syntax into postfix form and then evaluate it.
* Our version has no functions and a tiny set of operators.
*
* The expressions consist of boolean identifiers, which can be
* combined using the following operators, listed from highest
* precedence to least:
*
* Operator Meaning
* -------------------------------------------------
* (expr) sub-expression, non-associative
* ! logical negation, prefix, left associative
* && || logical and/or, binary, left associative
*
* The operands manipulated by these operators are names, consisting of
* a sequence of letters and digits. The first character must be a letter.
* Underscore (_) and period (.) are also considered to be characters.
* An operand is considered True if it is found in our set of known
* names (lms.lms_cexp_id), and False otherwise.
*
* The Shunting Yard algorithm works using two stacks, one for operators,
* and a second for operands. The infix input expression is tokenized from
* left to right and processed in order. Issues of associativity and
* precedence are managed by reducing (poping and evaluating) items with
* higer precedence before pushing additional tokens with lower precedence.
*/
static int
cexp_eval_expr(Mapfile *mf)
{
char *ident;
size_t len;
cexp_op_t new_op = CEXP_OP_AND; /* to catch binop at start */
ld_map_npatch_t np;
char *str = mf->mf_next;
STACK_RESET(lms.lms_cexp_op_stack);
STACK_RESET(lms.lms_cexp_val_stack);
for (; *str; str++) {
/* Skip whitespace */
while (isspace(*str))
str++;
if (!*str)
break;
switch (*str) {
case '&':
case '|':
if (*(str + 1) != *str)
goto token_error;
if ((new_op != CEXP_OP_NONE) &&
(new_op != CEXP_OP_CPAR)) {
mf_fatal0(mf, MSG_INTL(MSG_MAP_CEXP_BADOPUSE));
return (-1);
}
str++;
/*
* As this is a left associative binary operator, we
* need to process all operators of equal or higher
* precedence before pushing the new operator.
*/
while (!STACK_IS_EMPTY(lms.lms_cexp_op_stack)) {
cexp_op_t op = STACK_TOP(lms.lms_cexp_op_stack);
if ((op != CEXP_OP_AND) && (op != CEXP_OP_OR) &&
(op != CEXP_OP_NEG))
break;
if (!cexp_eval_op())
goto semantic_error;
}
new_op = (*str == '&') ? CEXP_OP_AND : CEXP_OP_OR;
if (!cexp_push_op(new_op))
return (-1);
break;
case '!':
new_op = CEXP_OP_NEG;
if (!cexp_push_op(new_op))
return (-1);
break;
case '(':
new_op = CEXP_OP_OPAR;
if (!cexp_push_op(new_op))
return (-1);
break;
case ')':
new_op = CEXP_OP_CPAR;
/* Evaluate the operator stack until reach '(' */
while (!STACK_IS_EMPTY(lms.lms_cexp_op_stack) &&
(STACK_TOP(lms.lms_cexp_op_stack) != CEXP_OP_OPAR))
if (!cexp_eval_op())
goto semantic_error;
/*
* If the top of operator stack is not an open paren,
* when we have an error. In this case, the operator
* stack will be empty due to the loop above.
*/
if (STACK_IS_EMPTY(lms.lms_cexp_op_stack))
goto unbalpar_error;
lms.lms_cexp_op_stack.stk_n--; /* Pop OPAR */
break;
default:
/* Ensure there's room to push another operand */
if (STACK_RESERVE(lms.lms_cexp_val_stack,
CEXP_VAL_STACK_INIT) == 0)
return (0);
new_op = CEXP_OP_NONE;
/*
* Operands cannot be numbers. However, we accept two
* special cases: '0' means false, and '1' is true.
* This is done to support the common C idiom of
* '#if 1' and '#if 0' to conditionalize code under
* development.
*/
if ((*str == '0') || (*str == '1')) {
STACK_PUSH(lms.lms_cexp_val_stack) =
(*str == '1');
break;
}
/* Look up the identifier */
ident = mf->mf_next = str;
if (!cexp_ident_validate(mf, &len, NULL))
return (-1);
str += len - 1; /* loop will advance past final ch */
null_patch_set(&ident[len], &np);
STACK_PUSH(lms.lms_cexp_val_stack) =
cexp_ident_test(ident);
null_patch_undo(&np);
break;
}
}
/* Evaluate the operator stack until empty */
while (!STACK_IS_EMPTY(lms.lms_cexp_op_stack)) {
if (STACK_TOP(lms.lms_cexp_op_stack) == CEXP_OP_OPAR)
goto unbalpar_error;
if (!cexp_eval_op())
goto semantic_error;
}
/* There should be exactly one value left */
if (lms.lms_cexp_val_stack.stk_n != 1)
goto semantic_error;
/* Final value is the result */
return (lms.lms_cexp_val_stack.stk_s[0]);
/* Errors issued more than once are handled below, accessed via goto */
token_error: /* unexpected characters in input stream */
mf_fatal(mf, MSG_INTL(MSG_MAP_CEXP_TOKERR), str);
return (-1);
semantic_error: /* valid tokens, but in invalid arrangement */
mf_fatal0(mf, MSG_INTL(MSG_MAP_CEXP_SEMERR));
return (-1);
unbalpar_error: /* Extra or missing parenthesis */
mf_fatal0(mf, MSG_INTL(MSG_MAP_CEXP_UNBALPAR));
return (-1);
}
/*
* Process a mapfile control directive. These directives start with
* the dollar character, and are used to manage details of the mapfile
* itself, such as version and conditional input.
*
* entry:
* mf - Mapfile descriptor
*
* exit:
* Returns TRUE (1) for success, and FALSE (0) on error. In the
* error case, a descriptive error is issued.
*/
static Boolean
cdir_process(Mapfile *mf)
{
typedef enum { /* Directive types */
CDIR_T_UNKNOWN = 0, /* Unrecognized control directive */
CDIR_T_ADD, /* $add */
CDIR_T_CLEAR, /* $clear */
CDIR_T_ERROR, /* $error */
CDIR_T_VERSION, /* $mapfile_version */
CDIR_T_IF, /* $if */
CDIR_T_ELIF, /* $elif */
CDIR_T_ELSE, /* $else */
CDIR_T_ENDIF, /* $endif */
} cdir_t;
typedef enum { /* Types of arguments accepted by directives */
ARG_T_NONE, /* Directive takes no arguments */
ARG_T_EXPR, /* Directive takes a conditional expression */
ARG_T_ID, /* Conditional expression identifier */
ARG_T_STR, /* Non-empty string */
ARG_T_IGN /* Ignore the argument */
} cdir_arg_t;
typedef struct {
const char *md_name; /* Directive name */
size_t md_size; /* strlen(md_name) */
cdir_arg_t md_arg; /* Type of arguments */
cdir_t md_op; /* CDIR_T_ code */
} cdir_match_t;
/* Control Directives: The most likely items are listed first */
static cdir_match_t match_data[] = {
{ MSG_ORIG(MSG_STR_CDIR_IF), MSG_STR_CDIR_IF_SIZE,
ARG_T_EXPR, CDIR_T_IF },
{ MSG_ORIG(MSG_STR_CDIR_ENDIF), MSG_STR_CDIR_ENDIF_SIZE,
ARG_T_NONE, CDIR_T_ENDIF },
{ MSG_ORIG(MSG_STR_CDIR_ELSE), MSG_STR_CDIR_ELSE_SIZE,
ARG_T_NONE, CDIR_T_ELSE },
{ MSG_ORIG(MSG_STR_CDIR_ELIF), MSG_STR_CDIR_ELIF_SIZE,
ARG_T_EXPR, CDIR_T_ELIF },
{ MSG_ORIG(MSG_STR_CDIR_ERROR), MSG_STR_CDIR_ERROR_SIZE,
ARG_T_STR, CDIR_T_ERROR },
{ MSG_ORIG(MSG_STR_CDIR_ADD), MSG_STR_CDIR_ADD_SIZE,
ARG_T_ID, CDIR_T_ADD },
{ MSG_ORIG(MSG_STR_CDIR_CLEAR), MSG_STR_CDIR_CLEAR_SIZE,
ARG_T_ID, CDIR_T_CLEAR },
{ MSG_ORIG(MSG_STR_CDIR_MFVER), MSG_STR_CDIR_MFVER_SIZE,
ARG_T_IGN, CDIR_T_VERSION },
{ NULL, 0,
ARG_T_IGN, CDIR_T_UNKNOWN }
};
cdir_match_t *mdptr;
char *tail;
int expr_eval; /* Result of evaluating ARG_T_EXPR */
Mapfile arg_mf;
cdir_level_t *level;
int pass, parent_pass; /* Currently accepting input */
restart:
/* Is the immediate context passing input? */
pass = STACK_IS_EMPTY(lms.lms_cdir_stack) ||
STACK_TOP(lms.lms_cdir_stack).cdl_pass;
/* Is the surrounding (parent) context passing input? */
parent_pass = (lms.lms_cdir_stack.stk_n <= 1) ||
lms.lms_cdir_stack.stk_s[lms.lms_cdir_stack.stk_n - 2].cdl_pass;
for (mdptr = match_data; mdptr->md_name; mdptr++) {
/* Prefix must match, or we move on */
if (strncmp(mf->mf_next, mdptr->md_name,
mdptr->md_size) != 0)
continue;
tail = mf->mf_next + mdptr->md_size;
/*
* If there isn't whitespace, or a NULL terminator following
* the prefix, then even though our prefix matched, the actual
* token is longer, and we don't have a match.
*/
if (!isspace(*tail) && (*tail != '\0'))
continue;
/* We have matched a valid control directive */
break;
}
/* Advance input to end of the current line */
advance_to_eol(&mf->mf_next);
/*
* Set up a temporary mapfile descriptor to reference the
* argument string. The benefit of this second block, is that
* we can advance the real one to the next line now, which allows
* us to return at any time knowing that the input has been moved
* to the proper spot. This simplifies the error cases.
*
* If we had a match, tail points at the start of the string.
* Otherwise, we want to point at the end of the line.
*/
arg_mf = *mf;
if (mdptr->md_name == NULL)
arg_mf.mf_text = arg_mf.mf_next;
else
arg_mf.mf_text = arg_mf.mf_next = tail;
/*
* Null terminate the arguments, and advance the main mapfile
* state block to the next line.
*/
if (*mf->mf_next == '\n') {
*mf->mf_next++ = '\0';
mf->mf_lineno++;
}
/* Skip leading whitespace to arguments */
while (isspace(*arg_mf.mf_next))
arg_mf.mf_next++;
/* Strip off any comment present on the line */
for (tail = arg_mf.mf_next; *tail; tail++)
if (*tail == '#') {
*tail = '\0';
break;
}
/*
* Process the arguments as necessary depending on their type.
* If this control directive is nested inside a surrounding context
* that is not currently passing text, then we skip the argument
* evaluation. This follows the behavior of the C preprocessor,
* which only examines enough to detect the operation within
* a disabled section, without issuing errors about the arguments.
*/
if (pass || (parent_pass && (mdptr->md_op == CDIR_T_ELIF))) {
switch (mdptr->md_arg) {
case ARG_T_NONE:
if (*arg_mf.mf_next == '\0')
break;
/* Args are present, but not wanted */
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_REQNOARG),
mdptr->md_name);
return (FALSE);
case ARG_T_EXPR:
/* Ensure that arguments are present */
if (*arg_mf.mf_next == '\0')
goto error_reqarg;
expr_eval = cexp_eval_expr(&arg_mf);
if (expr_eval == -1)
return (FALSE);
break;
case ARG_T_ID:
/* Ensure that arguments are present */
if (*arg_mf.mf_next == '\0')
goto error_reqarg;
if (!cexp_ident_validate(&arg_mf, NULL,
mdptr->md_name))
return (FALSE);
break;
case ARG_T_STR:
/* Ensure that arguments are present */
if (*arg_mf.mf_next == '\0')
goto error_reqarg;
/* Remove trailing whitespace */
tail = arg_mf.mf_next + strlen(arg_mf.mf_next);
while ((tail > arg_mf.mf_next) &&
isspace(*(tail -1)))
tail--;
*tail = '\0';
break;
}
}
/*
* Carry out the specified control directive:
*/
if (!STACK_IS_EMPTY(lms.lms_cdir_stack))
level = &STACK_TOP(lms.lms_cdir_stack);
switch (mdptr->md_op) {
case CDIR_T_UNKNOWN: /* Unrecognized control directive */
if (!pass)
break;
mf_fatal0(&arg_mf, MSG_INTL(MSG_MAP_CDIR_BAD));
return (FALSE);
case CDIR_T_ADD:
if (pass && !cexp_ident_add(&arg_mf, arg_mf.mf_next))
return (FALSE);
break;
case CDIR_T_CLEAR:
if (pass)
cexp_ident_clear(&arg_mf, arg_mf.mf_next);
break;
case CDIR_T_ERROR:
if (!pass)
break;
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_ERROR),
arg_mf.mf_next);
return (FALSE);
case CDIR_T_VERSION:
/*
* A $mapfile_version control directive can only appear
* as the first directive in a mapfile, and is used to
* determine the syntax for the rest of the file. It's
* too late to be using it here.
*/
if (!pass)
break;
mf_fatal0(&arg_mf, MSG_INTL(MSG_MAP_CDIR_REPVER));
return (FALSE);
case CDIR_T_IF:
/* Push a new level on the conditional input stack */
if (STACK_RESERVE(lms.lms_cdir_stack, CDIR_STACK_INIT) == 0)
return (FALSE);
level = &lms.lms_cdir_stack.stk_s[lms.lms_cdir_stack.stk_n++];
level->cdl_if_lineno = arg_mf.mf_lineno;
level->cdl_else_lineno = 0;
/*
* If previous level is not passing, this level is disabled.
* Otherwise, the expression value determines what happens.
*/
if (pass) {
level->cdl_done = level->cdl_pass = expr_eval;
} else {
level->cdl_done = 1;
level->cdl_pass = 0;
}
break;
case CDIR_T_ELIF:
/* $elif requires an open $if construct */
if (STACK_IS_EMPTY(lms.lms_cdir_stack)) {
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_NOIF),
MSG_ORIG(MSG_STR_CDIR_ELIF));
return (FALSE);
}
/* $elif cannot follow $else */
if (level->cdl_else_lineno > 0) {
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_ELSE),
MSG_ORIG(MSG_STR_CDIR_ELIF),
EC_LINENO(level->cdl_else_lineno));
return (FALSE);
}
/*
* Accept text from $elif if the level isn't already
* done and the expression evaluates to true.
*/
level->cdl_pass = !level->cdl_done && expr_eval;
if (level->cdl_pass)
level->cdl_done = 1;
break;
case CDIR_T_ELSE:
/* $else requires an open $if construct */
if (STACK_IS_EMPTY(lms.lms_cdir_stack)) {
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_NOIF),
MSG_ORIG(MSG_STR_CDIR_ELSE));
return (FALSE);
}
/* There can only be one $else in the chain */
if (level->cdl_else_lineno > 0) {
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_ELSE),
MSG_ORIG(MSG_STR_CDIR_ELSE),
EC_LINENO(level->cdl_else_lineno));
return (FALSE);
}
level->cdl_else_lineno = arg_mf.mf_lineno;
/* Accept text from $else if the level isn't already done */
level->cdl_pass = !level->cdl_done;
level->cdl_done = 1;
break;
case CDIR_T_ENDIF:
/* $endif requires an open $if construct */
if (STACK_IS_EMPTY(lms.lms_cdir_stack)) {
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_NOIF),
MSG_ORIG(MSG_STR_CDIR_ENDIF));
return (FALSE);
}
if (--lms.lms_cdir_stack.stk_n > 0)
level = &STACK_TOP(lms.lms_cdir_stack);
break;
default:
return (FALSE);
}
/* Evaluating the control directive above can change pass status */
expr_eval = STACK_IS_EMPTY(lms.lms_cdir_stack) ||
STACK_TOP(lms.lms_cdir_stack).cdl_pass;
if (expr_eval != pass) {
pass = expr_eval;
DBG_CALL(Dbg_map_pass(arg_mf.mf_ofl->ofl_lml, pass,
arg_mf.mf_name, arg_mf.mf_lineno, mdptr->md_name));
}
/*
* At this point, we have processed a control directive,
* updated our conditional state stack, and the input is
* positioned at the start of the line following the directive.
* If the current level is accepting input, then give control
* back to ld_map_gettoken() to resume its normal operation.
*/
if (pass)
return (TRUE);
/*
* The current level is not accepting input. Only another
* control directive can change this, so read and discard input
* until we encounter one of the following:
*
* EOF: Return and let ld_map_gettoken() report it
* Control Directive: Restart this function / evaluate new directive
*/
while (*mf->mf_next != '\0') {
/* Skip leading whitespace */
while (isspace_nonl(*mf->mf_next))
mf->mf_next++;
/*
* Control directives start with a '$'. If we hit
* one, restart the function at this point
*/
if (*mf->mf_next == '$')
goto restart;
/* Not a control directive, so advance input to next line */
advance_to_eol(&mf->mf_next);
if (*mf->mf_next == '\n') {
mf->mf_lineno++;
mf->mf_next++;
}
}
assert(*mf->mf_next == '\0');
return (TRUE);
/*
* Control directives that require an argument that is not present
* jump here to report the error and exit.
*/
error_reqarg:
mf_fatal(&arg_mf, MSG_INTL(MSG_MAP_CDIR_REQARG), mdptr->md_name);
return (FALSE);
}
#ifndef _ELF64
/*
* Convert a string to lowercase.
*/
void
ld_map_lowercase(char *str)
{
while (*str = tolower(*str))
str++;
}
#endif
/*
* Wrappper on strtoul()/strtoull(), adapted to return an Xword.
*
* entry:
* str - Pointer to string to be converted.
* endptr - As documented for strtoul(3C). Either NULL, or
* address of pointer to receive the address of the first
* unused character in str (called "final" in strtoul(3C)).
* ret_value - Address of Xword variable to receive result.
*
* exit:
* On success, *ret_value receives the result, *endptr is updated if
* endptr is non-NULL, and STRTOXWORD_OK is returned.
* On failure, STRTOXWORD_TOBIG is returned if an otherwise valid
* value was too large, and STRTOXWORD_BAD is returned if the string
* is malformed.
*/
ld_map_strtoxword_t
ld_map_strtoxword(const char *restrict str, char **restrict endptr,
Xword *ret_value)
{
#if defined(_ELF64) /* _ELF64 */
#define FUNC strtoull /* Function to use */
#define FUNC_MAX ULLONG_MAX /* Largest value returned by FUNC */
#define XWORD_MAX ULLONG_MAX /* Largest Xword value */
uint64_t value; /* Variable of FUNC return type */
#else /* _ELF32 */
#define FUNC strtoul
#define FUNC_MAX ULONG_MAX
#define XWORD_MAX UINT_MAX
ulong_t value;
#endif
char *endptr_local; /* Used if endptr is NULL */
if (endptr == NULL)
endptr = &endptr_local;
errno = 0;
value = FUNC(str, endptr, 0);
if ((errno != 0) || (str == *endptr)) {
if (value == FUNC_MAX)
return (STRTOXWORD_TOOBIG);
else
return (STRTOXWORD_BAD);
}
/*
* If this is a 64-bit linker building an ELFCLASS32 object,
* the FUNC return type is a 64-bit value, while an Xword is
* 32-bit. It is possible for FUNC to be able to convert a value
* too large for our return type.
*/
#if FUNC_MAX != XWORD_MAX
if (value > XWORD_MAX)
return (STRTOXWORD_TOOBIG);
#endif
*ret_value = value;
return (STRTOXWORD_OK);
#undef FUNC
#undef FUNC_MAX
#undef XWORD_MAC
}
/*
* Convert the unsigned integer value at the current mapfile input
* into binary form. All numeric values in mapfiles are treated as
* unsigned integers of the appropriate width for an address on the
* given target. Values can be decimal, hex, or octal.
*
* entry:
* str - String to process.
* value - Address of variable to receive resulting value.
* notail - If TRUE, an error is issued if non-whitespace
* characters other than '#' (comment) are found following
* the numeric value before the end of line.
*
* exit:
* On success:
* - *str is advanced to the next character following the value
* - *value receives the value
* - Returns TRUE (1).
* On failure, returns FALSE (0).
*/
static Boolean
ld_map_getint(Mapfile *mf, ld_map_tkval_t *value, Boolean notail)
{
ld_map_strtoxword_t s2xw_ret;
ld_map_npatch_t np;
char *endptr;
char *errstr = mf->mf_next;
value->tkv_int.tkvi_str = mf->mf_next;
s2xw_ret = ld_map_strtoxword(mf->mf_next, &endptr,
&value->tkv_int.tkvi_value);
if (s2xw_ret != STRTOXWORD_OK) {
null_patch_eol(mf->mf_next, &np);
if (s2xw_ret == STRTOXWORD_TOOBIG)
mf_fatal(mf, MSG_INTL(MSG_MAP_VALUELIMIT), errstr);
else
mf_fatal(mf, MSG_INTL(MSG_MAP_MALVALUE), errstr);
null_patch_undo(&np);
return (FALSE);
}
/* Advance position to item following value, skipping whitespace */
value->tkv_int.tkvi_cnt = endptr - mf->mf_next;
mf->mf_next = endptr;
while (isspace_nonl(*mf->mf_next))
mf->mf_next++;
/* If requested, ensure there's nothing left */
if (notail && (*mf->mf_next != '\n') && (*mf->mf_next != '#') &&
(*mf->mf_next != '\0')) {
null_patch_eol(mf->mf_next, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_BADVALUETAIL), errstr);
null_patch_undo(&np);
return (FALSE);
}
return (TRUE);
}
/*
* Convert a an unquoted identifier into a TK_STRING token, using the
* rules for syntax version in use. Used exclusively by ld_map_gettoken().
*
* entry:
* mf - Mapfile descriptor, positioned to the first character of
* the string.
* flags - Bitmask of options to control ld_map_gettoken()s behavior
* tkv- Address of pointer to variable to receive token value.
*
* exit:
* On success, mf is advanced past the token, tkv is updated with
* the string, and TK_STRING is returned. On error, TK_ERROR is returned.
*/
inline static Token
gettoken_ident(Mapfile *mf, int flags, ld_map_tkval_t *tkv)
{
char *end;
Token tok;
ld_map_npatch_t np;
tkv->tkv_str = mf->mf_next;
if ((end = ident_delimit(mf)) == NULL)
return (TK_ERROR);
mf->mf_next = end;
/*
* One advantage of reading the entire mapfile into memory is that
* we can access the strings within it without having to allocate
* more memory or make copies. In order to do that, we need to NULL
* terminate this identifier. That is going to overwrite the
* following character. The problem this presents is that the next
* character may well be the first character of a subsequent token.
* The solution to this is:
*
* 1) Disallow the case where the next character is able to
* start a string. This is not legal mapfile syntax anyway,
* so catching it here simplifies matters.
* 2) Copy the character into the special mf->mf_next_ch
* 3) The next call to ld_map_gettoken() checks mf->mf_next_ch,
* and if it is non-0, uses it instead of dereferencing the
* mf_next pointer.
*/
tok = (*mf->mf_next & 0x80) ?
TK_OP_ILLCHR : mf->mf_tokdisp[*mf->mf_next];
switch (tok) {
case TK_OP_BADCHR:
null_patch_eol(mf->mf_next, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_BADCHAR), mf->mf_next);
null_patch_undo(&np);
return (TK_ERROR);
case TK_OP_SIMQUOTE:
case TK_OP_CQUOTE:
case TK_OP_CDIR:
case TK_OP_NUM:
case TK_OP_ID:
null_patch_eol(mf->mf_next, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_WSNEEDED), mf->mf_next);
null_patch_undo(&np);
return (TK_ERROR);
}
/* Null terminate, saving the replaced character */
mf->mf_next_ch = *mf->mf_next;
*mf->mf_next = '\0';
if (flags & TK_F_STRLC)
ld_map_lowercase(tkv->tkv_str);
return (TK_STRING);
}
/*
* Convert a quoted string into a TK_STRING token, using simple
* quoting rules:
* - Start and end quotes must be present and match
* - There are no special characters or escape sequences.
* This function is used exclusively by ld_map_gettoken().
*
* entry:
* mf - Mapfile descriptor, positioned to the opening quote character.
* flags - Bitmask of options to control ld_map_gettoken()s behavior
* tkv- Address of pointer to variable to receive token value.
*
* exit:
* On success, mf is advanced past the token, tkv is updated with
* the string, and TK_STRING is returned. On error, TK_ERROR is returned.
*/
inline static Token
gettoken_simquote_str(Mapfile *mf, int flags, ld_map_tkval_t *tkv)
{
char *str, *end;
char quote;
str = mf->mf_next++;
quote = *str;
end = mf->mf_next;
while ((*end != '\0') && (*end != '\n') && (*end != quote))
end++;
if (*end != quote) {
ld_map_npatch_t np;
null_patch_eol(end, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_NOTERM), str);
null_patch_undo(&np);
return (TK_ERROR);
}
/*
* end is pointing at the closing quote. We can turn that into NULL
* termination for the string without needing to restore it later.
*/
*end = '\0';
mf->mf_next = end + 1;
tkv->tkv_str = str + 1; /* Skip opening quote */
if (flags & TK_F_STRLC)
ld_map_lowercase(tkv->tkv_str);
return (TK_STRING);
}
/*
* Convert a quoted string into a TK_STRING token, using C string literal
* quoting rules:
* - Start and end quotes must be present and match
* - Backslash is an escape, used to introduce special characters
* This function is used exclusively by ld_map_gettoken().
*
* entry:
* mf - Mapfile descriptor, positioned to the opening quote character.
* flags - Bitmask of options to control ld_map_gettoken()s behavior
* tkv- Address of pointer to variable to receive token value.
*
* exit:
* On success, mf is advanced past the token, tkv is updated with
* the string, and TK_STRING is returned. On error, TK_ERROR is returned.
*/
inline static Token
gettoken_cquote_str(Mapfile *mf, int flags, ld_map_tkval_t *tkv)
{
char *str, *cur, *end;
char quote;
int c;
/*
* This function goes through the quoted string and copies
* it on top of itself, replacing escape sequences with the
* characters they denote. There is always enough room for this,
* because escapes are multi-character sequences that are converted
* to single character results.
*/
str = mf->mf_next++;
quote = *str;
cur = end = mf->mf_next;
for (c = *end++; (c != '\0') && (c != '\n') && (c != quote);
c = *end++) {
if (c == '\\') {
c = conv_translate_c_esc(&end);
if (c == -1) {
mf_fatal(mf, MSG_INTL(MSG_MAP_BADCESC), *end);
return (TK_ERROR);
}
}
*cur++ = c;
}
*cur = '\0'; /* terminate the result */
if (c != quote) {
ld_map_npatch_t np;
null_patch_eol(end, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_NOTERM), str);
null_patch_undo(&np);
return (TK_ERROR);
}
/* end is pointing one character past the closing quote */
mf->mf_next = end;
tkv->tkv_str = str + 1; /* Skip opening quote */
if (flags & TK_F_STRLC)
ld_map_lowercase(tkv->tkv_str);
return (TK_STRING);
}
/*
* Get a token from the mapfile.
*
* entry:
* mf - Mapfile descriptor
* flags - Bitmask of options to control ld_map_gettoken()s behavior
* tkv- Address of pointer to variable to receive token value.
*
* exit:
* Returns one of the TK_* values, to report the result. If the resulting
* token has a value (TK_STRING / TK_INT), and tkv is non-NULL, tkv
* is filled in with the resulting value.
*/
Token
ld_map_gettoken(Mapfile *mf, int flags, ld_map_tkval_t *tkv)
{
int cdir_allow, ch;
Token tok;
ld_map_npatch_t np;
/*
* Mapfile control directives all start with a '$' character. However,
* they are only valid when they are the first thing on a line. That
* happens on the first call to ld_map_gettoken() for a new a new
* mapfile, as tracked with lms.lms_cdir_valid, and immediately
* following each newline seen in the file.
*/
cdir_allow = lms.lms_cdir_valid;
lms.lms_cdir_valid = 0;
/* Cycle through the characters looking for tokens. */
for (;;) {
/*
* Process the next character. This is normally *mf->mf_next,
* but if mf->mf_next_ch is non-0, then it contains the
* character, and *mf->mf_next contains a NULL termination
* from the TK_STRING token returned on the previous call.
*
* gettoken_ident() ensures that this is never done to
* a character that starts a string.
*/
if (mf->mf_next_ch == 0) {
ch = *mf->mf_next;
} else {
ch = mf->mf_next_ch;
mf->mf_next_ch = 0; /* Reset */
}
/* Map the character to a dispatch action */
tok = (ch & 0x80) ? TK_OP_ILLCHR : mf->mf_tokdisp[ch];
/*
* Items that require processing are identified as OP tokens.
* We process them, and return a result non-OP token.
*
* Non-OP tokens are single character tokens, and we return
* them immediately.
*/
switch (tok) {
case TK_OP_EOF:
/* If EOFOK is set, quietly report it as TK_EOF */
if ((flags & TK_F_EOFOK) != 0)
return (TK_EOF);
/* Treat it as a standard error */
mf_fatal0(mf, MSG_INTL(MSG_MAP_PREMEOF));
return (TK_ERROR);
case TK_OP_ILLCHR:
mf_fatal(mf, MSG_INTL(MSG_MAP_ILLCHAR), ch);
mf->mf_next++;
return (TK_ERROR);
case TK_OP_BADCHR:
tk_op_badchr:
null_patch_eol(mf->mf_next, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_BADCHAR), mf->mf_next);
null_patch_undo(&np);
mf->mf_next++;
return (TK_ERROR);
case TK_OP_WS: /* White space */
mf->mf_next++;
break;
case TK_OP_NL: /* White space too, but bump line number. */
mf->mf_next++;
mf->mf_lineno++;
cdir_allow = 1;
break;
case TK_OP_SIMQUOTE:
if (flags & TK_F_KEYWORD)
goto tk_op_badkwquote;
return (gettoken_simquote_str(mf, flags, tkv));
case TK_OP_CQUOTE:
if (flags & TK_F_KEYWORD) {
tk_op_badkwquote:
null_patch_eol(mf->mf_next, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_BADKWQUOTE),
mf->mf_next);
null_patch_undo(&np);
mf->mf_next++;
return (TK_ERROR);
}
return (gettoken_cquote_str(mf, flags, tkv));
case TK_OP_CMT:
advance_to_eol(&mf->mf_next);
break;
case TK_OP_CDIR:
/*
* Control directives are only valid at the start
* of a line.
*/
if (!cdir_allow) {
null_patch_eol(mf->mf_next, &np);
mf_fatal(mf, MSG_INTL(MSG_MAP_CDIR_NOTBOL),
mf->mf_next);
null_patch_undo(&np);
mf->mf_next++;
return (TK_ERROR);
}
if (!cdir_process(mf))
return (TK_ERROR);
break;
case TK_OP_NUM: /* Decimal, hex(0x...), or octal (0...) value */
if (!ld_map_getint(mf, tkv, FALSE))
return (TK_ERROR);
return (TK_INT);
case TK_OP_ID: /* Unquoted identifier */
return (gettoken_ident(mf, flags, tkv));
case TK_OP_CEQUAL: /* += or -= */
if (*(mf->mf_next + 1) != '=')
goto tk_op_badchr;
tok = (ch == '+') ? TK_PLUSEQ : TK_MINUSEQ;
mf->mf_next += 2;
return (tok);
default: /* Non-OP token */
mf->mf_next++;
return (tok);
}
}
}
/*
* Given a token and value returned by ld_map_gettoken(), return a string
* representation of it suitable for use in an error message.
*
* entry:
* tok - Token code. Must not be an OP-token
* tkv - Token value
*/
const char *
ld_map_tokenstr(Token tok, ld_map_tkval_t *tkv, Conv_inv_buf_t *inv_buf)
{
size_t cnt;
switch (tok) {
case TK_ERROR:
return (MSG_ORIG(MSG_STR_ERROR));
case TK_EOF:
return (MSG_ORIG(MSG_STR_EOF));
case TK_STRING:
return (tkv->tkv_str);
case TK_COLON:
return (MSG_ORIG(MSG_QSTR_COLON));
case TK_SEMICOLON:
return (MSG_ORIG(MSG_QSTR_SEMICOLON));
case TK_EQUAL:
return (MSG_ORIG(MSG_QSTR_EQUAL));
case TK_PLUSEQ:
return (MSG_ORIG(MSG_QSTR_PLUSEQ));
case TK_MINUSEQ:
return (MSG_ORIG(MSG_QSTR_MINUSEQ));
case TK_ATSIGN:
return (MSG_ORIG(MSG_QSTR_ATSIGN));
case TK_DASH:
return (MSG_ORIG(MSG_QSTR_DASH));
case TK_LEFTBKT:
return (MSG_ORIG(MSG_QSTR_LEFTBKT));
case TK_RIGHTBKT:
return (MSG_ORIG(MSG_QSTR_RIGHTBKT));
case TK_PIPE:
return (MSG_ORIG(MSG_QSTR_PIPE));
case TK_INT:
cnt = tkv->tkv_int.tkvi_cnt;
if (cnt >= sizeof (inv_buf->buf))
cnt = sizeof (inv_buf->buf) - 1;
(void) memcpy(inv_buf->buf, tkv->tkv_int.tkvi_str, cnt);
inv_buf->buf[cnt] = '\0';
return (inv_buf->buf);
case TK_STAR:
return (MSG_ORIG(MSG_QSTR_STAR));
case TK_BANG:
return (MSG_ORIG(MSG_QSTR_BANG));
default:
assert(0);
break;
}
/*NOTREACHED*/
return (MSG_INTL(MSG_MAP_INTERR));
}
/*
* Advance the input to the first non-empty line, and determine
* the mapfile version. The version is specified by the mapfile
* using a $mapfile_version directive. The original System V
* syntax lacks this directive, and we use that fact to identify
* such files. SysV mapfile are implicitly defined to have version 1.
*
* entry:
* ofl - Output file descriptor
* mf - Mapfile block
*
* exit:
* On success, updates mf->mf_version, and returns TRUE (1).
* On failure, returns FALSE (0).
*/
static Boolean
mapfile_version(Mapfile *mf)
{
char *line_start = mf->mf_next;
Boolean cont = TRUE;
Boolean status = TRUE; /* Assume success */
Token tok;
mf->mf_version = MFV_SYSV;
/*
* Cycle through the characters looking for tokens. Although the
* true version is not known yet, we use the v2 dispatch table.
* It contains control directives, which we need for this search,
* and the other TK_OP_ tokens we will recognize and act on are the
* same for both tables.
*
* It is important not to process any tokens that would lead to
* a non-OP token:
*
* - The version is required to interpret them
* - Our mapfile descriptor is not fully initialized,
* attempts to run that code will crash the program.
*/
while (cont) {
/* Map the character to a dispatch action */
tok = (*mf->mf_next & 0x80) ?
TK_OP_ILLCHR : gettok_dispatch_v2[*mf->mf_next];
switch (tok) {
case TK_OP_WS: /* White space */
mf->mf_next++;
break;
case TK_OP_NL: /* White space too, but bump line number. */
mf->mf_next++;
mf->mf_lineno++;
break;
case TK_OP_CMT:
advance_to_eol(&mf->mf_next);
break;
case TK_OP_CDIR:
/*
* Control directives are only valid at the start
* of a line. However, as we have not yet seen
* a token, we do not need to test for this, and
* can safely assume that we are at the start.
*/
if (!strncasecmp(mf->mf_next,
MSG_ORIG(MSG_STR_CDIR_MFVER),
MSG_STR_CDIR_MFVER_SIZE) &&
isspace_nonl(*(mf->mf_next +
MSG_STR_CDIR_MFVER_SIZE))) {
ld_map_tkval_t ver;
mf->mf_next += MSG_STR_CDIR_MFVER_SIZE + 1;
if (!ld_map_getint(mf, &ver, TRUE)) {
status = cont = FALSE;
break;
}
/*
* Is it a valid version? Note that we
* intentionally do not allow you to
* specify version 1 using the $mapfile_version
* syntax, because that's reserved to version
* 2 and up.
*/
if ((ver.tkv_int.tkvi_value < 2) ||
(ver.tkv_int.tkvi_value >= MFV_NUM)) {
const char *fmt;
fmt = (ver.tkv_int.tkvi_value < 2) ?
MSG_INTL(MSG_MAP_CDIR_BADVDIR) :
MSG_INTL(MSG_MAP_CDIR_BADVER);
mf_fatal(mf, fmt,
EC_WORD(ver.tkv_int.tkvi_value));
status = cont = FALSE;
break;
}
mf->mf_version = ver.tkv_int.tkvi_value;
cont = FALSE; /* Version recovered. All done */
break;
}
/*
* Not a version directive. Reset the current position
* to the start of the current line and stop here.
* SysV syntax applies.
*/
mf->mf_next = line_start;
cont = FALSE;
break;
default:
/*
* If we see anything else, then stop at this point.
* The file has System V syntax (version 1), and the
* next token should be interpreted as such.
*/
cont = FALSE;
break;
}
}
return (status);
}
/*
* Parse the mapfile.
*/
Boolean
ld_map_parse(const char *mapfile, Ofl_desc *ofl)
{
struct stat stat_buf; /* stat of mapfile */
int mapfile_fd; /* descriptor for mapfile */
int err;
Mapfile *mf; /* Mapfile descriptor */
size_t name_len; /* strlen(mapfile) */
/*
* Determine if we're dealing with a file or a directory.
*/
if (stat(mapfile, &stat_buf) == -1) {
err = errno;
ld_eprintf(ofl, ERR_FATAL, MSG_INTL(MSG_SYS_STAT), mapfile,
strerror(err));
return (FALSE);
}
if (S_ISDIR(stat_buf.st_mode)) {
DIR *dirp;
struct dirent *denp;
/*
* Open the directory and interpret each visible file as a
* mapfile.
*/
if ((dirp = opendir(mapfile)) == NULL)
return (TRUE);
while ((denp = readdir(dirp)) != NULL) {
char path[PATH_MAX];
/*
* Ignore any hidden filenames. Construct the full
* pathname to the new mapfile.
*/
if (*denp->d_name == '.')
continue;
(void) snprintf(path, PATH_MAX, MSG_ORIG(MSG_STR_PATH),
mapfile, denp->d_name);
if (!ld_map_parse(path, ofl))
return (FALSE);
}
(void) closedir(dirp);
return (TRUE);
} else if (!S_ISREG(stat_buf.st_mode)) {
ld_eprintf(ofl, ERR_FATAL, MSG_INTL(MSG_SYS_NOTREG), mapfile);
return (FALSE);
}
/* Open file */
if ((mapfile_fd = open(mapfile, O_RDONLY)) == -1) {
err = errno;
ld_eprintf(ofl, ERR_FATAL, MSG_INTL(MSG_SYS_OPEN), mapfile,
strerror(err));
return (FALSE);
}
/*
* Allocate enough memory to hold the state block, mapfile name,
* and mapfile text. Text has alignment 1, so it can follow the
* state block without padding.
*/
name_len = strlen(mapfile) + 1;
mf = libld_malloc(sizeof (*mf) + name_len + stat_buf.st_size + 1);
if (mf == NULL)
return (FALSE);
mf->mf_ofl = ofl;
mf->mf_name = (char *)(mf + 1);
(void) strcpy(mf->mf_name, mapfile);
mf->mf_text = mf->mf_name + name_len;
if (read(mapfile_fd, mf->mf_text, stat_buf.st_size) !=
stat_buf.st_size) {
err = errno;
ld_eprintf(ofl, ERR_FATAL, MSG_INTL(MSG_SYS_READ), mapfile,
strerror(err));
(void) close(mapfile_fd);
return (FALSE);
}
(void) close(mapfile_fd);
mf->mf_text[stat_buf.st_size] = '\0';
mf->mf_next = mf->mf_text;
mf->mf_lineno = 1;
mf->mf_next_ch = 0; /* No "lookahead" character yet */
mf->mf_ec_insndx = 0; /* Insert entrace criteria at top */
/*
* Read just enough from the mapfile to determine the version,
* and then dispatch to the appropriate code for further processing
*/
if (!mapfile_version(mf))
return (FALSE);
/*
* Start and continuation masks for unquoted identifier at this
* mapfile version level.
*/
mf->mf_tkid_start = TKID_ATTR_START(mf->mf_version);
mf->mf_tkid_cont = TKID_ATTR_CONT(mf->mf_version);
DBG_CALL(Dbg_map_parse(ofl->ofl_lml, mapfile, mf->mf_version));
switch (mf->mf_version) {
case MFV_SYSV:
/* Guidance: Use newer mapfile syntax */
if (OFL_GUIDANCE(ofl, FLG_OFG_NO_MF))
ld_eprintf(ofl, ERR_GUIDANCE,
MSG_INTL(MSG_GUIDE_MAPFILE), mapfile);
mf->mf_tokdisp = gettok_dispatch_v1;
if (!ld_map_parse_v1(mf))
return (FALSE);
break;
case MFV_SOLARIS:
mf->mf_tokdisp = gettok_dispatch_v2;
STACK_RESET(lms.lms_cdir_stack);
/*
* If the conditional expression identifier tree has not been
* initialized, set it up. This is only done on the first
* mapfile, because the identifier control directives accumulate
* across all the mapfiles.
*/
if ((lms.lms_cexp_id == NULL) && !cexp_ident_init())
return (FALSE);
/*
* Tell ld_map_gettoken() we will accept a '$' as starting a
* control directive on the first call. Normally, they are
* only allowed after a newline.
*/
lms.lms_cdir_valid = 1;
if (!ld_map_parse_v2(mf))
return (FALSE);
/* Did we leave any open $if control directives? */
if (!STACK_IS_EMPTY(lms.lms_cdir_stack)) {
while (!STACK_IS_EMPTY(lms.lms_cdir_stack)) {
cdir_level_t *level =
&STACK_POP(lms.lms_cdir_stack);
mf_fatal(mf, MSG_INTL(MSG_MAP_CDIR_NOEND),
EC_LINENO(level->cdl_if_lineno));
}
return (FALSE);
}
break;
}
return (TRUE);
}
/*
* Sort the segment list. This is necessary if a mapfile has set explicit
* virtual addresses for segments, or defined a SEGMENT_ORDER directive.
*
* Only PT_LOAD segments can be assigned a virtual address. These segments can
* be one of two types:
*
* - Standard segments for text, data or bss. These segments will have been
* inserted before the default text (first PT_LOAD) segment.
*
* - Empty (reservation) segments. These segment will have been inserted at
* the end of any default PT_LOAD segments.
*
* Any standard segments that are assigned a virtual address will be sorted,
* and as their definitions precede any default PT_LOAD segments, these segments
* will be assigned sections before any defaults.
*
* Any reservation segments are also sorted amoung themselves, as these segments
* must still follow the standard default segments.
*/
static Boolean
sort_seg_list(Ofl_desc *ofl)
{
APlist *sort_segs = NULL, *load_segs = NULL;
Sg_desc *sgp1;
Aliste idx1;
Aliste nsegs;
/*
* We know the number of elements in the sorted list will be
* the same as the original, so use this as the initial allocation
* size for the replacement aplist.
*/
nsegs = aplist_nitems(ofl->ofl_segs);
/* Add the items below SGID_TEXT to the list */
for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp1)) {
if (sgp1->sg_id >= SGID_TEXT)
break;
if (aplist_append(&sort_segs, sgp1, nsegs) == NULL)
return (FALSE);
}
/*
* If there are any SEGMENT_ORDER items, add them, and set their
* FLG_SG_ORDERED flag to identify them in debug output, and to
* prevent them from being added again below.
*/
for (APLIST_TRAVERSE(ofl->ofl_segs_order, idx1, sgp1)) {
if (aplist_append(&sort_segs, sgp1, nsegs) == NULL)
return (FALSE);
sgp1->sg_flags |= FLG_SG_ORDERED;
}
/*
* Add the loadable segments to another list in sorted order.
*/
DBG_CALL(Dbg_map_sort_title(ofl->ofl_lml, TRUE));
for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp1)) {
DBG_CALL(Dbg_map_sort_seg(ofl->ofl_lml, ELFOSABI_SOLARIS,
ld_targ.t_m.m_mach, sgp1));
/* Only interested in PT_LOAD items not in SEGMENT_ORDER list */
if ((sgp1->sg_phdr.p_type != PT_LOAD) ||
(sgp1->sg_flags & FLG_SG_ORDERED))
continue;
/*
* If the loadable segment does not contain a vaddr, simply
* append it to the new list.
*/
if ((sgp1->sg_flags & FLG_SG_P_VADDR) == 0) {
if (aplist_append(&load_segs, sgp1, AL_CNT_SEGMENTS) ==
NULL)
return (FALSE);
} else {
Aliste idx2;
Sg_desc *sgp2;
int inserted = 0;
/*
* Traverse the segment list we are creating, looking
* for a segment that defines a vaddr.
*/
for (APLIST_TRAVERSE(load_segs, idx2, sgp2)) {
/*
* Any real segments that contain vaddr's need
* to be sorted. Any reservation segments also
* need to be sorted. However, any reservation
* segments should be placed after any real
* segments.
*/
if (((sgp2->sg_flags &
(FLG_SG_P_VADDR | FLG_SG_EMPTY)) == 0) &&
(sgp1->sg_flags & FLG_SG_EMPTY))
continue;
if ((sgp2->sg_flags & FLG_SG_P_VADDR) &&
((sgp2->sg_flags & FLG_SG_EMPTY) ==
(sgp1->sg_flags & FLG_SG_EMPTY))) {
if (sgp1->sg_phdr.p_vaddr ==
sgp2->sg_phdr.p_vaddr) {
ld_eprintf(ofl, ERR_FATAL,
MSG_INTL(MSG_MAP_SEGSAME),
sgp1->sg_name,
sgp2->sg_name);
return (FALSE);
}
if (sgp1->sg_phdr.p_vaddr >
sgp2->sg_phdr.p_vaddr)
continue;
}
/*
* Insert this segment before the segment on
* the load_segs list.
*/
if (aplist_insert(&load_segs, sgp1,
AL_CNT_SEGMENTS, idx2) == NULL)
return (FALSE);
inserted = 1;
break;
}
/*
* If the segment being inspected has not been inserted
* in the segment list, simply append it to the list.
*/
if ((inserted == 0) && (aplist_append(&load_segs,
sgp1, AL_CNT_SEGMENTS) == NULL))
return (FALSE);
}
}
/*
* Add the sorted loadable segments to our initial segment list.
*/
for (APLIST_TRAVERSE(load_segs, idx1, sgp1)) {
if (aplist_append(&sort_segs, sgp1, AL_CNT_SEGMENTS) == NULL)
return (FALSE);
}
/*
* Add all other segments to our list.
*/
for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp1)) {
if ((sgp1->sg_id < SGID_TEXT) ||
(sgp1->sg_phdr.p_type == PT_LOAD) ||
(sgp1->sg_flags & FLG_SG_ORDERED))
continue;
if (aplist_append(&sort_segs, sgp1, AL_CNT_SEGMENTS) == NULL)
return (FALSE);
}
/*
* Free the original list, and the pt_load list, and use
* the new list as the segment list.
*/
free(ofl->ofl_segs);
if (load_segs) free(load_segs);
ofl->ofl_segs = sort_segs;
if (DBG_ENABLED) {
Dbg_map_sort_title(ofl->ofl_lml, FALSE);
for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp1)) {
Dbg_map_sort_seg(ofl->ofl_lml, ELFOSABI_SOLARIS,
ld_targ.t_m.m_mach, sgp1);
}
}
return (TRUE);
}
/*
* After all mapfiles have been processed, this routine is used to
* finish any remaining mapfile related work.
*
* exit:
* Returns TRUE on success, and FALSE on failure.
*/
Boolean
ld_map_post_process(Ofl_desc *ofl)
{
Aliste idx, idx2;
Is_desc *isp;
Sg_desc *sgp;
Ent_desc *enp;
Sg_desc *first_seg = NULL;
DBG_CALL(Dbg_map_post_title(ofl->ofl_lml));
/*
* Per-segment processing:
* - Identify segments with explicit virtual address
* - Details of input and output section order
*/
for (APLIST_TRAVERSE(ofl->ofl_segs, idx, sgp)) {
/*
* We are looking for segments. Program headers that represent
* segments are required to have a non-NULL name pointer,
* while that those that do not are required to have a
* NULL name pointer.
*/
if (sgp->sg_name == NULL)
continue;
/* Remember the first non-disabled segment */
if ((first_seg == NULL) && !(sgp->sg_flags & FLG_SG_DISABLED))
first_seg = sgp;
/*
* If a segment has an explicit virtual address, we will
* need to sort the segments.
*/
if (sgp->sg_flags & FLG_SG_P_VADDR)
ofl->ofl_flags1 |= FLG_OF1_VADDR;
/*
* The FLG_OF_OS_ORDER flag enables the code that does
* output section ordering. Set if the segment has
* a non-empty output section order list.
*/
if (alist_nitems(sgp->sg_os_order) > 0)
ofl->ofl_flags |= FLG_OF_OS_ORDER;
/*
* The version 1 and version 2 syntaxes for input section
* ordering are different and incompatible enough that we
* only allow the use of one or the other for a given segment:
*
* v1) The version 1 syntax has the user set the ?O flag on
* the segment. If this is done, all input sections placed
* via an entrance criteria that has a section name are to
* be sorted, using the order of the entrance criteria
* as the sort key.
*
* v2) The version 2 syntax has the user specify a name for
* the entry criteria, and then provide a list of entry
* criteria names via the IS_ORDER segment attribute.
* Sections placed via the criteria listed in IS_ORDER
* are sorted, and the others are not.
*
* Regardless of the syntax version used, the section sorting
* code expects the following:
*
* - Segments requiring input section sorting have the
* FLG_SG_IS_ORDER flag set
*
* - Entrance criteria referencing the segment that
* participate in input section sorting have a non-zero
* sort key in their ec_ordndx field.
*
* At this point, the following are true:
*
* - All entrance criteria have ec_ordndx set to 0.
* - Segments that require the version 1 behavior have
* the FLG_SG_IS_ORDER flag set, and the segments
* sg_is_order list is empty.
* - Segments that require the version 2 behavior do not
* have FLG_SG_IS_ORDER set, and the sg_is_order list is
* non-empty. This list contains the names of the entrance
* criteria that will participate in input section sorting,
* and their relative order in the list provides the
* sort key to use.
*
* We must detect these two cases, set the FLG_SG_IS_ORDER
* flag as necessary, and fill in all entrance criteria
* sort keys. If any input section sorting is to be done,
* we also set the FLG_OF_IS_ORDER flag on the output descriptor
* to enable the code that does that work.
*/
/* Version 1: ?O flag? */
if (sgp->sg_flags & FLG_SG_IS_ORDER) {
Word index = 0;
ofl->ofl_flags |= FLG_OF_IS_ORDER;
DBG_CALL(Dbg_map_ent_ord_title(ofl->ofl_lml,
sgp->sg_name));
/*
* Give each user defined entrance criteria for this
* segment that specifies a section name a
* monotonically increasing sort key.
*/
for (APLIST_TRAVERSE(ofl->ofl_ents, idx2, enp))
if ((enp->ec_segment == sgp) &&
(enp->ec_is_name != NULL) &&
((enp->ec_flags & FLG_EC_BUILTIN) == 0))
enp->ec_ordndx = ++index;
continue;
}
/* Version 2: SEGMENT IS_ORDER list? */
if (aplist_nitems(sgp->sg_is_order) > 0) {
Word index = 0;
ofl->ofl_flags |= FLG_OF_IS_ORDER;
DBG_CALL(Dbg_map_ent_ord_title(ofl->ofl_lml,
sgp->sg_name));
/*
* Give each entrance criteria in the sg_is_order
* list a monotonically increasing sort key.
*/
for (APLIST_TRAVERSE(sgp->sg_is_order, idx2, enp)) {
enp->ec_ordndx = ++index;
enp->ec_segment->sg_flags |= FLG_SG_IS_ORDER;
}
}
}
/* Sort the segment descriptors if necessary */
if (((ofl->ofl_flags1 & FLG_OF1_VADDR) ||
(aplist_nitems(ofl->ofl_segs_order) > 0)) &&
!sort_seg_list(ofl))
return (FALSE);
/*
* If the output file is a static file without an interpreter, and
* if any virtual address is specified, then set the NOHDR flag for
* backward compatibility.
*/
if (!(ofl->ofl_flags & (FLG_OF_DYNAMIC | FLG_OF_RELOBJ)) &&
!(ofl->ofl_osinterp) && (ofl->ofl_flags1 & FLG_OF1_VADDR))
ofl->ofl_dtflags_1 |= DF_1_NOHDR;
if (ofl->ofl_flags & FLG_OF_RELOBJ) {
/*
* NOHDR has no effect on a relocatable file.
* Make sure this flag isn't set.
*/
ofl->ofl_dtflags_1 &= ~DF_1_NOHDR;
} else if (first_seg != NULL) {
/*
* DF_1_NOHDR might have been set globally by the HDR_NOALLOC
* directive. If not, then we want to check the per-segment
* flag for the first loadable segment and propagate it
* if set.
*/
if ((ofl->ofl_dtflags_1 & DF_1_NOHDR) == 0) {
/*
* If we sorted the segments, the first segment
* may have changed.
*/
if ((ofl->ofl_flags1 & FLG_OF1_VADDR) ||
(aplist_nitems(ofl->ofl_segs_order) > 0)) {
for (APLIST_TRAVERSE(ofl->ofl_segs, idx, sgp)) {
if (sgp->sg_name == NULL)
continue;
if ((sgp->sg_flags & FLG_SG_DISABLED) ==
0) {
first_seg = sgp;
break;
}
}
}
/*
* If the per-segment NOHDR flag is set on our first
* segment, then make it take effect.
*/
if (first_seg->sg_flags & FLG_SG_NOHDR)
ofl->ofl_dtflags_1 |= DF_1_NOHDR;
}
/*
* For executable and shared objects, the first segment must
* be loadable unless NOHDR was specified, because the ELF
* header must simultaneously lie at offset 0 of the file and
* be included in the first loadable segment. This isn't
* possible if some other segment type starts the file
*/
if (!(ofl->ofl_dtflags_1 & DF_1_NOHDR) &&
(first_seg->sg_phdr.p_type != PT_LOAD)) {
Conv_inv_buf_t inv_buf;
ld_eprintf(ofl, ERR_FATAL,
MSG_INTL(MSG_SEG_FIRNOTLOAD),
conv_phdr_type(ELFOSABI_SOLARIS, ld_targ.t_m.m_mach,
first_seg->sg_phdr.p_type, 0, &inv_buf),
first_seg->sg_name);
return (FALSE);
}
}
/*
* Mapfiles may have been used to create symbol definitions
* with backing storage. Although the backing storage is
* associated with an input section, the association of the
* section to an output section (and segment) is initially
* deferred. Now that all mapfile processing is complete, any
* entrance criteria requirements have been processed, and
* these backing storage sections can be associated with the
* appropriate output section (and segment).
*/
if (ofl->ofl_maptext || ofl->ofl_mapdata)
DBG_CALL(Dbg_sec_backing(ofl->ofl_lml));
for (APLIST_TRAVERSE(ofl->ofl_maptext, idx, isp)) {
if (ld_place_section(ofl, isp, NULL,
ld_targ.t_id.id_text, NULL) == (Os_desc *)S_ERROR)
return (FALSE);
}
for (APLIST_TRAVERSE(ofl->ofl_mapdata, idx, isp)) {
if (ld_place_section(ofl, isp, NULL,
ld_targ.t_id.id_data, NULL) == (Os_desc *)S_ERROR)
return (FALSE);
}
return (TRUE);
}
| 28.607042 | 80 | 0.649968 | [
"object"
] |
9abf327e688b1587dc0bf5931f63b629c56b03ab | 10,761 | h | C | Pseudo-Drifter/Ronin-Math-Library/vector.h | WerenskjoldH/Pseudo-Drifter | e9b09baa540372276608270dbfa14d5dd7e72639 | [
"Unlicense"
] | 1 | 2019-11-22T15:56:56.000Z | 2019-11-22T15:56:56.000Z | Pseudo-Drifter/Ronin-Math-Library/vector.h | WerenskjoldH/Pseudo-Drifter | e9b09baa540372276608270dbfa14d5dd7e72639 | [
"Unlicense"
] | null | null | null | Pseudo-Drifter/Ronin-Math-Library/vector.h | WerenskjoldH/Pseudo-Drifter | e9b09baa540372276608270dbfa14d5dd7e72639 | [
"Unlicense"
] | null | null | null | #ifndef VECTOR_H
#define VECTOR_H
/*
File: vector.h
Description: This file is from my Ronin Math Library, it has been slightly extended to support "dual vectors" and projections form world to screen space.
https://github.com/WerenskjoldH/Ronin-Math-Libary
*/
#include <math.h>
#include <iostream>
#include "matrix.h"
namespace rn
{
class vector3f
{
private:
public:
real x;
real y;
real z;
// For 4-word speed increase, most computers now-a-days use 4-word memory busses and, as such, just 3-words requires an offset
real padding = 0;
// Getters/Setters
real r() const
{
return x;
}
real g() const
{
return y;
}
real b() const
{
return z;
}
// Constructors
vector3f(real iX = 0, real iY = 0, real iZ = 0) : x(iX), y(iY), z(iZ) {};
// Deconstructor
~vector3f() {}
// Copy Constructor
vector3f(const vector3f& v) : x(v.x), y(v.y), z(v.z) {};
// Operator Overloads
vector3f& operator=(const vector3f& v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
// Add components to eachother and set equal
void operator+=(const vector3f& v)
{
x += v.x;
y += v.y;
z += v.z;
}
// Subtract components from eachother and set equal
void operator-=(const vector3f& v)
{
x -= v.x;
y -= v.y;
z -= v.z;
}
// Multiply vector by scalar and set equal
void operator*=(const real& s)
{
x *= s;
y *= s;
z *= s;
}
// Divide vector by scalar and set equal
void operator/=(const real& s)
{
real mag = 1.f / s;
x = x * mag;
y = y * mag;
z = z * mag;
}
// Vector cross product
void operator%=(const vector3f& v)
{
*this = cross(v);
}
// Calculate scalar(dot) product and return result
real operator*(const vector3f& v) const
{
return x * v.x + y * v.y + z * v.z;
}
// Divide by scalar and return result
vector3f operator/(const real s) const
{
real mag = 1.f / s;
return vector3f(x * mag, y * mag, z * mag);
}
// Cross vectors and return result
vector3f operator%(const vector3f& v)
{
return cross(v);
}
// Returns scalar(dot) product
vector3f operator*(const real s) const
{
return vector3f(s * x, s * y, s * z);
}
#ifdef MATRIX_H
// Multiply by matrix and return result
vector3f operator*(matrix m) const
{
return vector3f(x * m(0, 0) + y * m(1, 0) + z * m(2, 0),
x * m(0, 1) + y * m(1, 1) + z * m(2, 1),
x * m(0, 2) + y * m(1, 2) + z * m(2, 2));
}
#endif
// Subtract component-wise and return result
vector3f operator-(const vector3f& v) const
{
return vector3f(x - v.x, y - v.y, z - v.z);
}
// Add component-wise and return result
vector3f operator+(const vector3f& v) const
{
return vector3f(x + v.x, y + v.y, z + v.z);
}
// Negate components and return result
vector3f operator-() const
{
return vector3f(-x, -y, -z);
}
// Access components array-wise for modification
real& operator[](int i)
{
switch (i)
{
case 2:
return z;
break;
case 1:
return y;
break;
case 0:
return x;
break;
default:
std::cout << "ERROR::VECTOR::OUT OF BOUNDS REQUEST" << std::endl;
}
}
// Access components array-wise for reading
real operator[](int i) const
{
switch (i)
{
case 2:
return z;
break;
case 1:
return y;
break;
case 0:
return x;
break;
default:
std::cout << "ERROR::VECTOR::OUT OF BOUNDS REQUEST" << std::endl;
}
}
// Vector cross product
vector3f cross(const vector3f& v) const
{
return vector3f(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);
}
// Calculate component-wise product and return result
vector3f componentProduct(const vector3f& v) const
{
return vector3f(x * v.x, y * v.y, z * v.z);
}
// Calculate the unit vector and return result
vector3f unit() const
{
if (this->magnitude() == 0)
return vector3f(0);
return vector3f(*this / this->magnitude());
}
// Invert components
void invert()
{
x *= -1;
y *= -1;
z *= -1;
}
// Normalize the vector and set equal
void normalize()
{
(*this) = (*this).unit();
}
// Return magnitude of vector
real magnitude() const
{
return std::sqrtf(x * x + y * y + z * z);
}
// Calculate squared magnitude and return result
real squaredMagnitude()
{
return x * x + y * y + z * z;
}
// Borrowing this straight from Ian Millington
// Add given vector scaled by float and set equal
void addScaledVector(const vector3f& v, real t)
{
x += v.x * t;
y += v.y * t;
z += v.z * t;
}
real angleBetween(const vector3f& v) const
{
vector3f aU = this->unit();
vector3f bU = v.unit();
return acosf(aU * bU);
}
};
inline std::ostream& operator<<(std::ostream& os, const vector3f& v)
{
return os << v.x << " " << v.y << " " << v.z;
}
inline vector3f operator*(real s, const vector3f& v)
{
return vector3f(s * v.x, s * v.y, s * v.z);
}
// Or scalar product
inline real dot(const vector3f& o, const vector3f& v)
{
return o.x * v.x + o.y * v.y + o.z * v.z;
}
inline vector3f unitVector(vector3f v)
{
return v / v.magnitude();
}
inline vector3f reflect(const vector3f v, const vector3f n)
{
return v - 2.0f * dot(v, n) * n;
}
// Returns a viable direction in a unit sphere
inline vector3f randomInUnitSphere()
{
vector3f p;
do
{
p = 2.0f * vector3f(rand() / (RAND_MAX + 1.0), rand() / (RAND_MAX + 1.0), rand() / (RAND_MAX + 1.0)) - vector3f(1, 1, 1);
} while (p.squaredMagnitude() >= 1.0f);
return p;
}
struct dualVector {
dualVector()
{
wV = 0;
sV = 0;
}
dualVector(vector3f v) : wV{ v }
{
sV = vector3f(0);
}
// This stores the world vertex position
vector3f wV;
// This stores the screen position
vector3f sV;
};
inline void project(dualVector& vec, const vector3f& camera, float depth, int windowWidth, int windowHeight, int roadWidth)
{
// Transform the point to camera space
// Essentially, we just find the distance from the point to the camera
float cX = vec.wV.x - camera.x, cY = vec.wV.y - camera.y, cZ = vec.wV.z - camera.z;
float scaling = depth / cZ;
// Transform the point from camera space to screen space x:[0 : 1] y:[0 : 1] from the top-left to the bottom-right and apply proper scaling
vec.sV.x = round((windowWidth / 2.f) + (scaling * cX * windowWidth / 2.f));
vec.sV.y = round((windowHeight / 2.f) - (scaling * cY * windowHeight / 2.f));
vec.sV.z = round((scaling * (float)roadWidth * (float)windowWidth / 2.f));
}
// Based on the algorithm written by Ian Millington in "Game Physics Engine Development"
// Right-handed coordinate system
#ifdef MATRIX_H
inline void orthonormalBasis(vector3f* v1, vector3f* v2, vector3f* v3)
{
v1->normalize();
(*v3) = (*v1) % (*v2);
if (v3->squaredMagnitude() == 0.0)
return;
v3->normalize();
(*v2) = (*v3) % (*v1);
}
#endif
class vector4f
{
private:
public:
real x;
real y;
real z;
real w;
// Getters/Setters
real r() const
{
return x;
}
real g() const
{
return y;
}
real b() const
{
return z;
}
real a() const
{
return w;
}
// Outside function declerations
real dot(const vector4f& o, const vector4f& v);
// Constructors
vector4f() : x(0.f), y(0.f), z(0.f), w(1.f) {};
vector4f(real iX = 0, real iY = 0, real iZ = 0, real iW = 1) : x(iX), y(iY), z(iZ), w(iW) {};
// Deconstructor
~vector4f() {}
// Copy Constructor
vector4f(const vector4f& v) : x(v.x), y(v.y), z(v.z), w(v.w) {};
// Operator Overloads
vector4f& operator=(const vector4f& v)
{
x = v.x;
y = v.y;
z = v.z;
w = v.w;
return *this;
}
void operator+=(const vector4f& v)
{
x += v.x;
y += v.y;
z += v.z;
w += v.w;
}
void operator-=(const vector4f& v)
{
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
}
void operator*=(const real& s)
{
x *= s;
y *= s;
z *= s;
w *= s;
}
void operator/=(const real& s)
{
real mag = 1.f / s;
x = x * mag;
y = y * mag;
z = z * mag;
w = w * mag;
}
// Scalar(dot) product
real operator*(const vector4f& v) const
{
return x * v.x + y * v.y + z * v.z + w * v.w;
}
vector4f operator/(const real s) const
{
real mag = 1.f / s;
return vector4f(x * mag, y * mag, z * mag, w * mag);
}
vector4f operator*(const real s) const
{
return vector4f(s * x, s * y, x * z, w * z);
}
#ifdef MATRIX_H
vector4f operator*(matrix m) const
{
return vector4f(x * m(0, 0) + y * m(1, 0) + z * m(2, 0) + w * m(3, 0),
x * m(0, 1) + y * m(1, 1) + z * m(2, 1) + w * m(3, 1),
x * m(0, 2) + y * m(1, 2) + z * m(2, 2) + w * m(3, 2),
x * m(0, 3) + y * m(1, 3) + z * m(2, 3) + w * m(3, 3));
}
#endif
vector4f operator-(const vector4f& v) const
{
return vector4f(x - v.x, y - v.y, z - v.z, w - v.w);
}
vector4f operator+(const vector4f& v) const
{
return vector4f(x + v.x, y + v.y, z + v.z, w + v.w);
}
vector3f operator-() const
{
return vector3f(-x, -y, -z);
}
real& operator[](int i)
{
switch (i)
{
case 3:
return w;
break;
case 2:
return z;
break;
case 1:
return y;
break;
case 0:
return x;
break;
default:
std::cout << "ERROR::VECTOR::OUT OF BOUNDS REQUEST" << std::endl;
}
}
real operator[](int i) const
{
switch (i)
{
case 3:
return w;
break;
case 2:
return z;
break;
case 1:
return y;
break;
case 0:
return x;
break;
default:
std::cout << "ERROR::VECTOR::OUT OF BOUNDS REQUEST" << std::endl;
}
}
vector4f componentProduct(const vector4f& v) const
{
return vector4f(x * v.x, y * v.y, z * v.z, w * v.w);
}
vector4f unit()
{
return vector4f(*this / this->magnitude());
}
void invert()
{
x *= -1;
y *= -1;
z *= -1;
w *= -1;
}
void normalize()
{
(*this) = (*this).unit();
}
real magnitude()
{
return std::sqrtf(x * x + y * y + z * z + w * w);
}
real squaredMagnitude()
{
return x * x + y * y + z * z + w * w;
}
// Borrowing this straight from Ian Millington
// Add given vector scaled by float and set equal
void addScaledVector(const vector4f& v, real t)
{
x += v.x * t;
y += v.y * t;
z += v.z * t;
w += v.w * t;
}
};
inline real dot(const vector4f& o, const vector4f& v)
{
return o.x * v.x + o.y * v.y + o.z * v.z + o.w * v.w;
}
inline std::ostream& operator<<(std::ostream& os, const vector4f& v)
{
return os << v.x << " " << v.y << " " << v.z << " " << v.w;
}
inline vector4f operator*(real s, const vector4f& v)
{
return vector4f(s * v.x, s * v.y, s * v.z, s * v.w);
}
} // namespace rn
#endif | 18.878947 | 154 | 0.559985 | [
"vector",
"transform"
] |
9abfdd40c562d2ca3902f5f4f15f2881420d5833 | 8,081 | h | C | Module 1/B04920_Code/B04920_Code/B04920_10_FinalCode/roguelike_template/include/Level.h | PacktPublishing/Cpp-for-game-developers | 2e26319290dc469698745ab422ee64623ade8c43 | [
"MIT"
] | 7 | 2017-12-28T20:11:12.000Z | 2021-11-14T14:22:40.000Z | Module 1/B04920_Code/B04920_Code/B04920_10_FinalCode/roguelike_template/include/Level.h | PacktPublishing/Cpp-for-game-developers | 2e26319290dc469698745ab422ee64623ade8c43 | [
"MIT"
] | null | null | null | Module 1/B04920_Code/B04920_Code/B04920_10_FinalCode/roguelike_template/include/Level.h | PacktPublishing/Cpp-for-game-developers | 2e26319290dc469698745ab422ee64623ade8c43 | [
"MIT"
] | 3 | 2017-12-28T20:14:04.000Z | 2020-06-21T08:00:54.000Z | //-------------------------------------------------------------------------------------
// Level.h
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Written by Dale Green. Copyright (c) Packt Publishing. All rights reserved.
//-------------------------------------------------------------------------------------
#ifndef LEVEL_H
#define LEVEL_H
#include "Torch.h"
// Constants for the game grid size.
static int const GRID_WIDTH = 19;
static int const GRID_HEIGHT = 19;
// The width and height of each tile in pixels.
static int const TILE_SIZE = 50;
// The level tile type.
struct Tile {
TILE type; // The type of tile this is.
int columnIndex; // The column index of the tile.
int rowIndex; // The row index of the tile.
sf::Sprite sprite; // The tile sprite.
int H; // Heuristic / movement cost to goal.
int G; // Movement cost. (Total of entire path)
int F; // Estimated cost for full path. (G + H)
Tile* parentNode; // Node to reach this node.
};
class Level
{
public:
/**
* Default constructor.
*/
Level();
/**
* Constructor.
* A renderWindow is needed in order for the level to calculate its position.
* @param window The game window.
*/
Level(sf::RenderWindow& window);
/**
* Returns true if the given tile index is solid.
* @param columnIndex The tile's column index.
* @param rowIndex The tile's row index.
* @return True if the given tile is solid.
*/
bool IsSolid(int columnIndex, int rowIndex);
/**
* Sets the index of a given tile in the 2D game grid.
* This also changes the tile sprite, and is how tiles should be changed and set manually.
* @param columnIndex The tile's column index.
* @param rowIndex The tile's row index.
* @param index The new index of the tile.
*/
void SetTile(int columnIndex, int rowIndex, TILE tileType);
/**
* Draws the level grid to the provided render window.
* @param window The render window to draw the level to.
* @param timeDelta The time that has elapsed since the last update.
*/
void Draw(sf::RenderWindow &window, float timeDelta);
/**
* Gets the index of the given tile.
* @param columnIndex The column index of the tile to check.
* @param rowIndex The row index of the tile to check.
* @return The index of the given tile.
*/
TILE GetTileType(int columnIndex, int rowIndex) const;
/**
* Gets the tile at the given position.
* @param position The coordinates of the position to check.
* @return A pointer to the tile at the given location.
*/
Tile* GetTile(sf::Vector2f position);
/**
* Gets the tile at the given position in the level array.
* @param columnIndex The column that the tile is in.
* @param rowIndex The row that the tile is in.
* @return A pointer to the tile if valid.
*/
Tile* GetTile(int columnIndex, int rowIndex);
/**
* Gets the position of the level grid relative to the window.
* @return The position of the top-left of the level grid.
*/
sf::Vector2f GetPosition() const;
/**
* Gets a vector of all torches in the level.
* @return A vector of shared_ptrs containing all torches in the level.
*/
std::vector<std::shared_ptr<Torch>>* GetTorches();
/**
* Checks if a given tile is valid.
* @param columnIndex The column that the tile is in.
* @param rowIndex The column that the row is in.
* @return True if the tile is valid.
*/
bool TileIsValid(int columnIndex, int rowIndex);
/**
* Sets the overlay color of the level tiles.
* @param tileColor The new tile overlay color.
*/
void SetColor(sf::Color tileColor);
/**
* Gets the current floor number.
* @return The current floor.
*/
int GetFloorNumber() const;
/**
* Gets the current room number.
* @return The current room.
*/
int GetRoomNumber() const;
/**
* Gets the size of the level in terms of tiles.
* @return The size of the level grid.
*/
sf::Vector2i GetSize() const;
/**
* Gets the actual position of a tile in the game.
* @param columnIndex The column that the tile is in.
* @param rowIndex The column that the row is in.
* @return The position of the tile if valid.
*/
sf::Vector2f GetActualTileLocation(int columnIndex, int rowIndex);
/**
* Returns a valid spawn location from the current room.
* The position returned is relative to the game window.
* @return A suitable spawn location within the room.
*/
sf::Vector2f GetRandomSpawnLocation();
/**
* Resets the A* data of all level tiles.
*/
void ResetNodes();
/**
* Generates a random level.
*/
void GenerateLevel();
/**
* Spawns a given number of torches in the level.
* @param torchCount The number of torches to create.
*/
void SpawnTorches(int torchCount);
/**
* Returns the spawn location for the current level.
* @return The spawn location of the level.
*/
sf::Vector2f SpawnLocation() const;
/**
* Unlocks the door in the level.
*/
void UnlockDoor();
/**
* Return true if the given tile is a floor tile.
* @param columnIndex The column that the tile is in.
* @param rowIndex The column that the row is in.
* @return True if the given tile is a floor tile.
*/
bool IsFloor(int columnIndex, int rowIndex);
/**
* Return true if the given tile is a floor tile.
* @param tile The tile to check
* @return True if the given tile is a floor tile.
*/
bool IsFloor(const Tile& tile);
/**
* Returns the size of the tiles in the level.
* @return The size of the tiles in the level.
*/
int GetTileSize() const;
/**
* Adds a tile to the level.
* These tiles are essentially sprites with a unique index. Once added, they can be loaded via the LoadLevelFromFile() function by including its index in the level data.
* @param fileName The path to the sprite resource, relative to the project directory.
* @param tileType The type of tile that is being added.
* @return The index of the tile. This is used when building levels.
*/
int AddTile(std::string fileName, TILE tileType);
private:
/**
* Creates a path between two nodes in the recursive backtracker algorithm.
* @param columnIndex The column that the tile is in.
* @param rowIndex The column that the row is in.
*/
void CreatePath(int columnIndex, int rowIndex);
/**
* Adds a given number of randomly sized rooms to the level to create some open space.
*/
void CreateRooms(int roomCount);
/**
* Calculates the correct texture for each tile in the level.
*/
void CalculateTextures();
/**
* Generates an entry and exit point for the given level.
*/
void GenerateEntryExit();
/**
* Checks if a given tile is a wall block.
* @param columnIndex The column that the tile is in.
* @param rowIndex The column that the row is in.
* @return True if the given tile is a wall tile.
*/
bool IsWall(int columnIndex, int rowIndex);
private:
/**
* A 2D array that describes the level data.
* The type is Tile, which holds a sprite and an index.
*/
Tile m_grid[GRID_WIDTH][GRID_HEIGHT];
/**
* A vector off all the sprites in the level.
*/
std::vector<sf::Sprite> m_tileSprites;
/**
* The position of the level relative to the window.
* This is to the top-left of the level grid.
*/
sf::Vector2i m_origin;
/**
* The floor number that the player is currently on.
*/
int m_floorNumber;
/**
* The room number that the player is currently in.
*/
int m_roomNumber;
/**
* A 2D array that contains the room layout for the current floor.
*/
int m_roomLayout[3][10];
/**
* An array containing all texture IDs of the level tiles.
*/
int m_textureIDs[static_cast<int>(TILE::COUNT)];
/**
* The spawn location for the current level.
*/
sf::Vector2f m_spawnLocation;
/**
* The indices of the tile containing the levels door.
*/
sf::Vector2i m_doorTileIndices;
/**
* A vector of all tiles in the level.
*/
std::vector<std::shared_ptr<Torch>> m_torches;
};
#endif | 27.11745 | 169 | 0.672937 | [
"render",
"vector",
"solid"
] |
9ac0e9a78fe12a5096301ebd06a46076a181b14e | 31,461 | c | C | dlls/gdiplus/tests/region.c | devyn/wine | 76bb12558beaece005419feb98f024a1eb1f74e8 | [
"MIT"
] | 1 | 2016-05-08T19:53:43.000Z | 2016-05-08T19:53:43.000Z | dlls/gdiplus/tests/region.c | devyn/wine | 76bb12558beaece005419feb98f024a1eb1f74e8 | [
"MIT"
] | null | null | null | dlls/gdiplus/tests/region.c | devyn/wine | 76bb12558beaece005419feb98f024a1eb1f74e8 | [
"MIT"
] | null | null | null | /*
* Unit test suite for gdiplus regions
*
* Copyright (C) 2008 Huw Davies
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "windows.h"
#include "gdiplus.h"
#include "wingdi.h"
#include "wine/test.h"
#define RGNDATA_RECT 0x10000000
#define RGNDATA_PATH 0x10000001
#define RGNDATA_EMPTY_RECT 0x10000002
#define RGNDATA_INFINITE_RECT 0x10000003
#define RGNDATA_MAGIC 0xdbc01001
#define RGNDATA_MAGIC2 0xdbc01002
#define expect(expected, got) ok(got == expected, "Expected %.8x, got %.8x\n", expected, got)
#define expect_magic(value) ok(*value == RGNDATA_MAGIC || *value == RGNDATA_MAGIC2, "Expected a known magic value, got %8x\n", *value)
#define expect_dword(value, expected) ok(*(value) == expected, "expected %08x got %08x\n", expected, *(value))
static inline void expect_float(DWORD *value, FLOAT expected)
{
FLOAT valuef = *(FLOAT*)value;
ok(valuef == expected, "expected %f got %f\n", expected, valuef);
}
/* We get shorts back, not INTs like a GpPoint */
typedef struct RegionDataPoint
{
short X, Y;
} RegionDataPoint;
static void verify_region(HRGN hrgn, const RECT *rc)
{
union
{
RGNDATA data;
char buf[sizeof(RGNDATAHEADER) + sizeof(RECT)];
} rgn;
const RECT *rect;
DWORD ret;
ret = GetRegionData(hrgn, 0, NULL);
if (IsRectEmpty(rc))
ok(ret == sizeof(rgn.data.rdh), "expected sizeof(rdh), got %u\n", ret);
else
ok(ret == sizeof(rgn.data.rdh) + sizeof(RECT), "expected sizeof(rgn), got %u\n", ret);
if (!ret) return;
ret = GetRegionData(hrgn, sizeof(rgn), &rgn.data);
if (IsRectEmpty(rc))
ok(ret == sizeof(rgn.data.rdh), "expected sizeof(rdh), got %u\n", ret);
else
ok(ret == sizeof(rgn.data.rdh) + sizeof(RECT), "expected sizeof(rgn), got %u\n", ret);
trace("size %u, type %u, count %u, rgn size %u, bound (%d,%d-%d,%d)\n",
rgn.data.rdh.dwSize, rgn.data.rdh.iType,
rgn.data.rdh.nCount, rgn.data.rdh.nRgnSize,
rgn.data.rdh.rcBound.left, rgn.data.rdh.rcBound.top,
rgn.data.rdh.rcBound.right, rgn.data.rdh.rcBound.bottom);
if (rgn.data.rdh.nCount != 0)
{
rect = (const RECT *)rgn.data.Buffer;
trace("rect (%d,%d-%d,%d)\n", rect->left, rect->top, rect->right, rect->bottom);
ok(EqualRect(rect, rc), "rects don't match\n");
}
ok(rgn.data.rdh.dwSize == sizeof(rgn.data.rdh), "expected sizeof(rdh), got %u\n", rgn.data.rdh.dwSize);
ok(rgn.data.rdh.iType == RDH_RECTANGLES, "expected RDH_RECTANGLES, got %u\n", rgn.data.rdh.iType);
if (IsRectEmpty(rc))
{
ok(rgn.data.rdh.nCount == 0, "expected 0, got %u\n", rgn.data.rdh.nCount);
ok(rgn.data.rdh.nRgnSize == 0, "expected 0, got %u\n", rgn.data.rdh.nRgnSize);
}
else
{
ok(rgn.data.rdh.nCount == 1, "expected 1, got %u\n", rgn.data.rdh.nCount);
ok(rgn.data.rdh.nRgnSize == sizeof(RECT), "expected sizeof(RECT), got %u\n", rgn.data.rdh.nRgnSize);
}
ok(EqualRect(&rgn.data.rdh.rcBound, rc), "rects don't match\n");
}
static void test_getregiondata(void)
{
GpStatus status;
GpRegion *region, *region2;
RegionDataPoint *point;
UINT needed;
DWORD buf[100];
GpRect rect;
GpPath *path;
memset(buf, 0xee, sizeof(buf));
status = GdipCreateRegion(®ion);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionDataSize(region, &needed);
ok(status == Ok, "status %08x\n", status);
expect(20, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
ok(status == Ok, "status %08x\n", status);
expect(20, needed);
expect_dword(buf, 12);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_INFINITE_RECT);
status = GdipSetEmpty(region);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionDataSize(region, &needed);
ok(status == Ok, "status %08x\n", status);
expect(20, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
ok(status == Ok, "status %08x\n", status);
expect(20, needed);
expect_dword(buf, 12);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_EMPTY_RECT);
status = GdipSetInfinite(region);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionDataSize(region, &needed);
ok(status == Ok, "status %08x\n", status);
expect(20, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
ok(status == Ok, "status %08x\n", status);
expect(20, needed);
expect_dword(buf, 12);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_INFINITE_RECT);
status = GdipDeleteRegion(region);
ok(status == Ok, "status %08x\n", status);
rect.X = 10;
rect.Y = 20;
rect.Width = 100;
rect.Height = 200;
status = GdipCreateRegionRectI(&rect, ®ion);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionDataSize(region, &needed);
ok(status == Ok, "status %08x\n", status);
expect(36, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
ok(status == Ok, "status %08x\n", status);
expect(36, needed);
expect_dword(buf, 28);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_RECT);
expect_float(buf + 5, 10.0);
expect_float(buf + 6, 20.0);
expect_float(buf + 7, 100.0);
expect_float(buf + 8, 200.0);
rect.X = 50;
rect.Y = 30;
rect.Width = 10;
rect.Height = 20;
status = GdipCombineRegionRectI(region, &rect, CombineModeIntersect);
ok(status == Ok, "status %08x\n", status);
rect.X = 100;
rect.Y = 300;
rect.Width = 30;
rect.Height = 50;
status = GdipCombineRegionRectI(region, &rect, CombineModeXor);
ok(status == Ok, "status %08x\n", status);
rect.X = 200;
rect.Y = 100;
rect.Width = 133;
rect.Height = 266;
status = GdipCreateRegionRectI(&rect, ®ion2);
ok(status == Ok, "status %08x\n", status);
rect.X = 20;
rect.Y = 10;
rect.Width = 40;
rect.Height = 66;
status = GdipCombineRegionRectI(region2, &rect, CombineModeUnion);
ok(status == Ok, "status %08x\n", status);
status = GdipCombineRegionRegion(region, region2, CombineModeComplement);
ok(status == Ok, "status %08x\n", status);
rect.X = 400;
rect.Y = 500;
rect.Width = 22;
rect.Height = 55;
status = GdipCombineRegionRectI(region, &rect, CombineModeExclude);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionDataSize(region, &needed);
ok(status == Ok, "status %08x\n", status);
expect(156, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
ok(status == Ok, "status %08x\n", status);
expect(156, needed);
expect_dword(buf, 148);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 10);
expect_dword(buf + 4, CombineModeExclude);
expect_dword(buf + 5, CombineModeComplement);
expect_dword(buf + 6, CombineModeXor);
expect_dword(buf + 7, CombineModeIntersect);
expect_dword(buf + 8, RGNDATA_RECT);
expect_float(buf + 9, 10.0);
expect_float(buf + 10, 20.0);
expect_float(buf + 11, 100.0);
expect_float(buf + 12, 200.0);
expect_dword(buf + 13, RGNDATA_RECT);
expect_float(buf + 14, 50.0);
expect_float(buf + 15, 30.0);
expect_float(buf + 16, 10.0);
expect_float(buf + 17, 20.0);
expect_dword(buf + 18, RGNDATA_RECT);
expect_float(buf + 19, 100.0);
expect_float(buf + 20, 300.0);
expect_float(buf + 21, 30.0);
expect_float(buf + 22, 50.0);
expect_dword(buf + 23, CombineModeUnion);
expect_dword(buf + 24, RGNDATA_RECT);
expect_float(buf + 25, 200.0);
expect_float(buf + 26, 100.0);
expect_float(buf + 27, 133.0);
expect_float(buf + 28, 266.0);
expect_dword(buf + 29, RGNDATA_RECT);
expect_float(buf + 30, 20.0);
expect_float(buf + 31, 10.0);
expect_float(buf + 32, 40.0);
expect_float(buf + 33, 66.0);
expect_dword(buf + 34, RGNDATA_RECT);
expect_float(buf + 35, 400.0);
expect_float(buf + 36, 500.0);
expect_float(buf + 37, 22.0);
expect_float(buf + 38, 55.0);
status = GdipDeleteRegion(region2);
ok(status == Ok, "status %08x\n", status);
status = GdipDeleteRegion(region);
ok(status == Ok, "status %08x\n", status);
/* Try some paths */
status = GdipCreatePath(FillModeAlternate, &path);
ok(status == Ok, "status %08x\n", status);
GdipAddPathRectangle(path, 12.5, 13.0, 14.0, 15.0);
status = GdipCreateRegionPath(path, ®ion);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionDataSize(region, &needed);
ok(status == Ok, "status %08x\n", status);
expect(72, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
ok(status == Ok, "status %08x\n", status);
expect(72, needed);
expect_dword(buf, 64);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_PATH);
expect_dword(buf + 5, 0x00000030);
expect_magic((DWORD*)(buf + 6));
expect_dword(buf + 7, 0x00000004);
expect_dword(buf + 8, 0x00000000);
expect_float(buf + 9, 12.5);
expect_float(buf + 10, 13.0);
expect_float(buf + 11, 26.5);
expect_float(buf + 12, 13.0);
expect_float(buf + 13, 26.5);
expect_float(buf + 14, 28.0);
expect_float(buf + 15, 12.5);
expect_float(buf + 16, 28.0);
expect_dword(buf + 17, 0x81010100);
rect.X = 50;
rect.Y = 30;
rect.Width = 10;
rect.Height = 20;
status = GdipCombineRegionRectI(region, &rect, CombineModeIntersect);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionDataSize(region, &needed);
ok(status == Ok, "status %08x\n", status);
expect(96, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
ok(status == Ok, "status %08x\n", status);
expect(96, needed);
expect_dword(buf, 88);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 2);
expect_dword(buf + 4, CombineModeIntersect);
expect_dword(buf + 5, RGNDATA_PATH);
expect_dword(buf + 6, 0x00000030);
expect_magic((DWORD*)(buf + 7));
expect_dword(buf + 8, 0x00000004);
expect_dword(buf + 9, 0x00000000);
expect_float(buf + 10, 12.5);
expect_float(buf + 11, 13.0);
expect_float(buf + 12, 26.5);
expect_float(buf + 13, 13.0);
expect_float(buf + 14, 26.5);
expect_float(buf + 15, 28.0);
expect_float(buf + 16, 12.5);
expect_float(buf + 17, 28.0);
expect_dword(buf + 18, 0x81010100);
expect_dword(buf + 19, RGNDATA_RECT);
expect_float(buf + 20, 50.0);
expect_float(buf + 21, 30.0);
expect_float(buf + 22, 10.0);
expect_float(buf + 23, 20.0);
status = GdipDeleteRegion(region);
ok(status == Ok, "status %08x\n", status);
status = GdipDeletePath(path);
ok(status == Ok, "status %08x\n", status);
/* Test an empty path */
status = GdipCreatePath(FillModeAlternate, &path);
expect(Ok, status);
status = GdipCreateRegionPath(path, ®ion);
expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(36, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(36, needed);
expect_dword(buf, 28);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_PATH);
/* Second signature for pathdata */
expect_dword(buf + 5, 12);
expect_magic((DWORD*)(buf + 6));
expect_dword(buf + 7, 0);
expect_dword(buf + 8, 0x00004000);
status = GdipDeleteRegion(region);
expect(Ok, status);
/* Test a simple triangle of INTs */
status = GdipAddPathLine(path, 5, 6, 7, 8);
expect(Ok, status);
status = GdipAddPathLine(path, 8, 1, 5, 6);
expect(Ok, status);
status = GdipClosePathFigure(path);
expect(Ok, status);
status = GdipCreateRegionPath(path, ®ion);
expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(56, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(56, needed);
expect_dword(buf, 48);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3 , 0);
expect_dword(buf + 4 , RGNDATA_PATH);
expect_dword(buf + 5, 32);
expect_magic((DWORD*)(buf + 6));
expect_dword(buf + 7, 4);
expect_dword(buf + 8, 0x00004000); /* ?? */
point = (RegionDataPoint*)buf + 9;
expect(5, point[0].X);
expect(6, point[0].Y);
expect(7, point[1].X); /* buf + 10 */
expect(8, point[1].Y);
expect(8, point[2].X); /* buf + 11 */
expect(1, point[2].Y);
expect(5, point[3].X); /* buf + 12 */
expect(6, point[3].Y);
expect_dword(buf + 13, 0x81010100); /* 0x01010100 if we don't close the path */
status = GdipDeletePath(path);
expect(Ok, status);
status = GdipDeleteRegion(region);
expect(Ok, status);
/* Test a floating-point triangle */
status = GdipCreatePath(FillModeAlternate, &path);
expect(Ok, status);
status = GdipAddPathLine(path, 5.6, 6.2, 7.2, 8.9);
expect(Ok, status);
status = GdipAddPathLine(path, 8.1, 1.6, 5.6, 6.2);
expect(Ok, status);
status = GdipCreateRegionPath(path, ®ion);
expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(72, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(72, needed);
expect_dword(buf, 64);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_PATH);
expect_dword(buf + 5, 48);
expect_magic((DWORD*)(buf + 6));
expect_dword(buf + 7, 4);
expect_dword(buf + 8, 0);
expect_float(buf + 9, 5.6);
expect_float(buf + 10, 6.2);
expect_float(buf + 11, 7.2);
expect_float(buf + 12, 8.9);
expect_float(buf + 13, 8.1);
expect_float(buf + 14, 1.6);
expect_float(buf + 15, 5.6);
expect_float(buf + 16, 6.2);
status = GdipDeletePath(path);
expect(Ok, status);
status = GdipDeleteRegion(region);
expect(Ok, status);
/* Test for a path with > 4 points, and CombineRegionPath */
GdipCreatePath(FillModeAlternate, &path);
status = GdipAddPathLine(path, 50, 70.2, 60, 102.8);
expect(Ok, status);
status = GdipAddPathLine(path, 55.4, 122.4, 40.4, 60.2);
expect(Ok, status);
status = GdipAddPathLine(path, 45.6, 20.2, 50, 70.2);
expect(Ok, status);
rect.X = 20;
rect.Y = 25;
rect.Width = 60;
rect.Height = 120;
status = GdipCreateRegionRectI(&rect, ®ion);
expect(Ok, status);
status = GdipCombineRegionPath(region, path, CombineModeUnion);
expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(116, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(116, needed);
expect_dword(buf, 108);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 2);
expect_dword(buf + 4, CombineModeUnion);
expect_dword(buf + 5, RGNDATA_RECT);
expect_float(buf + 6, 20);
expect_float(buf + 7, 25);
expect_float(buf + 8, 60);
expect_float(buf + 9, 120);
expect_dword(buf + 10, RGNDATA_PATH);
expect_dword(buf + 11, 68);
expect_magic((DWORD*)(buf + 12));
expect_dword(buf + 13, 6);
expect_float(buf + 14, 0x0);
expect_float(buf + 15, 50);
expect_float(buf + 16, 70.2);
expect_float(buf + 17, 60);
expect_float(buf + 18, 102.8);
expect_float(buf + 19, 55.4);
expect_float(buf + 20, 122.4);
expect_float(buf + 21, 40.4);
expect_float(buf + 22, 60.2);
expect_float(buf + 23, 45.6);
expect_float(buf + 24, 20.2);
expect_float(buf + 25, 50);
expect_float(buf + 26, 70.2);
expect_dword(buf + 27, 0x01010100);
expect_dword(buf + 28, 0x00000101);
status = GdipDeletePath(path);
expect(Ok, status);
status = GdipDeleteRegion(region);
expect(Ok, status);
}
static void test_isinfinite(void)
{
GpStatus status;
GpRegion *region;
GpGraphics *graphics = NULL;
GpMatrix *m;
HDC hdc = GetDC(0);
BOOL res;
status = GdipCreateFromHDC(hdc, &graphics);
expect(Ok, status);
GdipCreateRegion(®ion);
GdipCreateMatrix2(3.0, 0.0, 0.0, 1.0, 20.0, 30.0, &m);
/* NULL arguments */
status = GdipIsInfiniteRegion(NULL, NULL, NULL);
expect(InvalidParameter, status);
status = GdipIsInfiniteRegion(region, NULL, NULL);
expect(InvalidParameter, status);
status = GdipIsInfiniteRegion(NULL, graphics, NULL);
expect(InvalidParameter, status);
status = GdipIsInfiniteRegion(NULL, NULL, &res);
expect(InvalidParameter, status);
status = GdipIsInfiniteRegion(region, NULL, &res);
expect(InvalidParameter, status);
res = FALSE;
status = GdipIsInfiniteRegion(region, graphics, &res);
expect(Ok, status);
expect(TRUE, res);
/* after world transform */
status = GdipSetWorldTransform(graphics, m);
expect(Ok, status);
res = FALSE;
status = GdipIsInfiniteRegion(region, graphics, &res);
expect(Ok, status);
expect(TRUE, res);
GdipDeleteMatrix(m);
GdipDeleteRegion(region);
GdipDeleteGraphics(graphics);
ReleaseDC(0, hdc);
}
static void test_isempty(void)
{
GpStatus status;
GpRegion *region;
GpGraphics *graphics = NULL;
HDC hdc = GetDC(0);
BOOL res;
status = GdipCreateFromHDC(hdc, &graphics);
expect(Ok, status);
GdipCreateRegion(®ion);
/* NULL arguments */
status = GdipIsEmptyRegion(NULL, NULL, NULL);
expect(InvalidParameter, status);
status = GdipIsEmptyRegion(region, NULL, NULL);
expect(InvalidParameter, status);
status = GdipIsEmptyRegion(NULL, graphics, NULL);
expect(InvalidParameter, status);
status = GdipIsEmptyRegion(NULL, NULL, &res);
expect(InvalidParameter, status);
status = GdipIsEmptyRegion(region, NULL, &res);
expect(InvalidParameter, status);
/* default is infinite */
res = TRUE;
status = GdipIsEmptyRegion(region, graphics, &res);
expect(Ok, status);
expect(FALSE, res);
status = GdipSetEmpty(region);
expect(Ok, status);
res = FALSE;
status = GdipIsEmptyRegion(region, graphics, &res);
expect(Ok, status);
expect(TRUE, res);
GdipDeleteRegion(region);
GdipDeleteGraphics(graphics);
ReleaseDC(0, hdc);
}
static void test_combinereplace(void)
{
GpStatus status;
GpRegion *region, *region2;
GpPath *path;
GpRectF rectf;
UINT needed;
DWORD buf[50];
rectf.X = rectf.Y = 0.0;
rectf.Width = rectf.Height = 100.0;
status = GdipCreateRegionRect(&rectf, ®ion);
expect(Ok, status);
/* replace with the same rectangle */
status = GdipCombineRegionRect(region, &rectf,CombineModeReplace);
expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(36, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(36, needed);
expect_dword(buf, 28);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_RECT);
/* replace with path */
status = GdipCreatePath(FillModeAlternate, &path);
expect(Ok, status);
status = GdipAddPathEllipse(path, 0.0, 0.0, 100.0, 250.0);
expect(Ok, status);
status = GdipCombineRegionPath(region, path, CombineModeReplace);
expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(156, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(156, needed);
expect_dword(buf, 148);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_PATH);
GdipDeletePath(path);
/* replace with infinite rect */
status = GdipCreateRegion(®ion2);
expect(Ok, status);
status = GdipCombineRegionRegion(region, region2, CombineModeReplace);
expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(20, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(20, needed);
expect_dword(buf, 12);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_INFINITE_RECT);
GdipDeleteRegion(region2);
/* more complex case : replace with a combined region */
status = GdipCreateRegionRect(&rectf, ®ion2);
expect(Ok, status);
status = GdipCreatePath(FillModeAlternate, &path);
expect(Ok, status);
status = GdipAddPathEllipse(path, 0.0, 0.0, 100.0, 250.0);
expect(Ok, status);
status = GdipCombineRegionPath(region2, path, CombineModeUnion);
expect(Ok, status);
GdipDeletePath(path);
status = GdipCombineRegionRegion(region, region2, CombineModeReplace);
expect(Ok, status);
GdipDeleteRegion(region2);
status = GdipGetRegionDataSize(region, &needed);
expect(Ok, status);
expect(180, needed);
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
expect(Ok, status);
expect(180, needed);
expect_dword(buf, 172);
trace("buf[1] = %08x\n", buf[1]);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 2);
expect_dword(buf + 4, CombineModeUnion);
GdipDeleteRegion(region);
}
static void test_fromhrgn(void)
{
GpStatus status;
GpRegion *region;
HRGN hrgn;
UINT needed;
DWORD buf[220];
RegionDataPoint *point;
/* NULL */
status = GdipCreateRegionHrgn(NULL, NULL);
expect(InvalidParameter, status);
status = GdipCreateRegionHrgn(NULL, ®ion);
expect(InvalidParameter, status);
status = GdipCreateRegionHrgn((HRGN)0xdeadbeef, ®ion);
todo_wine expect(InvalidParameter, status);
/* rectangle */
hrgn = CreateRectRgn(0, 0, 100, 10);
status = GdipCreateRegionHrgn(hrgn, ®ion);
todo_wine expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
todo_wine{
expect(Ok, status);
expect(56, needed);
}
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
todo_wine expect(Ok, status);
if(status == Ok){
todo_wine{
expect(56, needed);
expect_dword(buf, 48);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_PATH);
expect_dword(buf + 5, 0x00000020);
expect_magic((DWORD*)(buf + 6));
expect_dword(buf + 7, 0x00000004);
expect_dword(buf + 8, 0x00006000); /* ?? */
}
point = (RegionDataPoint*)buf + 9;
expect(0, point[0].X);
expect(0, point[0].Y);
todo_wine{
expect(100,point[1].X); /* buf + 10 */
expect(0, point[1].Y);
expect(100,point[2].X); /* buf + 11 */
expect(10, point[2].Y);
}
expect(0, point[3].X); /* buf + 12 */
todo_wine{
expect(10, point[3].Y);
expect_dword(buf + 13, 0x81010100); /* closed */
}
}
GdipDeleteRegion(region);
DeleteObject(hrgn);
/* ellipse */
hrgn = CreateEllipticRgn(0, 0, 100, 10);
status = GdipCreateRegionHrgn(hrgn, ®ion);
todo_wine expect(Ok, status);
status = GdipGetRegionDataSize(region, &needed);
todo_wine{
expect(Ok, status);
expect(216, needed);
}
status = GdipGetRegionData(region, (BYTE*)buf, sizeof(buf), &needed);
todo_wine{
expect(Ok, status);
expect(216, needed);
expect_dword(buf, 208);
expect_magic((DWORD*)(buf + 2));
expect_dword(buf + 3, 0);
expect_dword(buf + 4, RGNDATA_PATH);
expect_dword(buf + 5, 0x000000C0);
expect_magic((DWORD*)(buf + 6));
expect_dword(buf + 7, 0x00000024);
expect_dword(buf + 8, 0x00006000); /* ?? */
}
GdipDeleteRegion(region);
DeleteObject(hrgn);
}
static void test_gethrgn(void)
{
GpStatus status;
GpRegion *region, *region2;
GpPath *path;
GpGraphics *graphics;
HRGN hrgn;
HDC hdc=GetDC(0);
static const RECT empty_rect = {0,0,0,0};
static const RECT test_rect = {10, 11, 20, 21};
static const GpRectF test_rectF = {10.0, 11.0, 10.0, 10.0};
static const RECT scaled_rect = {20, 22, 40, 42};
static const RECT test_rect2 = {10, 21, 20, 31};
static const GpRectF test_rect2F = {10.0, 21.0, 10.0, 10.0};
static const RECT test_rect3 = {10, 11, 20, 31};
static const GpRectF test_rect3F = {10.0, 11.0, 10.0, 20.0};
status = GdipCreateFromHDC(hdc, &graphics);
ok(status == Ok, "status %08x\n", status);
status = GdipCreateRegion(®ion);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(NULL, graphics, &hrgn);
ok(status == InvalidParameter, "status %08x\n", status);
status = GdipGetRegionHRgn(region, graphics, NULL);
ok(status == InvalidParameter, "status %08x\n", status);
status = GdipGetRegionHRgn(region, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
ok(hrgn == NULL, "hrgn=%p\n", hrgn);
DeleteObject(hrgn);
status = GdipGetRegionHRgn(region, graphics, &hrgn);
ok(status == Ok, "status %08x\n", status);
ok(hrgn == NULL, "hrgn=%p\n", hrgn);
DeleteObject(hrgn);
status = GdipSetEmpty(region);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &empty_rect);
DeleteObject(hrgn);
status = GdipCreatePath(FillModeAlternate, &path);
ok(status == Ok, "status %08x\n", status);
status = GdipAddPathRectangle(path, 10.0, 11.0, 10.0, 10.0);
ok(status == Ok, "status %08x\n", status);
status = GdipCreateRegionPath(path, ®ion2);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region2, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &test_rect);
DeleteObject(hrgn);
/* resulting HRGN is in device coordinates */
status = GdipScaleWorldTransform(graphics, 2.0, 2.0, MatrixOrderPrepend);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region2, graphics, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &scaled_rect);
DeleteObject(hrgn);
status = GdipCombineRegionRect(region2, &test_rectF, CombineModeReplace);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region2, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &test_rect);
DeleteObject(hrgn);
status = GdipGetRegionHRgn(region2, graphics, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &scaled_rect);
DeleteObject(hrgn);
status = GdipSetInfinite(region);
ok(status == Ok, "status %08x\n", status);
status = GdipCombineRegionRect(region, &test_rectF, CombineModeIntersect);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &test_rect);
DeleteObject(hrgn);
status = GdipCombineRegionRect(region, &test_rectF, CombineModeReplace);
ok(status == Ok, "status %08x\n", status);
status = GdipCombineRegionRect(region, &test_rect2F, CombineModeUnion);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &test_rect3);
DeleteObject(hrgn);
status = GdipCombineRegionRect(region, &test_rect3F, CombineModeReplace);
ok(status == Ok, "status %08x\n", status);
status = GdipCombineRegionRect(region, &test_rect2F, CombineModeXor);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &test_rect);
DeleteObject(hrgn);
status = GdipCombineRegionRect(region, &test_rect3F, CombineModeReplace);
ok(status == Ok, "status %08x\n", status);
status = GdipCombineRegionRect(region, &test_rectF, CombineModeExclude);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &test_rect2);
DeleteObject(hrgn);
status = GdipCombineRegionRect(region, &test_rectF, CombineModeReplace);
ok(status == Ok, "status %08x\n", status);
status = GdipCombineRegionRect(region, &test_rect3F, CombineModeComplement);
ok(status == Ok, "status %08x\n", status);
status = GdipGetRegionHRgn(region, NULL, &hrgn);
ok(status == Ok, "status %08x\n", status);
verify_region(hrgn, &test_rect2);
DeleteObject(hrgn);
status = GdipDeletePath(path);
ok(status == Ok, "status %08x\n", status);
status = GdipDeleteRegion(region);
ok(status == Ok, "status %08x\n", status);
status = GdipDeleteRegion(region2);
ok(status == Ok, "status %08x\n", status);
status = GdipDeleteGraphics(graphics);
ok(status == Ok, "status %08x\n", status);
ReleaseDC(0, hdc);
}
START_TEST(region)
{
struct GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
gdiplusStartupInput.GdiplusVersion = 1;
gdiplusStartupInput.DebugEventCallback = NULL;
gdiplusStartupInput.SuppressBackgroundThread = 0;
gdiplusStartupInput.SuppressExternalCodecs = 0;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
test_getregiondata();
test_isinfinite();
test_isempty();
test_combinereplace();
test_fromhrgn();
test_gethrgn();
GdiplusShutdown(gdiplusToken);
}
| 33.116842 | 134 | 0.637074 | [
"transform"
] |
9ac157f82c2a711f1726a1598805ef2d21ae8bef | 8,516 | h | C | C++/Algorithms and data structures/lr5/laboratory_work_5/hash_table/customvector.h | po4yka/elementary-education-projects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | 1 | 2020-09-01T20:22:30.000Z | 2020-09-01T20:22:30.000Z | C++/Algorithms and data structures/lr5/laboratory_work_5/hash_table/customvector.h | po4yka/EducationProjects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | null | null | null | C++/Algorithms and data structures/lr5/laboratory_work_5/hash_table/customvector.h | po4yka/EducationProjects | f525a41eef2dee98e2a2ff8a7d063fac747d0d4b | [
"MIT"
] | null | null | null | #ifndef CUSTOMVECTOR_H
#define CUSTOMVECTOR_H
#include "allheaders.h"
namespace lrstruct
{
struct out_of_range {};
template<class T> class Vector
{
public:
/* ----- CONSTRUCTORS ----- */
// Default constructor
Vector();
explicit Vector(size_t s);
// Copy constructor
Vector(const Vector& arg);
// Copy assingment
Vector<T>& operator=(const Vector<T>& arg);
// Destructor
~Vector();
/* -------- ITERATORS --------*/
class iterator;
iterator begin();
const iterator begin() const;
iterator end();
const iterator end() const;
const iterator cbegin() const;
const iterator cend() const;
/* -------- CAPACITY -------- */
bool empty() const;
// Returns size of allocated storate capacity
size_t capacity() const;
// Requests a change in capacity
// reserve() will never decrase the capacity.
void reserve(int newmalloc);
// Changes the Vector's size.
// If the newsize is smaller, the last elements will be lost.
// Has a default value param for custom values when resizing.
void resize(int newsize, T val = T());
// Returns the size of the Vector (number of elements).
size_t size() const;
// Returns the maximum number of elements the Vector can hold
size_t max_size() const;
// Reduces capcity to fit the size
void shrink_to_fit();
/* -------- MODIFIERS --------*/
// Removes all elements from the Vector
// Capacity is not changed.
void clear();
// Inserts element at the back
void push_back(const T& d);
// Removes the last element from the Vector
void pop_back();
/* ----- ELEMENT ACCESS ----- */
// Access elements with bounds checking
T& at(int n);
// Access elements with bounds checking for constant vectors.
const T& at(int n) const;
// Access elements, no bounds checking
T& operator[](int i);
// Access elements, no bounds checking
const T& operator[](int i) const;
// Returns a reference to the first element
T& front();
// Returns a reference to the first element
const T& front() const;
// Returns a reference to the last element
T& back();
// Returns a reference to the last element
const T& back() const;
// Returns a pointer to the array used by Vector
T* data();
// Returns a pointer to the array used by Vector
const T* data() const;
private:
size_t _size; // Number of elements in vector
T* _elements; // Pointer to first element of vector
size_t _space; // Total space used by Vector including
// elements and free space.
};
template<class T> class Vector<T>::iterator
{
public:
iterator(T* p)
:_curr(p)
{}
iterator& operator++()
{
_curr++;
return *this;
}
iterator& operator--()
{
_curr--;
return *this;
}
T& operator*()
{
return *_curr;
}
bool operator==(const iterator& b) const
{
return *_curr == *b._curr;
}
bool operator!=(const iterator& b) const
{
return *_curr != *b._curr;
}
private:
T* _curr;
};
// Constructors/Destructor
template<class T>
Vector<T>::Vector()
:_size(0), _elements(0), _space(0)
{}
template<class T>
inline Vector<T>::Vector(size_t s)
:_size(s), _elements(new T[s]), _space(s)
{
for (int index = 0; index < _size; ++index)
_elements[index] = T();
}
template<class T>
inline Vector<T>::Vector(const Vector & arg)
:_size(arg._size), _elements(new T[arg._size])
{
for (size_t index = 0; index < arg._size; ++index)
_elements[index] = arg._elements[index];
}
template<class T>
inline Vector<T>& Vector<T>::operator=(const Vector<T>& a)
{
if (this == &a) return *this; // Self-assingment not work needed
// Current Vector has enough space, so there is no need for new allocation
if (a._size <= _space)
{
for (int index = 0; index < a._size; ++index)
{
_elements[index] = a._elements[index];
_size = a._size;
return *this;
}
}
T* p = new T[a._size];
for (int index = 0; index < a._size; ++index)
p[index] = a._elements[index];
delete[] _elements;
_size = a._size;
_space = a._size;
_elements = p;
return *this;
}
template<class T>
Vector<T>::~Vector()
{
delete[] _elements;
}
// Iterators
template<class T>
inline typename Vector<T>::iterator Vector<T>::begin()
{
return Vector<T>::iterator(&_elements[0]);
}
template<class T>
inline const typename Vector<T>::iterator Vector<T>::begin() const
{
return Vector<T>::iterator(&_elements[0]);
}
template<class T>
inline typename Vector<T>::iterator Vector<T>::end()
{
return Vector<T>::iterator(&_elements[_size]);
}
template<class T>
inline const typename Vector<T>::iterator Vector<T>::end() const
{
return Vector<T>::iterator(&_elements[_size]);
}
template<class T>
inline const typename Vector<T>::iterator Vector<T>::cbegin() const
{
return Vector<T>::iterator(&_elements[0]);
}
template<class T>
inline const typename Vector<T>::iterator Vector<T>::cend() const
{
return Vector<T>::iterator(&_elements[_size]);
}
// Capacity
template<class T>
inline bool Vector<T>::empty() const
{
return (_size == 0);
}
template<class T>
inline size_t Vector<T>::capacity() const
{
return _space;
}
template<class T>
inline void Vector<T>::reserve(int newalloc)
{
if (static_cast<size_t>(newalloc) <= _space) return;
T* p = new T[newalloc];
for (size_t i = 0; i < _size; ++i)
p[i] = _elements[i];
delete[] _elements;
_elements = p;
_space = newalloc;
}
template<class T>
inline void Vector<T>::resize(int newsize, T val)
{
// DON'T TOUCH: VIRTUAL CLASS
Q_UNUSED(val)
reserve(newsize);
for (int index = _size; index < newsize; ++index)
_elements[index] = T();
_size = newsize;
}
template<class T>
inline size_t Vector<T>::size() const
{
return _size;
}
// Modifiers
template<class T>
inline void Vector<T>::push_back(const T& d)
{
if (_space == 0)
reserve(8);
else if (_size == _space)
reserve(2 * _space);
_elements[_size] = d;
++_size;
}
// Accessors
template<class T>
inline T & Vector<T>::at(int n)
{
if (n < 0 || _size <= static_cast<size_t>(n)) throw out_of_range();
return _elements[n];
}
template<class T>
inline const T & Vector<T>::at(int n) const
{
if (n < 0 || _size <= n) throw out_of_range();
return _elements[n];
}
template<class T>
inline T & Vector<T>::operator[](int i)
{
return _elements[i];
}
template<class T>
inline const T & Vector<T>::operator[](int i) const
{
return _elements[i];
}
template<class T>
inline T& Vector<T>::front()
{
return _elements[0];
}
template<class T>
inline const T& Vector<T>::front() const
{
return _elements[0];
}
template<class T>
inline T& Vector<T>::back()
{
return _elements[_size - 1];
}
template<class T>
inline const T& Vector<T>::back() const
{
return _elements[_size - 1];
}
template<class T>
inline T* Vector<T>::data()
{
return _elements;
}
template<class T>
inline const T* Vector<T>::data() const
{
return _elements;
}
}
#endif // CUSTOMVECTOR_H
| 21.669211 | 114 | 0.529004 | [
"vector"
] |
9ac2e634ed3601e7613d2cee319aef82329f3a33 | 6,554 | h | C | include/rvshsa.h | Umio-Yasuno/ROCmValidationSuite | e2aec8bbba87c1a5c6f69fc4aa7d6d7eba652b5f | [
"MIT"
] | 30 | 2018-08-30T12:56:51.000Z | 2022-03-11T02:50:41.000Z | include/rvshsa.h | Umio-Yasuno/ROCmValidationSuite | e2aec8bbba87c1a5c6f69fc4aa7d6d7eba652b5f | [
"MIT"
] | 130 | 2018-08-29T07:06:41.000Z | 2022-03-30T07:08:54.000Z | include/rvshsa.h | Umio-Yasuno/ROCmValidationSuite | e2aec8bbba87c1a5c6f69fc4aa7d6d7eba652b5f | [
"MIT"
] | 32 | 2019-02-13T15:29:38.000Z | 2022-03-10T21:24:40.000Z | /********************************************************************************
*
* Copyright (c) 2018 ROCm Developer Tools
*
* MIT LICENSE:
* 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 INCLUDE_RVSHSA_H_
#define INCLUDE_RVSHSA_H_
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <algorithm>
#include <cctype>
#include <sstream>
#include <limits>
#include <string>
#include <vector>
#include <iomanip>
#include "hsa/hsa.h"
#include "hsa/hsa_ext_amd.h"
using std::string;
using std::vector;
#ifdef TRACEHSA
#define RVSHSATRACE_ rvs::lp::Log(std::string(__FILE__)+" "+__func__+":"\
+std::to_string(__LINE__), rvs::logtrace);
#else
#define RVSHSATRACE_
#endif
namespace rvs {
/**
* @class linkinfo_s
* @ingroup RVS
*
* @brief Utility class used to store HSA agent information
*
*/
typedef struct linkinfo_s {
//! NUMA distance of this hop
uint32_t distance;
//! link type of this hop (as string)
std::string strtype;
//! link type of this hop
hsa_amd_link_info_type_t etype;
} linkinfo_t;
/**
* @class hsa
* @ingroup RVS
*
* @brief Wrapper class for HSA functionality needed for rvs tests
*
*/
class hsa {
public:
//! Default constructor
hsa();
//! Default destructor
virtual ~hsa();
/**
* @class AgentInformation
* @ingroup RVS
*
* @brief Utility class used to store HSA agent information
*
*/
struct AgentInformation {
//! HSA agent handle
hsa_agent_t agent;
//! agent name
string agent_name;
//! device type, can be "GPU" or "CPU"
string agent_device_type;
//! NUMA node this agent belongs to
uint32_t node;
//! system memory pool
hsa_amd_memory_pool_t sys_pool;
/** vector of memory pool HSA handles as reported during mem pool
* enumeration
**/
vector<hsa_amd_memory_pool_t> mem_pool_list;
//! vecor of mem pools max sizes (index alligned with mem_pool_list)
vector<size_t> max_size_list;
};
//! constant for "no connection" distance value
static const uint32_t NO_CONN = 0xFFFFFFFF;
//! list of test transfer sizes
const uint32_t DEFAULT_SIZE_LIST[20] = { 1 * 1024,
2 * 1024,
4 * 1024,
8 * 1024,
16 * 1024,
32 * 1024,
64 * 1024,
128 * 1024,
256 * 1024,
512 * 1024,
1 * 1024 * 1024,
2 * 1024 * 1024,
4 * 1024 * 1024,
8 * 1024 * 1024,
16 * 1024 * 1024,
32 * 1024 * 1024,
64 * 1024 * 1024,
128 * 1024 * 1024,
256 * 1024 * 1024,
512 * 1024 * 1024 };
//! same as DEFAULT_SIZE_LIST but as std::vector
vector<uint32_t> size_list;
//! array of all found HSA agents
vector<AgentInformation> agent_list;
//! array of HSA GPU agents
vector<AgentInformation> gpu_list;
//! array of HSA CPU agents
vector<AgentInformation> cpu_list;
public:
static void Init();
static void Terminate();
static rvs::hsa* Get();
int FindAgent(uint32_t Node);
int Allocate(int SrcAgent, int DstAgent, size_t Size,
hsa_amd_memory_pool_t* pSrcPool, void** SrcBuff,
hsa_amd_memory_pool_t* pDstPool, void** DstBuff);
int SendTraffic(uint32_t SrcNode, uint32_t DstNode,
size_t Size, bool bidirectional,
double* Duration);
int GetPeerStatus(uint32_t SrcNode, uint32_t DstNode);
int GetPeerStatusAgent(const AgentInformation& SrcAgent,
const AgentInformation& DstAgent);
int GetLinkInfo(uint32_t SrcNode, uint32_t DstNode,
uint32_t* pDistance, std::vector<linkinfo_t>* pInfoarr);
double GetCopyTime(bool bidirectional,
hsa_signal_t signal_fwd, hsa_signal_t signal_rev);
static void print_hsa_status(const char* message, hsa_status_t st);
static void print_hsa_status(const char* file, int line,
const char* function, hsa_status_t st);
static void print_hsa_status(const char* file,
int line,
const char* function,
const char* msg,
hsa_status_t st);
static bool check_link_type(const std::vector<rvs::linkinfo_t>& arrLinkInfo,
int LinkType);
void PrintTopology();
protected:
void InitAgents();
static hsa_status_t ProcessAgent(hsa_agent_t agent, void* data);
static hsa_status_t ProcessMemPool(hsa_amd_memory_pool_t pool, void* data);
protected:
//! pointer to RVS HSA singleton
static rvs::hsa* pDsc;
};
} // namespace rvs
#endif // INCLUDE_RVSHSA_H_
| 33.610256 | 82 | 0.563015 | [
"vector"
] |
9ac792194d09407cf8875a32cecb70f973e1c1c9 | 1,197 | h | C | INaturalistIOS/ExploreUpdateRealm.h | myronjwells/INaturalistIOS | ce0a70c7b791d2701b1e2854ccc47b4866c9a5f7 | [
"MIT"
] | 105 | 2015-01-29T14:37:03.000Z | 2022-03-28T01:29:59.000Z | INaturalistIOS/ExploreUpdateRealm.h | myronjwells/INaturalistIOS | ce0a70c7b791d2701b1e2854ccc47b4866c9a5f7 | [
"MIT"
] | 566 | 2015-01-01T00:00:54.000Z | 2022-03-04T20:27:10.000Z | INaturalistIOS/ExploreUpdateRealm.h | myronjwells/INaturalistIOS | ce0a70c7b791d2701b1e2854ccc47b4866c9a5f7 | [
"MIT"
] | 41 | 2015-01-19T17:10:49.000Z | 2021-07-28T14:27:41.000Z | //
// ExploreUpdateRealm.h
// iNaturalist
//
// Created by Alex Shepard on 10/17/16.
// Copyright © 2016 iNaturalist. All rights reserved.
//
#import <Realm/Realm.h>
#import "ExploreUpdate.h"
#import "ExploreUserRealm.h"
#import "ExploreCommentRealm.h"
#import "ExploreIdentificationRealm.h"
@interface ExploreUpdateRealm : RLMObject
@property NSDate *createdAt;
@property NSInteger updateId;
@property ExploreIdentificationRealm *identification;
@property ExploreCommentRealm *comment;
@property NSInteger resourceOwnerId;
@property NSInteger resourceId;
// inat-wide sense of whether the update has been seen
// locally, this means whether it's been seen in the updates list view
// tab and app badging are computed from this
@property BOOL viewed;
// local sense of whether the update has been seen
// locally, this means whether it's been seen in the updates detail view
// there's a special visual treatment for this state
// this value may get overwritten by the inat-wide sense of
// viewed on RLMRealm -addOrUpdate
@property BOOL viewedLocally;
+ (RLMResults *)updatesForObservationId:(NSInteger)observationId;;
- (instancetype)initWithMantleModel:(ExploreUpdate *)model;
@end
| 29.195122 | 72 | 0.779449 | [
"model"
] |
9acc4651d089a5b389c3cb7f3769d2dcf3d26194 | 10,749 | h | C | src/ir/attr_functor.h | twlostow/incubator-tvm | 997a14eda9aec3b343e742e55c3018f9dc23d8c3 | [
"Apache-2.0"
] | null | null | null | src/ir/attr_functor.h | twlostow/incubator-tvm | 997a14eda9aec3b343e742e55c3018f9dc23d8c3 | [
"Apache-2.0"
] | null | null | null | src/ir/attr_functor.h | twlostow/incubator-tvm | 997a14eda9aec3b343e742e55c3018f9dc23d8c3 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file attr_functor.h
* \brief A way to define arbitrary function signature
* with dispatch on common attributes.
*
* Common attributes include:
* - int, float, str constants
* - array of attributes
* - map of attributes
*/
#ifndef TVM_IR_ATTR_FUNCTOR_H_
#define TVM_IR_ATTR_FUNCTOR_H_
#include <tvm/node/functor.h>
#include <tvm/tir/expr.h>
#include <utility>
namespace tvm {
template <typename FType>
class AttrFunctor;
#define ATTR_FUNCTOR_DEFAULT \
{ return VisitAttrDefault_(op, std::forward<Args>(args)...); }
#define ATTR_FUNCTOR_DISPATCH(OP) \
vtable.template set_dispatch<OP>( \
[](const ObjectRef& n, TSelf* self, Args... args) { \
return self->VisitAttr_(static_cast<const OP*>(n.get()), \
std::forward<Args>(args)...); \
}); \
// A functor for common attribute information.
template <typename R, typename... Args>
class AttrFunctor<R(const ObjectRef& n, Args...)> {
private:
using TSelf = AttrFunctor<R(const ObjectRef& n, Args...)>;
using FType = tvm::NodeFunctor<R(const ObjectRef& n, TSelf* self, Args...)>;
public:
/*! \brief the result type of this functor */
using result_type = R;
/*! \brief virtual destructor */
virtual ~AttrFunctor() {}
/*!
* \brief The functor call.
* \param n The expression node.
* \param args Additional arguments.
* \return The result of the call
*/
virtual R VisitAttr(const ObjectRef& n, Args... args) {
static FType vtable = InitVTable();
if (vtable.can_dispatch(n)) {
return vtable(n, this, std::forward<Args>(args)...);
} else {
return VisitAttrDefault_(n.get(), std::forward<Args>(args)...);
}
}
virtual R VisitAttrDefault_(const Object* node, Args... args) = 0;
virtual R VisitAttr_(const ArrayNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const StrMapNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::IntImmNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::FloatImmNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::StringImmNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
// deep comparison of symbolic integer expressions.
virtual R VisitAttr_(const tir::VarNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::SizeVarNode* op, Args... args) {
return VisitAttr_(static_cast<const tir::VarNode*>(op), std::forward<Args>(args)...);
}
virtual R VisitAttr_(const tir::AddNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::SubNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::MulNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::DivNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::ModNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::FloorDivNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::FloorModNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::MinNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::MaxNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::GENode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::GTNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::LTNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::LENode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::EQNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::NENode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::AndNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::OrNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::NotNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::CastNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::CallNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
virtual R VisitAttr_(const tir::SelectNode* op, Args... args) ATTR_FUNCTOR_DEFAULT;
private:
// initialize the vtable.
static FType InitVTable() {
using namespace tir;
FType vtable;
// Set dispatch
ATTR_FUNCTOR_DISPATCH(StrMapNode);
ATTR_FUNCTOR_DISPATCH(ArrayNode);
ATTR_FUNCTOR_DISPATCH(IntImmNode);
ATTR_FUNCTOR_DISPATCH(FloatImmNode);
ATTR_FUNCTOR_DISPATCH(StringImmNode);
ATTR_FUNCTOR_DISPATCH(VarNode);
ATTR_FUNCTOR_DISPATCH(SizeVarNode);
ATTR_FUNCTOR_DISPATCH(AddNode);
ATTR_FUNCTOR_DISPATCH(SubNode);
ATTR_FUNCTOR_DISPATCH(MulNode);
ATTR_FUNCTOR_DISPATCH(DivNode);
ATTR_FUNCTOR_DISPATCH(ModNode);
ATTR_FUNCTOR_DISPATCH(FloorDivNode);
ATTR_FUNCTOR_DISPATCH(FloorModNode);
ATTR_FUNCTOR_DISPATCH(MinNode);
ATTR_FUNCTOR_DISPATCH(MaxNode);
ATTR_FUNCTOR_DISPATCH(GENode);
ATTR_FUNCTOR_DISPATCH(GTNode);
ATTR_FUNCTOR_DISPATCH(LENode);
ATTR_FUNCTOR_DISPATCH(LTNode);
ATTR_FUNCTOR_DISPATCH(EQNode);
ATTR_FUNCTOR_DISPATCH(NENode);
ATTR_FUNCTOR_DISPATCH(AndNode);
ATTR_FUNCTOR_DISPATCH(OrNode);
ATTR_FUNCTOR_DISPATCH(NotNode);
ATTR_FUNCTOR_DISPATCH(CastNode);
ATTR_FUNCTOR_DISPATCH(CallNode);
ATTR_FUNCTOR_DISPATCH(SelectNode);
return vtable;
}
};
class AttrsEqualHandler :
protected AttrFunctor<bool(const ObjectRef&, const ObjectRef&)> {
public:
/*!
* \brief Check if lhs equals rhs
* \param lhs The left operand.
* \param rhs The right operand.
*/
bool Equal(const ObjectRef& lhs, const ObjectRef& rhs);
protected:
bool VisitAttrDefault_(const Object* lhs, const ObjectRef& other) final;
bool VisitAttr_(const ArrayNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const StrMapNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::IntImmNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::FloatImmNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::StringImmNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::AddNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::SubNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::MulNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::DivNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::ModNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::FloorDivNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::FloorModNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::MinNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::MaxNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::GENode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::GTNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::LTNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::LENode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::EQNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::NENode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::AndNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::OrNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::NotNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::CastNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::CallNode* lhs, const ObjectRef& other) final;
bool VisitAttr_(const tir::SelectNode* lhs, const ObjectRef& other) final;
};
class AttrsHashHandler :
protected AttrFunctor<size_t(const ObjectRef&)> {
public:
/*!
* \brief Get hash value of node
* \param node The node to be hashed.
*/
size_t Hash(const ObjectRef& node) {
if (!node.defined()) return 0;
return this->VisitAttr(node);
}
protected:
size_t VisitAttrDefault_(const Object* lhs) final;
size_t VisitAttr_(const tir::IntImmNode* lhs) final;
size_t VisitAttr_(const tir::FloatImmNode* lhs) final;
size_t VisitAttr_(const tir::StringImmNode* lhs) final;
size_t VisitAttr_(const ArrayNode* lhs) final;
size_t VisitAttr_(const StrMapNode* lhs) final;
size_t VisitAttr_(const tir::AddNode* op) final;
size_t VisitAttr_(const tir::SubNode* op) final;
size_t VisitAttr_(const tir::MulNode* op) final;
size_t VisitAttr_(const tir::DivNode* op) final;
size_t VisitAttr_(const tir::ModNode* op) final;
size_t VisitAttr_(const tir::FloorDivNode* op) final;
size_t VisitAttr_(const tir::FloorModNode* op) final;
size_t VisitAttr_(const tir::MinNode* op) final;
size_t VisitAttr_(const tir::MaxNode* op) final;
size_t VisitAttr_(const tir::GENode* op) final;
size_t VisitAttr_(const tir::GTNode* op) final;
size_t VisitAttr_(const tir::LENode* op) final;
size_t VisitAttr_(const tir::LTNode* op) final;
size_t VisitAttr_(const tir::EQNode* op) final;
size_t VisitAttr_(const tir::NENode* op) final;
size_t VisitAttr_(const tir::AndNode* op) final;
size_t VisitAttr_(const tir::OrNode* op) final;
size_t VisitAttr_(const tir::NotNode* op) final;
size_t VisitAttr_(const tir::CastNode* op) final;
size_t VisitAttr_(const tir::CallNode* op) final;
size_t VisitAttr_(const tir::SelectNode* op) final;
/*!
* \brief alias of dmlc::HashCombine
* \param lhs The first hash value.
* \param rhs The second hash value.
*/
static size_t Combine(size_t lhs, size_t rhs) {
return dmlc::HashCombine(lhs, rhs);
}
};
} // namespace tvm
#endif // TVM_IR_ATTR_FUNCTOR_H_
| 44.60166 | 89 | 0.717927 | [
"object"
] |
9acc5366d53aabf051d01253d762474ef335c957 | 5,400 | c | C | nitan/kungfu/skill/riyue-bian.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/kungfu/skill/riyue-bian.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/kungfu/skill/riyue-bian.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // riyue-bian.c 日月鞭法
#include <ansi.h>
inherit SKILL;
string type() { return "martial"; }
string martialtype() { return "skill"; }
mapping *action = ({
([ "action": "$N端坐不動,一招"HIY"「裂石式」"NOR",手中$w抖得筆直,對準$n的胸腹要害連刺數鞭",
"lvl" : 0,
"skill_name" : "裂石式",
]),
([ "action": "$N身形一轉,一招"HIB"「斷川式」"NOR",手中$w如矯龍般騰空一卷,猛地向$n劈頭打下",
"lvl" : 60,
"skill_name" : "斷川式",
]),
([ "action": "$N力貫鞭梢,一招"HIC"「破雲式」"NOR",手中$w舞出滿天鞭影,排山倒海般掃向$n全身",
"lvl" : 90,
"skill_name" : "破雲式",
]),
([ "action":"$N力貫鞭梢,一招"HIW"「分海式」"NOR",手中$w舞出滿天鞭影,排山倒海般掃向$n全身",
"lvl" : 100,
"skill_name" : "分海式",
]),
([ "action":"$N力貫鞭梢,一招"HIG"「裂空式」"NOR",手中$w舞出滿天鞭影,排山倒海般掃向$n全身",
"lvl" : 110,
"skill_name" : "裂空式",
]),
([ "action":"$N力貫鞭梢,一招"HIY"「佛光普照」"NOR",手中$w舞出滿天鞭影,排山倒海般掃向$n全身",
"lvl" : 120,
"skill_name": "佛光普照",
]),
([ "action":"$N力貫鞭梢,一招"HIY"「金剛伏魔」"NOR",手中$w舞出滿天鞭影,排山倒海般掃向$n全身",
"lvl" : 130,
"skill_name" : "金剛伏魔",
]),
([ "action":"$N力貫鞭梢,一招"HIM"「佛法無邊」"NOR",手中$w舞出滿天鞭影,排山倒海般掃向$n全身",
"lvl" : 200,
"skill_name" : "佛法無邊",
]),
});
int valid_enable(string usage) { return usage == "whip" || usage =="parry"; }
int valid_learn(object me)
{
object weapon;
if( query("str", me)<26 )
return notify_fail("你研究了半天,感覺膂力有些低,始終無法隨意施展。\n");
if( !objectp(weapon=query_temp("weapon", me)) ||
query("skill_type", weapon) != "whip" )
return notify_fail("你必須先找一條鞭子才能練鞭法。\n");
if( query("max_neili", me)<1000 )
return notify_fail("你的內力不足,沒有辦法練日月鞭法,多練些內力再來吧。\n");
if ((int)me->query_skill("force") < 150)
return notify_fail("你的內功火候太淺,沒有辦法練日月鞭法。\n");
if ((int)me->query_skill("whip", 1) < 100)
return notify_fail("你的基本鞭法火候太淺,沒有辦法練日月鞭法。\n");
if ((int)me->query_skill("whip", 1) < (int)me->query_skill("riyue-bian", 1))
return notify_fail("你的基本鞭法水平還不夠,無法領會更高深的日月鞭法。\n");
return 1;
}
int practice_skill(object me)
{
object weapon;
if( !objectp(weapon=query_temp("weapon", me) )
|| query("skill_type", weapon) != "whip" )
return notify_fail("你使用的武器不對。\n");
if( query("qi", me)<30 || query("neili", me)<30 )
return notify_fail("你的體力不夠練日月鞭法。\n");
me->receive_damage("qi", 30);
addn("neili", -30, me);
return 1;
}
string query_skill_name(int level)
{
int i;
for(i = sizeof(action)-1; i >= 0; i--)
if(level >= action[i]["lvl"])
return action[i]["skill_name"];
}
mapping query_action(object me, object weapon)
{
int d_e1 = -60;
int d_e2 = -70;
int p_e1 = -25;
int p_e2 = -35;
int f_e1 = 150;
int f_e2 = 200;
int m_e1 = 300;
int m_e2 = 550;
int i, lvl, seq, ttl = sizeof(action);
lvl = (int) me->query_skill("riyue-bian", 1);
for(i = ttl; i > 0; i--)
if(lvl > action[i-1]["lvl"])
{
seq = i; /* 獲得招數序號上限 */
break;
}
seq = random(seq); /* 選擇出手招數序號 */
return ([
"action" : action[seq]["action"],
"dodge" : d_e1 + (d_e2 - d_e1) * seq / ttl,
"parry" : p_e1 + (p_e2 - p_e1) * seq / ttl,
"force" : f_e1 + (f_e2 - f_e1) * seq / ttl,
"damage" : m_e1 + (m_e2 - m_e1) * seq / ttl,
"damage_type" : random(2) ? "瘀傷" : "刺傷",
]);
}
mixed hit_ob(object me, object victim, int damage_bonus)
{
mixed result;
int level;
object weapon;
string *msg;
weapon=query_temp("weapon", me);
if (! objectp(weapon)) return;
msg = ({
HIR"只聽得“啊”的一聲慘叫,$n背脊為"+weapon->name()+HIR"所擊中,摔出了戰圈,眼見是不活了。\n"NOR,
HIR"這一鞭威力極巨,登時打得$p腦漿迸裂,四肢齊折,不成人形。\n"NOR,
HIR""+weapon->name()+HIR"一抖之下,一股排山倒海的內勁向$n胸口撞到,$n當場肋骨斷折,五臟齊碎。\n"NOR,
});
result = ([ "damage" : damage_bonus ]);
result += ([ "msg" : msg[random(sizeof(msg))] ]);
return result;
}
int query_effect_parry(object attacker, object me)
{
int lvl;
if( !query_temp("weapon", me) )
return 0;
lvl = me->query_skill("riyue-bian", 1);
if (lvl < 80) return 0;
if (lvl < 200) return 50;
if (lvl < 280) return 80;
if (lvl < 350) return 100;
return 120;
}
string perform_action_file(string action)
{
if ( this_player()->query_skill("riyue-bian", 1) >= 50 )
return __DIR__"riyue-bian/" + action;
}
int learn_bonus() { return 5; }
int practice_bonus() { return 5; }
int success() { return 5; }
int power_point(object me) {
object weapon;
if( objectp(weapon=query_temp("weapon", me) )
&& query("id", weapon) == "heisuo" )
return 1.3;
else
return 1.0;
}
int help(object me)
{
write(HIC"\n日月鞭法:"NOR"\n");
write(@HELP
日月鞭法為少林長老三渡的鎮山絕技。
學習要求:
混元一氣功50級
內力500
HELP
);
return 1;
}
| 29.189189 | 84 | 0.487778 | [
"object"
] |
9ad970a2832f8c2f0cee36c5e8f4a8d581b067b5 | 4,253 | h | C | cpp/src/render/render_builder.h | yxm1536/arctern | ef88ffd23bd91cb4fa9c5e8524a5e6ab53008117 | [
"Apache-2.0"
] | null | null | null | cpp/src/render/render_builder.h | yxm1536/arctern | ef88ffd23bd91cb4fa9c5e8524a5e6ab53008117 | [
"Apache-2.0"
] | 1 | 2020-03-12T00:49:52.000Z | 2020-03-12T00:49:52.000Z | cpp/src/render/render_builder.h | yxm1536/arctern | ef88ffd23bd91cb4fa9c5e8524a5e6ab53008117 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2019-2020 Zilliz. 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.
*/
#pragma once
#include <ogr_api.h>
#include <ogrsf_frmts.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "render/2d/choropleth_map/choropleth_map.h"
#include "render/2d/heatmap/heatmap.h"
#include "render/2d/scatter_plot/pointmap.h"
#include "render/2d/scatter_plot/weighted_pointmap.h"
namespace arctern {
namespace render {
enum AggType {
SUM = 0,
MIN,
MAX,
COUNT,
STDDEV,
AVG,
};
struct hash_func {
size_t operator()(OGRGeometry* geo) const {
auto type = wkbFlatten(geo->getGeometryType());
if (type == wkbPoint) {
return (std::hash<uint32_t>()(geo->toPoint()->getX()) ^
std::hash<uint32_t>()(geo->toPoint()->getY()));
} else if (type == wkbPolygon) {
auto ring = geo->toPolygon()->getExteriorRing();
auto ring_size = ring->getNumPoints();
size_t hash_value = 0;
for (int i = 0; i < ring_size; i++) {
hash_value +=
std::hash<uint32_t>()(ring->getX(i)) ^ std::hash<uint32_t>()(ring->getY(i));
}
return hash_value;
}
return 0;
}
};
std::shared_ptr<arrow::Array> Projection(const std::shared_ptr<arrow::Array>& geos,
const std::string& bottom_right,
const std::string& top_left, const int& height,
const int& width);
std::shared_ptr<arrow::Array> TransformAndProjection(
const std::shared_ptr<arrow::Array>& geos, const std::string& src_rs,
const std::string& dst_rs, const std::string& bottom_right,
const std::string& top_left, const int& height, const int& width);
template <typename T>
std::unordered_map<OGRGeometry*, std::vector<T>, hash_func> weight_agg(
const std::shared_ptr<arrow::Array>& geos,
const std::shared_ptr<arrow::Array>& arr_c);
template <typename T>
std::unordered_map<OGRGeometry*, std::pair<std::vector<T>, std::vector<T>>, hash_func>
weight_agg_multiple_column(const std::shared_ptr<arrow::Array>& geos,
const std::shared_ptr<arrow::Array>& arr_c,
const std::shared_ptr<arrow::Array>& arr_s);
std::pair<uint8_t*, int64_t> pointmap(uint32_t* arr_x, uint32_t* arr_y,
int64_t num_vertices, const std::string& conf);
std::pair<uint8_t*, int64_t> weighted_pointmap(uint32_t* arr_x, uint32_t* arr_y,
int64_t num_vertices,
const std::string& conf);
template <typename T>
std::pair<uint8_t*, int64_t> weighted_pointmap(uint32_t* arr_x, uint32_t* arr_y, T* arr,
int64_t num_vertices,
const std::string& conf);
template <typename T>
std::pair<uint8_t*, int64_t> weighted_pointmap(uint32_t* arr_x, uint32_t* arr_y, T* arr_c,
T* arr_s, int64_t num_vertices,
const std::string& conf);
template <typename T>
std::pair<uint8_t*, int64_t> heatmap(uint32_t* arr_x, uint32_t* arr_y, T* arr_c,
int64_t num_vertices, const std::string& conf);
template <typename T>
std::pair<uint8_t*, int64_t> choroplethmap(const std::vector<OGRGeometry*>& arr_wkt,
T* arr_c, int64_t num_buildings,
const std::string& conf);
} // namespace render
} // namespace arctern
#include "render/render_builder_impl.h"
| 36.982609 | 90 | 0.607101 | [
"render",
"vector"
] |
9add289a1c3e02c50ec0860f0bc7dd89308b2a08 | 17,579 | h | C | components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_provisioning_api.h | ewpa/esp-idf | 15d68d7ae8d40a9758eef0c957d3c9d527192232 | [
"Apache-2.0"
] | 6 | 2018-01-07T15:23:15.000Z | 2020-08-03T05:42:03.000Z | components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_provisioning_api.h | ustccw/esp-idf | 38a5780650663048a821b48c4c82e708eda8fbd0 | [
"Apache-2.0"
] | null | null | null | components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_provisioning_api.h | ustccw/esp-idf | 38a5780650663048a821b48c4c82e708eda8fbd0 | [
"Apache-2.0"
] | 6 | 2018-07-28T16:14:42.000Z | 2020-02-13T10:14:44.000Z | // Copyright 2017-2019 Espressif Systems (Shanghai) PTE 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 _ESP_BLE_MESH_PROVISIONING_API_H_
#define _ESP_BLE_MESH_PROVISIONING_API_H_
#include "esp_ble_mesh_defs.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @brief: event, event code of provisioning events; param, parameters of provisioning events */
typedef void (* esp_ble_mesh_prov_cb_t)(esp_ble_mesh_prov_cb_event_t event,
esp_ble_mesh_prov_cb_param_t *param);
/**
* @brief Register BLE Mesh provisioning callback.
*
* @param[in] callback: Pointer to the callback function.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_register_prov_callback(esp_ble_mesh_prov_cb_t callback);
/**
* @brief Check if a device has been provisioned.
*
* @return TRUE if the device is provisioned, FALSE if the device is unprovisioned.
*
*/
bool esp_ble_mesh_node_is_provisioned(void);
/**
* @brief Enable specific provisioning bearers to get the device ready for provisioning.
*
* @note PB-ADV: send unprovisioned device beacon.
* PB-GATT: send connectable advertising packets.
*
* @param bearers: Bit-wise OR of provisioning bearers.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_node_prov_enable(esp_ble_mesh_prov_bearer_t bearers);
/**
* @brief Disable specific provisioning bearers to make a device inaccessible for provisioning.
*
* @param bearers: Bit-wise OR of provisioning bearers.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_node_prov_disable(esp_ble_mesh_prov_bearer_t bearers);
/**
* @brief Unprovisioned device set own oob public key & private key pair.
*
* @param[in] pub_key_x: Unprovisioned device's Public Key X
* @param[in] pub_key_y: Unprovisioned device's Public Key Y
* @param[in] private_key: Unprovisioned device's Private Key
*
* @return ESP_OK on success or error code otherwise.
*/
esp_err_t esp_ble_mesh_node_set_oob_pub_key(uint8_t pub_key_x[32], uint8_t pub_key_y[32],
uint8_t private_key[32]);
/**
* @brief Provide provisioning input OOB number.
*
* @note This is intended to be called if the user has received ESP_BLE_MESH_NODE_PROV_INPUT_EVT
* with ESP_BLE_MESH_ENTER_NUMBER as the action.
*
* @param[in] number: Number input by device.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_node_input_number(uint32_t number);
/**
* @brief Provide provisioning input OOB string.
*
* @note This is intended to be called if the user has received ESP_BLE_MESH_NODE_PROV_INPUT_EVT
* with ESP_BLE_MESH_ENTER_STRING as the action.
*
* @param[in] string: String input by device.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_node_input_string(const char *string);
/**
* @brief Using this function, an unprovisioned device can set its own device name,
* which will be broadcasted in its advertising data.
*
* @param[in] name: Unprovisioned device name
*
* @note This API applicable to PB-GATT mode only by setting the name to the scan response data,
* it doesn't apply to PB-ADV mode.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_set_unprovisioned_device_name(const char *name);
/**
* @brief Provisioner inputs unprovisioned device's oob public key.
*
* @param[in] link_idx: The provisioning link index
* @param[in] pub_key_x: Unprovisioned device's Public Key X
* @param[in] pub_key_y: Unprovisioned device's Public Key Y
*
* @return ESP_OK on success or error code otherwise.
*/
esp_err_t esp_ble_mesh_provisioner_read_oob_pub_key(uint8_t link_idx, uint8_t pub_key_x[32],
uint8_t pub_key_y[32]);
/**
* @brief Provide provisioning input OOB string.
*
* This is intended to be called after the esp_ble_mesh_prov_t prov_input_num
* callback has been called with ESP_BLE_MESH_ENTER_STRING as the action.
*
* @param[in] string: String input by Provisioner.
* @param[in] link_idx: The provisioning link index.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_input_string(const char *string, uint8_t link_idx);
/**
* @brief Provide provisioning input OOB number.
*
* This is intended to be called after the esp_ble_mesh_prov_t prov_input_num
* callback has been called with ESP_BLE_MESH_ENTER_NUMBER as the action.
*
* @param[in] number: Number input by Provisioner.
* @param[in] link_idx: The provisioning link index.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_input_number(uint32_t number, uint8_t link_idx);
/**
* @brief Enable one or more provisioning bearers.
*
* @param[in] bearers: Bit-wise OR of provisioning bearers.
*
* @note PB-ADV: Enable BLE scan.
* PB-GATT: Initialize corresponding BLE Mesh Proxy info.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_prov_enable(esp_ble_mesh_prov_bearer_t bearers);
/**
* @brief Disable one or more provisioning bearers.
*
* @param[in] bearers: Bit-wise OR of provisioning bearers.
*
* @note PB-ADV: Disable BLE scan.
* PB-GATT: Break any existing BLE Mesh Provisioning connections.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_prov_disable(esp_ble_mesh_prov_bearer_t bearers);
/**
* @brief Add unprovisioned device info to the unprov_dev queue.
*
* @param[in] add_dev: Pointer to a struct containing the device information
* @param[in] flags: Flags indicate several operations on the device information
* - Remove device information from queue after device has been provisioned (BIT0)
* - Start provisioning immediately after device is added to queue (BIT1)
* - Device can be removed if device queue is full (BIT2)
*
* @return ESP_OK on success or error code otherwise.
*
* @note: 1. Currently address type only supports public address and static random address.
* 2. If device UUID and/or device address as well as address type already exist in the
* device queue, but the bearer is different from the existing one, add operation
* will also be successful and it will update the provision bearer supported by
* the device.
* 3. For example, if the Provisioner wants to add an unprovisioned device info before
* receiving its unprovisioned device beacon or Mesh Provisioning advertising packets,
* the Provisioner can use this API to add the device info with each one or both of
* device UUID and device address added. When the Provisioner gets the device's
* advertising packets, it will start provisioning the device internally.
* - In this situation, the Provisioner can set bearers with each one or both of
* ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled, and cannot set flags
* with ADD_DEV_START_PROV_NOW_FLAG enabled.
* 4. Another example is when the Provisioner receives the unprovisioned device's beacon or
* Mesh Provisioning advertising packets, the advertising packets will be reported on to
* the application layer using the callback registered by the function
* esp_ble_mesh_register_prov_callback. And in the callback, the Provisioner
* can call this API to start provisioning the device.
* - If the Provisioner uses PB-ADV to provision, either one or both of device UUID and
* device address can be added, bearers shall be set with ESP_BLE_MESH_PROV_ADV
* enabled and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled.
* - If the Provisioner uses PB-GATT to provision, both the device UUID and device
* address need to be added, bearers shall be set with ESP_BLE_MESH_PROV_GATT enabled,
* and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled.
* - If the Provisioner just wants to store the unprovisioned device info when receiving
* its advertising packets and start to provision it the next time (e.g. after receiving
* its advertising packets again), then it can add the device info with either one or both
* of device UUID and device address included. Bearers can be set with either one or both
* of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled (recommend to enable the
* bearer which will receive its advertising packets, because if the other bearer is
* enabled, the Provisioner is not aware if the device supports the bearer), and flags
* cannot be set with ADD_DEV_START_PROV_NOW_FLAG enabled.
* - Note: ESP_BLE_MESH_PROV_ADV, ESP_BLE_MESH_PROV_GATT and ADD_DEV_START_PROV_NOW_FLAG
* can not be enabled at the same time.
*
*/
esp_err_t esp_ble_mesh_provisioner_add_unprov_dev(esp_ble_mesh_unprov_dev_add_t *add_dev,
esp_ble_mesh_dev_add_flag_t flags);
/** @brief Provision an unprovisioned device with fixed unicast address.
*
* @param[in] uuid: Device UUID of the unprovisioned device
* @param[in] addr: Device address of the unprovisioned device
* @param[in] addr_type: Device address type of the unprovisioned device
* @param[in] bearer: Provisioning bearer going to be used by Provisioner
* @param[in] oob_info: OOB info of the unprovisioned device
* @param[in] unicast_addr: Unicast address going to be allocated for the unprovisioned device
*
* @return Zero on success or (negative) error code otherwise.
*
* @note: 1. Currently address type only supports public address and static random address.
* 2. Bearer must be equal to ESP_BLE_MESH_PROV_ADV or ESP_BLE_MESH_PROV_GATT, since
* Provisioner will start to provision a device immediately once this function is
* invked. And the input bearer must be identical with the one within the parameters
* of the ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT event.
* 3. If this function is used by a Provisioner to provision devices, the application
* should take care of the assigned unicast address and avoid overlap of the unicast
* addresses of different nodes.
* 4. Recommend to use only one of the functions "esp_ble_mesh_provisioner_add_unprov_dev"
* and "esp_ble_mesh_provisioner_prov_device_with_addr" by a Provisioner.
*/
esp_err_t esp_ble_mesh_provisioner_prov_device_with_addr(const uint8_t uuid[16],
esp_ble_mesh_bd_addr_t addr,
esp_ble_mesh_addr_type_t addr_type,
esp_ble_mesh_prov_bearer_t bearer,
uint16_t oob_info, uint16_t unicast_addr);
/**
* @brief Delete device from queue, and reset current provisioning link with the device.
*
* @note If the device is in the queue, remove it from the queue; if the device is
* being provisioned, terminate the provisioning procedure. Either one of the
* device address or device UUID can be used as input.
*
* @param[in] del_dev: Pointer to a struct containing the device information.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_delete_dev(esp_ble_mesh_device_delete_t *del_dev);
/**
* @brief Callback for Provisioner that received advertising packets from unprovisioned devices which are
* not in the unprovisioned device queue.
*
* Report on the unprovisioned device beacon and mesh provisioning service adv data to application.
*
* @param[in] addr: Pointer to the unprovisioned device address.
* @param[in] addr_type: Unprovisioned device address type.
* @param[in] adv_type: Adv packet type(ADV_IND or ADV_NONCONN_IND).
* @param[in] dev_uuid: Unprovisioned device UUID pointer.
* @param[in] oob_info: OOB information of the unprovisioned device.
* @param[in] bearer: Adv packet received from PB-GATT or PB-ADV bearer.
*
*/
typedef void (*esp_ble_mesh_prov_adv_cb_t)(const esp_ble_mesh_bd_addr_t addr, const esp_ble_mesh_addr_type_t addr_type,
const uint8_t adv_type, const uint8_t *dev_uuid,
uint16_t oob_info, esp_ble_mesh_prov_bearer_t bearer);
/**
* @brief This function is called by Provisioner to set the part of the device UUID
* to be compared before starting to provision.
*
* @param[in] match_val: Value to be compared with the part of the device UUID.
* @param[in] match_len: Length of the compared match value.
* @param[in] offset: Offset of the device UUID to be compared (based on zero).
* @param[in] prov_after_match: Flag used to indicate whether provisioner should start to provision
* the device immediately if the part of the UUID matches.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_set_dev_uuid_match(const uint8_t *match_val, uint8_t match_len,
uint8_t offset, bool prov_after_match);
/**
* @brief This function is called by Provisioner to set provisioning data information
* before starting to provision.
*
* @param[in] prov_data_info: Pointer to a struct containing net_idx or flags or iv_index.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_set_prov_data_info(esp_ble_mesh_prov_data_info_t *prov_data_info);
/**
* @brief This function is called by Provisioner to set static oob value used for provisioning.
*
* @param[in] value: Pointer to the static oob value.
* @param[in] length: Length of the static oob value.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_set_static_oob_value(const uint8_t *value, uint8_t length);
/**
* @brief This function is called by Provisioner to set own Primary element address.
*
* @note This API must be invoked when BLE Mesh initialization is completed successfully,
* and can be invoked before Provisioner functionality is enabled.
* Once this API is invoked successfully, the prov_unicast_addr value in the struct
* esp_ble_mesh_prov_t will be ignored, and Provisioner will use this address as its
* own primary element address.
* And if the unicast address going to assigned for the next unprovisioned device is
* smaller than the input address + element number of Provisioner, then the address
* for the next unprovisioned device will be recalculated internally.
*
* @param[in] addr: Unicast address of the Primary element of Provisioner.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_provisioner_set_primary_elem_addr(uint16_t addr);
/**
* @brief This function is called to set provisioning data information before starting
* fast provisioning.
*
* @param[in] fast_prov_info: Pointer to a struct containing unicast address range, net_idx, etc.
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_set_fast_prov_info(esp_ble_mesh_fast_prov_info_t *fast_prov_info);
/**
* @brief This function is called to start/suspend/exit fast provisioning.
*
* @param[in] action: fast provisioning action (i.e. enter, suspend, exit).
*
* @return ESP_OK on success or error code otherwise.
*
*/
esp_err_t esp_ble_mesh_set_fast_prov_action(esp_ble_mesh_fast_prov_action_t action);
#ifdef __cplusplus
}
#endif
#endif /* _ESP_BLE_MESH_PROVISIONING_API_H_ */
| 46.260526 | 119 | 0.676205 | [
"mesh"
] |
9ae2213d3a2324756d9bc1719d02d497c206fc55 | 11,879 | h | C | Code/GraphMol/ShapeHelpers/ShapeUtils.h | kazuyaujihara/rdkit | 06027dcd05674787b61f27ba46ec0d42a6037540 | [
"BSD-3-Clause"
] | 1,609 | 2015-01-05T02:41:13.000Z | 2022-03-30T21:57:24.000Z | Code/GraphMol/ShapeHelpers/ShapeUtils.h | kazuyaujihara/rdkit | 06027dcd05674787b61f27ba46ec0d42a6037540 | [
"BSD-3-Clause"
] | 3,412 | 2015-01-06T12:13:33.000Z | 2022-03-31T17:25:41.000Z | Code/GraphMol/ShapeHelpers/ShapeUtils.h | bp-kelley/rdkit | e0de7c9622ce73894b1e7d9568532f6d5638058a | [
"BSD-3-Clause"
] | 811 | 2015-01-11T03:33:48.000Z | 2022-03-28T11:57:49.000Z | //
// Copyright (C) 2005-2006 Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <RDGeneral/export.h>
#ifndef _RD_SHAPE_UTILS_H_20050128_
#define _RD_SHAPE_UTILS_H_20050128_
#include <DataStructs/DiscreteValueVect.h>
#include <vector>
namespace RDGeom {
class Point3D;
class Transform3D;
} // namespace RDGeom
namespace RDKit {
class ROMol;
class Conformer;
namespace MolShapes {
//! Compute the size of the box that can fit the conformation, and offset of the
/// box
//! from the origin
RDKIT_SHAPEHELPERS_EXPORT void computeConfDimsAndOffset(
const Conformer &conf, RDGeom::Point3D &dims, RDGeom::Point3D &offSet,
const RDGeom::Transform3D *trans = nullptr, double padding = 2.5);
//! Compute the box that will fit the conformer
/*!
\param conf The conformer of interest
\param leftBottom Storage for one extremity of the box
\param rightTop Storage for other extremity of the box
\param trans Optional transformation to be applied to the atom
coordinates
\param padding Padding added on the sides around the conformer
*/
RDKIT_SHAPEHELPERS_EXPORT void computeConfBox(
const Conformer &conf, RDGeom::Point3D &leftBottom,
RDGeom::Point3D &rightTop, const RDGeom::Transform3D *trans = nullptr,
double padding = 2.5);
//! Compute the union of two boxes
RDKIT_SHAPEHELPERS_EXPORT void computeUnionBox(
const RDGeom::Point3D &leftBottom1, const RDGeom::Point3D &rightTop1,
const RDGeom::Point3D &leftBottom2, const RDGeom::Point3D &rightTop2,
RDGeom::Point3D &uLeftBottom, RDGeom::Point3D &uRightTop);
//! Compute dimensions of a conformer
/*!
\param conf Conformer of interest
\param padding Padding added to the atom coordinates on all sides
\param center Optionally specify the center
\param ignoreHs if true, ignore the hydrogen atoms in computing the centroid
*/
RDKIT_SHAPEHELPERS_EXPORT std::vector<double> getConfDimensions(
const Conformer &conf, double padding = 2.5,
const RDGeom::Point3D *center = nullptr, bool ignoreHs = true);
//! Compute the shape tversky index between two molecule based on a
/// predefined alignment
/*!
\param mol1 The first molecule of interest
\param mol2 The second molecule of interest
\param alpha
\param beta
\param confId1 Conformer in the first molecule (defaults to first
conformer)
\param confId2 Conformer in the second molecule (defaults to first
conformer)
\param gridSpacing resolution of the grid used to encode the molecular shapes
\param bitsPerPoint number of bit used to encode the occupancy at each grid
point
defaults to two bits per grid point
\param vdwScale Scaling factor for the radius of the atoms to determine
the base radius
used in the encoding - grid points inside this sphere
carry the maximum occupancy
\param stepSize thickness of the each layer outside the base radius, the
occupancy value is decreased
from layer to layer from the maximum value
\param maxLayers the maximum number of layers - defaults to the number
allowed the number of bits
use per grid point - e.g. two bits per grid point will
allow 3 layers
\param ignoreHs if true, ignore the hydrogen atoms in the shape encoding
process
*/
RDKIT_SHAPEHELPERS_EXPORT double tverskyIndex(
const ROMol &mol1, const ROMol &mol2, double alpha, double beta,
int confId1 = -1, int confId2 = -1, double gridSpacing = 0.5,
DiscreteValueVect::DiscreteValueType bitsPerPoint =
DiscreteValueVect::TWOBITVALUE,
double vdwScale = 0.8, double stepSize = 0.25, int maxLayers = -1,
bool ignoreHs = true);
//! Compute the shape tversky index between two conformers based on a
/// predefined alignment
/*!
\param conf1 The first conformer of interest
\param conf2 The second conformer of interest
\param alpha
\param beta
\param gridSpacing resolution of the grid used to encode the molecular shapes
\param bitsPerPoint number of bit used to encode the occupancy at each grid
point
\param vdwScale Scaling factor for the radius of the atoms to determine
the base radius
used in the encoding - grid points inside this sphere
carry the maximum occupancy
\param stepSize thickness of the each layer outside the base radius, the
occupancy value is decreased
from layer to layer from the maximum value
\param maxLayers the maximum number of layers - defaults to the number
allowed the number of bits
use per grid point - e.g. two bits per grid point will
allow 3 layers
\param ignoreHs if true, ignore the hydrogen atoms in the shape encoding
process
*/
RDKIT_SHAPEHELPERS_EXPORT double tverskyIndex(
const Conformer &conf1, const Conformer &conf2, double alpha, double beta,
double gridSpacing = 0.5,
DiscreteValueVect::DiscreteValueType bitsPerPoint =
DiscreteValueVect::TWOBITVALUE,
double vdwScale = 0.8, double stepSize = 0.25, int maxLayers = -1,
bool ignoreHs = true);
//! Compute the shape tanimoto distance between two molecule based on a
/// predefined alignment
/*!
\param mol1 The first molecule of interest
\param mol2 The second molecule of interest
\param confId1 Conformer in the first molecule (defaults to first
conformer)
\param confId2 Conformer in the second molecule (defaults to first
conformer)
\param gridSpacing resolution of the grid used to encode the molecular shapes
\param bitsPerPoint number of bit used to encode the occupancy at each grid
point
defaults to two bits per grid point
\param vdwScale Scaling factor for the radius of the atoms to determine
the base radius
used in the encoding - grid points inside this sphere
carry the maximum occupancy
\param stepSize thickness of the each layer outside the base radius, the
occupancy value is decreased
from layer to layer from the maximum value
\param maxLayers the maximum number of layers - defaults to the number
allowed the number of bits
use per grid point - e.g. two bits per grid point will
allow 3 layers
\param ignoreHs if true, ignore the hydrogen atoms in the shape encoding
process
*/
RDKIT_SHAPEHELPERS_EXPORT double tanimotoDistance(
const ROMol &mol1, const ROMol &mol2, int confId1 = -1, int confId2 = -1,
double gridSpacing = 0.5,
DiscreteValueVect::DiscreteValueType bitsPerPoint =
DiscreteValueVect::TWOBITVALUE,
double vdwScale = 0.8, double stepSize = 0.25, int maxLayers = -1,
bool ignoreHs = true);
//! Compute the shape tanimoto distance between two conformers based on a
/// predefined alignment
/*!
\param conf1 The first conformer of interest
\param conf2 The second conformer of interest
\param gridSpacing resolution of the grid used to encode the molecular shapes
\param bitsPerPoint number of bit used to encode the occupancy at each grid
point
\param vdwScale Scaling factor for the radius of the atoms to determine
the base radius
used in the encoding - grid points inside this sphere
carry the maximum occupancy
\param stepSize thickness of the each layer outside the base radius, the
occupancy value is decreased
from layer to layer from the maximum value
\param maxLayers the maximum number of layers - defaults to the number
allowed the number of bits
use per grid point - e.g. two bits per grid point will
allow 3 layers
\param ignoreHs if true, ignore the hydrogen atoms in the shape encoding
process
*/
RDKIT_SHAPEHELPERS_EXPORT double tanimotoDistance(
const Conformer &conf1, const Conformer &conf2, double gridSpacing = 0.5,
DiscreteValueVect::DiscreteValueType bitsPerPoint =
DiscreteValueVect::TWOBITVALUE,
double vdwScale = 0.8, double stepSize = 0.25, int maxLayers = -1,
bool ignoreHs = true);
//! Compute the shape protrusion distance between two molecule based on a
/// predefined alignment
/*!
\param mol1 The first molecule of interest
\param mol2 The second molecule of interest
\param confId1 Conformer in the first molecule (defaults to first
conformer)
\param confId2 Conformer in the second molecule (defaults to first
conformer)
\param gridSpacing resolution of the grid used to encode the molecular shapes
\param bitsPerPoint number of bit used to encode the occupancy at each grid
point
defaults to two bits per grid point
\param vdwScale Scaling factor for the radius of the atoms to determine
the base radius
used in the encoding - grid points inside this sphere
carry the maximum occupancy
\param stepSize thickness of the each layer outside the base radius, the
occupancy value is decreased
from layer to layer from the maximum value
\param maxLayers the maximum number of layers - defaults to the number
allowed the number of bits
use per grid point - e.g. two bits per grid point will
allow 3 layers
\param ignoreHs if true, ignore the hydrogen atoms in the shape encoding
process
\param allowReordering if set the order will be automatically updated so that
the value calculated
is the protrusion of the smaller shape from the larger
one.
*/
RDKIT_SHAPEHELPERS_EXPORT double protrudeDistance(
const ROMol &mol1, const ROMol &mol2, int confId1 = -1, int confId2 = -1,
double gridSpacing = 0.5,
DiscreteValueVect::DiscreteValueType bitsPerPoint =
DiscreteValueVect::TWOBITVALUE,
double vdwScale = 0.8, double stepSize = 0.25, int maxLayers = -1,
bool ignoreHs = true, bool allowReordering = true);
//! Compute the shape protrusion distance between two conformers based on a
/// predefined alignment
/*!
\param conf1 The first conformer of interest
\param conf2 The second conformer of interest
\param gridSpacing resolution of the grid used to encode the molecular shapes
\param bitsPerPoint number of bit used to encode the occupancy at each grid
point
\param vdwScale Scaling factor for the radius of the atoms to determine
the base radius
used in the encoding - grid points inside this sphere
carry the maximum occupancy
\param stepSize thickness of the each layer outside the base radius, the
occupancy value is decreased
from layer to layer from the maximum value
\param maxLayers the maximum number of layers - defaults to the number
allowed the number of bits
use per grid point - e.g. two bits per grid point will
allow 3 layers
\param ignoreHs if true, ignore the hydrogen atoms in the shape encoding
process
\param allowReordering if set the order will be automatically updated so that
the value calculated
is the protrusion of the smaller shape from the larger
one.
*/
RDKIT_SHAPEHELPERS_EXPORT double protrudeDistance(
const Conformer &conf1, const Conformer &conf2, double gridSpacing = 0.5,
DiscreteValueVect::DiscreteValueType bitsPerPoint =
DiscreteValueVect::TWOBITVALUE,
double vdwScale = 0.8, double stepSize = 0.25, int maxLayers = -1,
bool ignoreHs = true, bool allowReordering = true);
} // namespace MolShapes
} // namespace RDKit
#endif
| 42.425 | 80 | 0.712013 | [
"shape",
"vector"
] |
36ed06a0d21be32814d699354fdad2746be01014 | 43,567 | h | C | configs/x86/MagickCore/magick-baseconfig.h | TinkerBoard2-Android/external-ImageMagick | 46696775cff41245ab4a23a7c89f6d399543852c | [
"ImageMagick"
] | null | null | null | configs/x86/MagickCore/magick-baseconfig.h | TinkerBoard2-Android/external-ImageMagick | 46696775cff41245ab4a23a7c89f6d399543852c | [
"ImageMagick"
] | null | null | null | configs/x86/MagickCore/magick-baseconfig.h | TinkerBoard2-Android/external-ImageMagick | 46696775cff41245ab4a23a7c89f6d399543852c | [
"ImageMagick"
] | null | null | null | #ifndef _MAGICKCORE_MAGICK_BASECONFIG_H
#define _MAGICKCORE_MAGICK_BASECONFIG_H 1
/* MagickCore/magick-baseconfig.h. Generated automatically at end of configure. */
/* config/config.h. Generated from config.h.in by configure. */
/* config/config.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define if you have AUTOTRACE library */
/* #undef AUTOTRACE_DELEGATE */
/* Define if coders and filters are to be built as modules. */
/* #undef BUILD_MODULES */
/* Define if you have the bzip2 library */
/* #undef BZLIB_DELEGATE */
/* Define if you have CAIRO library */
/* #undef CAIRO_DELEGATE */
/* permit enciphering and deciphering image pixels */
#ifndef MAGICKCORE_CIPHER_SUPPORT
#define MAGICKCORE_CIPHER_SUPPORT 1
#endif
/* Define to 1 if the `closedir' function returns void instead of `int'. */
#ifndef MAGICKCORE_CLOSEDIR_VOID
#define MAGICKCORE_CLOSEDIR_VOID 1
#endif
/* coders subdirectory. */
#ifndef MAGICKCORE_CODER_DIRNAME
#define MAGICKCORE_CODER_DIRNAME "coders"
#endif
/* Directory where architecture-dependent configuration files live. */
#ifndef MAGICKCORE_CONFIGURE_PATH
#define MAGICKCORE_CONFIGURE_PATH "/usr/local/etc/ImageMagick-7/"
#endif
/* Subdirectory of lib where architecture-dependent configuration files live.
*/
#ifndef MAGICKCORE_CONFIGURE_RELATIVE_PATH
#define MAGICKCORE_CONFIGURE_RELATIVE_PATH "ImageMagick-7"
#endif
/* Define if you have DJVU library */
/* #undef DJVU_DELEGATE */
/* Directory where ImageMagick documents live. */
#ifndef MAGICKCORE_DOCUMENTATION_PATH
#define MAGICKCORE_DOCUMENTATION_PATH "/usr/local/share/doc/ImageMagick-7/"
#endif
/* Define if you have Display Postscript */
/* #undef DPS_DELEGATE */
/* exclude deprecated methods in MagickCore API */
/* #undef EXCLUDE_DEPRECATED */
/* Directory where executables are installed. */
#ifndef MAGICKCORE_EXECUTABLE_PATH
#define MAGICKCORE_EXECUTABLE_PATH "/usr/local/bin/"
#endif
/* Define if you have FFTW library */
/* #undef FFTW_DELEGATE */
/* filter subdirectory. */
#ifndef MAGICKCORE_FILTER_DIRNAME
#define MAGICKCORE_FILTER_DIRNAME "filters"
#endif
/* Define if you have FLIF library */
/* #undef FLIF_DELEGATE */
/* Define if you have FONTCONFIG library */
/* #undef FONTCONFIG_DELEGATE */
/* Define if you have FlashPIX library */
/* #undef FPX_DELEGATE */
/* Define if you have FREETYPE library */
/* #undef FREETYPE_DELEGATE */
/* Define if you have Ghostscript library or framework */
/* #undef GS_DELEGATE */
/* Define if you have GVC library */
/* #undef GVC_DELEGATE */
/* Define to 1 if you have the `acosh' function. */
#ifndef MAGICKCORE_HAVE_ACOSH
#define MAGICKCORE_HAVE_ACOSH 1
#endif
/* Define to 1 if you have the <arm/limits.h> header file. */
/* #undef HAVE_ARM_LIMITS_H */
/* Define to 1 if you have the <arpa/inet.h> header file. */
#ifndef MAGICKCORE_HAVE_ARPA_INET_H
#define MAGICKCORE_HAVE_ARPA_INET_H 1
#endif
/* Define to 1 if you have the `asinh' function. */
#ifndef MAGICKCORE_HAVE_ASINH
#define MAGICKCORE_HAVE_ASINH 1
#endif
/* Define to 1 if you have the `atanh' function. */
#ifndef MAGICKCORE_HAVE_ATANH
#define MAGICKCORE_HAVE_ATANH 1
#endif
/* Define to 1 if you have the `atexit' function. */
#ifndef MAGICKCORE_HAVE_ATEXIT
#define MAGICKCORE_HAVE_ATEXIT 1
#endif
/* Define to 1 if you have the `atoll' function. */
#ifndef MAGICKCORE_HAVE_ATOLL
#define MAGICKCORE_HAVE_ATOLL 1
#endif
/* define if bool is a built-in type */
#ifndef MAGICKCORE_HAVE_BOOL
#define MAGICKCORE_HAVE_BOOL /**/
#endif
/* Define to 1 if you have the `cabs' function. */
#ifndef MAGICKCORE_HAVE_CABS
#define MAGICKCORE_HAVE_CABS 1
#endif
/* Define to 1 if you have the `carg' function. */
#ifndef MAGICKCORE_HAVE_CARG
#define MAGICKCORE_HAVE_CARG 1
#endif
/* Define to 1 if you have the `cimag' function. */
#ifndef MAGICKCORE_HAVE_CIMAG
#define MAGICKCORE_HAVE_CIMAG 1
#endif
/* Define to 1 if you have the `clock' function. */
#ifndef MAGICKCORE_HAVE_CLOCK
#define MAGICKCORE_HAVE_CLOCK 1
#endif
/* Define to 1 if you have the `clock_getres' function. */
#ifndef MAGICKCORE_HAVE_CLOCK_GETRES
#define MAGICKCORE_HAVE_CLOCK_GETRES 1
#endif
/* Define to 1 if you have the `clock_gettime' function. */
#ifndef MAGICKCORE_HAVE_CLOCK_GETTIME
#define MAGICKCORE_HAVE_CLOCK_GETTIME 1
#endif
/* Define to 1 if clock_gettime supports CLOCK_REALTIME. */
#ifndef MAGICKCORE_HAVE_CLOCK_REALTIME
#define MAGICKCORE_HAVE_CLOCK_REALTIME 1
#endif
/* Define to 1 if you have the <CL/cl.h> header file. */
/* #undef HAVE_CL_CL_H */
/* Define to 1 if you have the <complex.h> header file. */
#ifndef MAGICKCORE_HAVE_COMPLEX_H
#define MAGICKCORE_HAVE_COMPLEX_H 1
#endif
/* Define to 1 if you have the `creal' function. */
#ifndef MAGICKCORE_HAVE_CREAL
#define MAGICKCORE_HAVE_CREAL 1
#endif
/* Define to 1 if you have the `ctime_r' function. */
#ifndef MAGICKCORE_HAVE_CTIME_R
#define MAGICKCORE_HAVE_CTIME_R 1
#endif
/* Define to 1 if you have the declaration of `pread', and to 0 if you don't.
*/
#ifndef MAGICKCORE_HAVE_DECL_PREAD
#define MAGICKCORE_HAVE_DECL_PREAD 1
#endif
/* Define to 1 if you have the declaration of `pwrite', and to 0 if you don't.
*/
#ifndef MAGICKCORE_HAVE_DECL_PWRITE
#define MAGICKCORE_HAVE_DECL_PWRITE 1
#endif
/* Define to 1 if you have the declaration of `strerror_r', and to 0 if you
don't. */
#ifndef MAGICKCORE_HAVE_DECL_STRERROR_R
#define MAGICKCORE_HAVE_DECL_STRERROR_R 1
#endif
/* Define to 1 if you have the declaration of `strlcpy', and to 0 if you
don't. */
#ifndef MAGICKCORE_HAVE_DECL_STRLCPY
#define MAGICKCORE_HAVE_DECL_STRLCPY 1
#endif
/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
*/
/* #undef HAVE_DECL_TZNAME */
/* Define to 1 if you have the declaration of `vsnprintf', and to 0 if you
don't. */
#ifndef MAGICKCORE_HAVE_DECL_VSNPRINTF
#define MAGICKCORE_HAVE_DECL_VSNPRINTF 1
#endif
/* Define to 1 if you have the `directio' function. */
/* #undef HAVE_DIRECTIO */
/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
*/
#ifndef MAGICKCORE_HAVE_DIRENT_H
#define MAGICKCORE_HAVE_DIRENT_H 1
#endif
/* Define to 1 if you have the <dlfcn.h> header file. */
#ifndef MAGICKCORE_HAVE_DLFCN_H
#define MAGICKCORE_HAVE_DLFCN_H 1
#endif
/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
/* #undef HAVE_DOPRNT */
/* Define to 1 if you have the `erf' function. */
#ifndef MAGICKCORE_HAVE_ERF
#define MAGICKCORE_HAVE_ERF 1
#endif
/* Define to 1 if you have the <errno.h> header file. */
#ifndef MAGICKCORE_HAVE_ERRNO_H
#define MAGICKCORE_HAVE_ERRNO_H 1
#endif
/* Define to 1 if you have the `execvp' function. */
#ifndef MAGICKCORE_HAVE_EXECVP
#define MAGICKCORE_HAVE_EXECVP 1
#endif
/* Define to 1 if you have the `fchmod' function. */
#ifndef MAGICKCORE_HAVE_FCHMOD
#define MAGICKCORE_HAVE_FCHMOD 1
#endif
/* Define to 1 if you have the <fcntl.h> header file. */
#ifndef MAGICKCORE_HAVE_FCNTL_H
#define MAGICKCORE_HAVE_FCNTL_H 1
#endif
/* Define to 1 if you have the `floor' function. */
#ifndef MAGICKCORE_HAVE_FLOOR
#define MAGICKCORE_HAVE_FLOOR 1
#endif
/* Define to 1 if you have the `fork' function. */
#ifndef MAGICKCORE_HAVE_FORK
#define MAGICKCORE_HAVE_FORK 1
#endif
/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
#ifndef MAGICKCORE_HAVE_FSEEKO
#define MAGICKCORE_HAVE_FSEEKO 1
#endif
/* Define to 1 if you have the `ftime' function. */
/* #undef HAVE_FTIME */
/* Define to 1 if you have the `ftruncate' function. */
#ifndef MAGICKCORE_HAVE_FTRUNCATE
#define MAGICKCORE_HAVE_FTRUNCATE 1
#endif
/* Define to 1 if you have the `getcwd' function. */
#ifndef MAGICKCORE_HAVE_GETCWD
#define MAGICKCORE_HAVE_GETCWD 1
#endif
/* Define to 1 if you have the `getc_unlocked' function. */
#ifndef MAGICKCORE_HAVE_GETC_UNLOCKED
#define MAGICKCORE_HAVE_GETC_UNLOCKED 1
#endif
/* Define to 1 if you have the `getdtablesize' function. */
/* #undef HAVE_GETDTABLESIZE */
/* Define to 1 if you have the `getexecname' function. */
/* #undef HAVE_GETEXECNAME */
/* Define to 1 if you have the `getpagesize' function. */
#ifndef MAGICKCORE_HAVE_GETPAGESIZE
#define MAGICKCORE_HAVE_GETPAGESIZE 1
#endif
/* Define to 1 if you have the `getpid' function. */
#ifndef MAGICKCORE_HAVE_GETPID
#define MAGICKCORE_HAVE_GETPID 1
#endif
/* Define to 1 if you have the `getrlimit' function. */
#ifndef MAGICKCORE_HAVE_GETRLIMIT
#define MAGICKCORE_HAVE_GETRLIMIT 1
#endif
/* Define to 1 if you have the `getrusage' function. */
#ifndef MAGICKCORE_HAVE_GETRUSAGE
#define MAGICKCORE_HAVE_GETRUSAGE 1
#endif
/* Define to 1 if you have the `gettimeofday' function. */
#ifndef MAGICKCORE_HAVE_GETTIMEOFDAY
#define MAGICKCORE_HAVE_GETTIMEOFDAY 1
#endif
/* Define to 1 if you have the `gmtime_r' function. */
#ifndef MAGICKCORE_HAVE_GMTIME_R
#define MAGICKCORE_HAVE_GMTIME_R 1
#endif
/* Compile with hugepage support */
/* #undef HAVE_HUGEPAGES */
/* Define to 1 if the system has the type `intmax_t'. */
#ifndef MAGICKCORE_HAVE_INTMAX_T
#define MAGICKCORE_HAVE_INTMAX_T 1
#endif
/* Define to 1 if the system has the type `intptr_t'. */
#ifndef MAGICKCORE_HAVE_INTPTR_T
#define MAGICKCORE_HAVE_INTPTR_T 1
#endif
/* Define to 1 if you have the <inttypes.h> header file. */
#ifndef MAGICKCORE_HAVE_INTTYPES_H
#define MAGICKCORE_HAVE_INTTYPES_H 1
#endif
/* Define to 1 if you have the `isnan' function. */
#ifndef MAGICKCORE_HAVE_ISNAN
#define MAGICKCORE_HAVE_ISNAN 1
#endif
/* Define to 1 if you have the `j0' function. */
#ifndef MAGICKCORE_HAVE_J0
#define MAGICKCORE_HAVE_J0 1
#endif
/* Define to 1 if you have the `j1' function. */
#ifndef MAGICKCORE_HAVE_J1
#define MAGICKCORE_HAVE_J1 1
#endif
/* Define if you have the <lcms2.h> header file. */
/* #undef HAVE_LCMS2_H */
/* Define if you have the <lcms2/lcms2.h> header file. */
/* #undef HAVE_LCMS2_LCMS2_H */
/* Define to 1 if you have the `gcov' library (-lgcov). */
/* #undef HAVE_LIBGCOV */
/* Define to 1 if you have the <limits.h> header file. */
#ifndef MAGICKCORE_HAVE_LIMITS_H
#define MAGICKCORE_HAVE_LIMITS_H 1
#endif
/* Define to 1 if you have the <linux/unistd.h> header file. */
#ifndef MAGICKCORE_HAVE_LINUX_UNISTD_H
#define MAGICKCORE_HAVE_LINUX_UNISTD_H 1
#endif
/* Define to 1 if you have the `lltostr' function. */
/* #undef HAVE_LLTOSTR */
/* Define to 1 if you have the <locale.h> header file. */
#ifndef MAGICKCORE_HAVE_LOCALE_H
#define MAGICKCORE_HAVE_LOCALE_H 1
#endif
/* Define to 1 if you have the `localtime_r' function. */
#ifndef MAGICKCORE_HAVE_LOCALTIME_R
#define MAGICKCORE_HAVE_LOCALTIME_R 1
#endif
/* Define to 1 if the system has the type `long long int'. */
#ifndef MAGICKCORE_HAVE_LONG_LONG_INT
#define MAGICKCORE_HAVE_LONG_LONG_INT 1
#endif
/* Define to 1 if you have the `lstat' function. */
#ifndef MAGICKCORE_HAVE_LSTAT
#define MAGICKCORE_HAVE_LSTAT 1
#endif
/* Define to 1 if you have the <machine/param.h> header file. */
/* #undef HAVE_MACHINE_PARAM_H */
/* Define to 1 if you have the <mach-o/dyld.h> header file. */
/* #undef HAVE_MACH_O_DYLD_H */
/* Define to 1 if <wchar.h> declares mbstate_t. */
#ifndef MAGICKCORE_HAVE_MBSTATE_T
#define MAGICKCORE_HAVE_MBSTATE_T 1
#endif
/* Define to 1 if you have the `memmove' function. */
#ifndef MAGICKCORE_HAVE_MEMMOVE
#define MAGICKCORE_HAVE_MEMMOVE 1
#endif
/* Define to 1 if you have the <memory.h> header file. */
#ifndef MAGICKCORE_HAVE_MEMORY_H
#define MAGICKCORE_HAVE_MEMORY_H 1
#endif
/* Define to 1 if you have the `memset' function. */
#ifndef MAGICKCORE_HAVE_MEMSET
#define MAGICKCORE_HAVE_MEMSET 1
#endif
/* Define to 1 if you have the `mkstemp' function. */
#ifndef MAGICKCORE_HAVE_MKSTEMP
#define MAGICKCORE_HAVE_MKSTEMP 1
#endif
/* Define to 1 if you have a working `mmap' system call. */
/* #undef HAVE_MMAP */
/* Define to 1 if you have the `munmap' function. */
#ifndef MAGICKCORE_HAVE_MUNMAP
#define MAGICKCORE_HAVE_MUNMAP 1
#endif
/* define if the compiler implements namespaces */
#ifndef MAGICKCORE_HAVE_NAMESPACES
#define MAGICKCORE_HAVE_NAMESPACES /**/
#endif
/* Define if g++ supports namespace std. */
#ifndef MAGICKCORE_HAVE_NAMESPACE_STD
#define MAGICKCORE_HAVE_NAMESPACE_STD /**/
#endif
/* Define to 1 if you have the `nanosleep' function. */
#ifndef MAGICKCORE_HAVE_NANOSLEEP
#define MAGICKCORE_HAVE_NANOSLEEP 1
#endif
/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
/* #undef HAVE_NDIR_H */
/* Define to 1 if you have the <netinet/in.h> header file. */
#ifndef MAGICKCORE_HAVE_NETINET_IN_H
#define MAGICKCORE_HAVE_NETINET_IN_H 1
#endif
/* Define to 1 if you have the `newlocale' function. */
#ifndef MAGICKCORE_HAVE_NEWLOCALE
#define MAGICKCORE_HAVE_NEWLOCALE 1
#endif
/* Define to 1 if you have the <OpenCL/cl.h> header file. */
/* #undef HAVE_OPENCL_CL_H */
/* Define to 1 if you have the <OS.h> header file. */
/* #undef HAVE_OS_H */
/* Define to 1 if you have the `pclose' function. */
#ifndef MAGICKCORE_HAVE_PCLOSE
#define MAGICKCORE_HAVE_PCLOSE 1
#endif
/* Define to 1 if you have the `poll' function. */
#ifndef MAGICKCORE_HAVE_POLL
#define MAGICKCORE_HAVE_POLL 1
#endif
/* Define to 1 if you have the `popen' function. */
#ifndef MAGICKCORE_HAVE_POPEN
#define MAGICKCORE_HAVE_POPEN 1
#endif
/* Define to 1 if you have the `posix_fadvise' function. */
#ifndef MAGICKCORE_HAVE_POSIX_FADVISE
#define MAGICKCORE_HAVE_POSIX_FADVISE 1
#endif
/* Define to 1 if you have the `posix_fallocate' function. */
#ifndef MAGICKCORE_HAVE_POSIX_FALLOCATE
#define MAGICKCORE_HAVE_POSIX_FALLOCATE 1
#endif
/* Define to 1 if you have the `posix_madvise' function. */
#ifndef MAGICKCORE_HAVE_POSIX_MADVISE
#define MAGICKCORE_HAVE_POSIX_MADVISE 1
#endif
/* Define to 1 if you have the `posix_memalign' function. */
#ifndef MAGICKCORE_HAVE_POSIX_MEMALIGN
#define MAGICKCORE_HAVE_POSIX_MEMALIGN 1
#endif
/* Define to 1 if you have the `posix_spawnp' function. */
#ifndef MAGICKCORE_HAVE_POSIX_SPAWNP
#define MAGICKCORE_HAVE_POSIX_SPAWNP 1
#endif
/* Define to 1 if you have the `pow' function. */
/* #undef HAVE_POW */
/* Define to 1 if you have the `pread' function. */
#ifndef MAGICKCORE_HAVE_PREAD
#define MAGICKCORE_HAVE_PREAD 1
#endif
/* Define to 1 if you have the <process.h> header file. */
/* #undef HAVE_PROCESS_H */
/* Define if you have POSIX threads libraries and header files. */
#ifndef MAGICKCORE_HAVE_PTHREAD
#define MAGICKCORE_HAVE_PTHREAD 1
#endif
/* Have PTHREAD_PRIO_INHERIT. */
#ifndef MAGICKCORE_HAVE_PTHREAD_PRIO_INHERIT
#define MAGICKCORE_HAVE_PTHREAD_PRIO_INHERIT 1
#endif
/* Define to 1 if you have the `pwrite' function. */
#ifndef MAGICKCORE_HAVE_PWRITE
#define MAGICKCORE_HAVE_PWRITE 1
#endif
/* Define to 1 if you have the `qsort_r' function. */
/* #undef HAVE_QSORT_R */
/* Define to 1 if you have the `raise' function. */
#ifndef MAGICKCORE_HAVE_RAISE
#define MAGICKCORE_HAVE_RAISE 1
#endif
/* Define to 1 if you have the `rand_r' function. */
#ifndef MAGICKCORE_HAVE_RAND_R
#define MAGICKCORE_HAVE_RAND_R 1
#endif
/* Define to 1 if you have the `readlink' function. */
#ifndef MAGICKCORE_HAVE_READLINK
#define MAGICKCORE_HAVE_READLINK 1
#endif
/* Define to 1 if you have the `realpath' function. */
#ifndef MAGICKCORE_HAVE_REALPATH
#define MAGICKCORE_HAVE_REALPATH 1
#endif
/* Define to 1 if you have the `seekdir' function. */
#ifndef MAGICKCORE_HAVE_SEEKDIR
#define MAGICKCORE_HAVE_SEEKDIR 1
#endif
/* Define to 1 if you have the `select' function. */
#ifndef MAGICKCORE_HAVE_SELECT
#define MAGICKCORE_HAVE_SELECT 1
#endif
/* Define to 1 if you have the `sendfile' function. */
#ifndef MAGICKCORE_HAVE_SENDFILE
#define MAGICKCORE_HAVE_SENDFILE 1
#endif
/* Define to 1 if you have the `setlocale' function. */
#ifndef MAGICKCORE_HAVE_SETLOCALE
#define MAGICKCORE_HAVE_SETLOCALE 1
#endif
/* Define to 1 if you have the `setvbuf' function. */
#ifndef MAGICKCORE_HAVE_SETVBUF
#define MAGICKCORE_HAVE_SETVBUF 1
#endif
/* X11 server supports shape extension */
/* #undef HAVE_SHAPE */
/* X11 server supports shared memory extension */
/* #undef HAVE_SHARED_MEMORY */
/* Define to 1 if you have the `sigaction' function. */
#ifndef MAGICKCORE_HAVE_SIGACTION
#define MAGICKCORE_HAVE_SIGACTION 1
#endif
/* Define to 1 if you have the `sigemptyset' function. */
#ifndef MAGICKCORE_HAVE_SIGEMPTYSET
#define MAGICKCORE_HAVE_SIGEMPTYSET 1
#endif
/* Define to 1 if you have the `socket' function. */
#ifndef MAGICKCORE_HAVE_SOCKET
#define MAGICKCORE_HAVE_SOCKET 1
#endif
/* Define to 1 if you have the `spawnvp' function. */
/* #undef HAVE_SPAWNVP */
/* Define to 1 if you have the `sqrt' function. */
#ifndef MAGICKCORE_HAVE_SQRT
#define MAGICKCORE_HAVE_SQRT 1
#endif
/* Define to 1 if you have the `stat' function. */
#ifndef MAGICKCORE_HAVE_STAT
#define MAGICKCORE_HAVE_STAT 1
#endif
/* Define to 1 if you have the <stdarg.h> header file. */
#ifndef MAGICKCORE_HAVE_STDARG_H
#define MAGICKCORE_HAVE_STDARG_H 1
#endif
/* Define to 1 if stdbool.h conforms to C99. */
#ifndef MAGICKCORE_HAVE_STDBOOL_H
#define MAGICKCORE_HAVE_STDBOOL_H 1
#endif
/* Define to 1 if you have the <stdint.h> header file. */
#ifndef MAGICKCORE_HAVE_STDINT_H
#define MAGICKCORE_HAVE_STDINT_H 1
#endif
/* Define to 1 if you have the <stdlib.h> header file. */
#ifndef MAGICKCORE_HAVE_STDLIB_H
#define MAGICKCORE_HAVE_STDLIB_H 1
#endif
/* define if the compiler supports ISO C++ standard library */
#ifndef MAGICKCORE_HAVE_STD_LIBS
#define MAGICKCORE_HAVE_STD_LIBS /**/
#endif
/* Define to 1 if you have the `strcasecmp' function. */
#ifndef MAGICKCORE_HAVE_STRCASECMP
#define MAGICKCORE_HAVE_STRCASECMP 1
#endif
/* Define to 1 if you have the `strcasestr' function. */
#ifndef MAGICKCORE_HAVE_STRCASESTR
#define MAGICKCORE_HAVE_STRCASESTR 1
#endif
/* Define to 1 if you have the `strchr' function. */
#ifndef MAGICKCORE_HAVE_STRCHR
#define MAGICKCORE_HAVE_STRCHR 1
#endif
/* Define to 1 if you have the `strcspn' function. */
#ifndef MAGICKCORE_HAVE_STRCSPN
#define MAGICKCORE_HAVE_STRCSPN 1
#endif
/* Define to 1 if you have the `strdup' function. */
#ifndef MAGICKCORE_HAVE_STRDUP
#define MAGICKCORE_HAVE_STRDUP 1
#endif
/* Define to 1 if you have the `strerror' function. */
#ifndef MAGICKCORE_HAVE_STRERROR
#define MAGICKCORE_HAVE_STRERROR 1
#endif
/* Define to 1 if you have the `strerror_r' function. */
#ifndef MAGICKCORE_HAVE_STRERROR_R
#define MAGICKCORE_HAVE_STRERROR_R 1
#endif
/* Define to 1 if cpp supports the ANSI # stringizing operator. */
#ifndef MAGICKCORE_HAVE_STRINGIZE
#define MAGICKCORE_HAVE_STRINGIZE 1
#endif
/* Define to 1 if you have the <strings.h> header file. */
#ifndef MAGICKCORE_HAVE_STRINGS_H
#define MAGICKCORE_HAVE_STRINGS_H 1
#endif
/* Define to 1 if you have the <string.h> header file. */
#ifndef MAGICKCORE_HAVE_STRING_H
#define MAGICKCORE_HAVE_STRING_H 1
#endif
/* Define to 1 if you have the `strlcat' function. */
#ifndef MAGICKCORE_HAVE_STRLCAT
#define MAGICKCORE_HAVE_STRLCAT 1
#endif
/* Define to 1 if you have the `strlcpy' function. */
#ifndef MAGICKCORE_HAVE_STRLCPY
#define MAGICKCORE_HAVE_STRLCPY 1
#endif
/* Define to 1 if you have the `strncasecmp' function. */
#ifndef MAGICKCORE_HAVE_STRNCASECMP
#define MAGICKCORE_HAVE_STRNCASECMP 1
#endif
/* Define to 1 if you have the `strpbrk' function. */
#ifndef MAGICKCORE_HAVE_STRPBRK
#define MAGICKCORE_HAVE_STRPBRK 1
#endif
/* Define to 1 if you have the `strrchr' function. */
#ifndef MAGICKCORE_HAVE_STRRCHR
#define MAGICKCORE_HAVE_STRRCHR 1
#endif
/* Define to 1 if you have the `strspn' function. */
#ifndef MAGICKCORE_HAVE_STRSPN
#define MAGICKCORE_HAVE_STRSPN 1
#endif
/* Define to 1 if you have the `strstr' function. */
#ifndef MAGICKCORE_HAVE_STRSTR
#define MAGICKCORE_HAVE_STRSTR 1
#endif
/* Define to 1 if you have the `strtod' function. */
/* #undef HAVE_STRTOD */
/* Define to 1 if you have the `strtod_l' function. */
#ifndef MAGICKCORE_HAVE_STRTOD_L
#define MAGICKCORE_HAVE_STRTOD_L 1
#endif
/* Define to 1 if you have the `strtol' function. */
#ifndef MAGICKCORE_HAVE_STRTOL
#define MAGICKCORE_HAVE_STRTOL 1
#endif
/* Define to 1 if you have the `strtoul' function. */
#ifndef MAGICKCORE_HAVE_STRTOUL
#define MAGICKCORE_HAVE_STRTOUL 1
#endif
/* Define to 1 if `tm_zone' is a member of `struct tm'. */
#ifndef MAGICKCORE_HAVE_STRUCT_TM_TM_ZONE
#define MAGICKCORE_HAVE_STRUCT_TM_TM_ZONE 1
#endif
/* Define to 1 if you have the <sun_prefetch.h> header file. */
/* #undef HAVE_SUN_PREFETCH_H */
/* Define to 1 if you have the `symlink' function. */
#ifndef MAGICKCORE_HAVE_SYMLINK
#define MAGICKCORE_HAVE_SYMLINK 1
#endif
/* Define to 1 if you have the `sysconf' function. */
#ifndef MAGICKCORE_HAVE_SYSCONF
#define MAGICKCORE_HAVE_SYSCONF 1
#endif
/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
*/
/* #undef HAVE_SYS_DIR_H */
/* Define to 1 if you have the <sys/ipc.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_IPC_H
#define MAGICKCORE_HAVE_SYS_IPC_H 1
#endif
/* Define to 1 if you have the <sys/mman.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_MMAN_H
#define MAGICKCORE_HAVE_SYS_MMAN_H 1
#endif
/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
*/
/* #undef HAVE_SYS_NDIR_H */
/* Define to 1 if you have the <sys/param.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_PARAM_H
#define MAGICKCORE_HAVE_SYS_PARAM_H 1
#endif
/* Define to 1 if you have the <sys/resource.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_RESOURCE_H
#define MAGICKCORE_HAVE_SYS_RESOURCE_H 1
#endif
/* Define to 1 if you have the <sys/select.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_SELECT_H
#define MAGICKCORE_HAVE_SYS_SELECT_H 1
#endif
/* Define to 1 if you have the <sys/sendfile.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_SENDFILE_H
#define MAGICKCORE_HAVE_SYS_SENDFILE_H 1
#endif
/* Define to 1 if you have the <sys/socket.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_SOCKET_H
#define MAGICKCORE_HAVE_SYS_SOCKET_H 1
#endif
/* Define to 1 if you have the <sys/stat.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_STAT_H
#define MAGICKCORE_HAVE_SYS_STAT_H 1
#endif
/* Define to 1 if you have the <sys/syslimits.h> header file. */
/* #undef HAVE_SYS_SYSLIMITS_H */
/* Define to 1 if you have the <sys/timeb.h> header file. */
/* #undef HAVE_SYS_TIMEB_H */
/* Define to 1 if you have the <sys/times.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_TIMES_H
#define MAGICKCORE_HAVE_SYS_TIMES_H 1
#endif
/* Define to 1 if you have the <sys/time.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_TIME_H
#define MAGICKCORE_HAVE_SYS_TIME_H 1
#endif
/* Define to 1 if you have the <sys/types.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_TYPES_H
#define MAGICKCORE_HAVE_SYS_TYPES_H 1
#endif
/* Define to 1 if you have the <sys/wait.h> header file. */
#ifndef MAGICKCORE_HAVE_SYS_WAIT_H
#define MAGICKCORE_HAVE_SYS_WAIT_H 1
#endif
/* Define if you have the tcmalloc memory allocation library */
/* #undef HAVE_TCMALLOC */
/* Define to 1 if you have the `telldir' function. */
#ifndef MAGICKCORE_HAVE_TELLDIR
#define MAGICKCORE_HAVE_TELLDIR 1
#endif
/* Define to 1 if you have the `tempnam' function. */
#ifndef MAGICKCORE_HAVE_TEMPNAM
#define MAGICKCORE_HAVE_TEMPNAM 1
#endif
/* Define to 1 if you have the <tiffconf.h> header file. */
/* #undef HAVE_TIFFCONF_H */
/* Define to 1 if you have the `TIFFIsBigEndian' function. */
/* #undef HAVE_TIFFISBIGENDIAN */
/* Define to 1 if you have the `TIFFIsCODECConfigured' function. */
/* #undef HAVE_TIFFISCODECCONFIGURED */
/* Define to 1 if you have the `TIFFMergeFieldInfo' function. */
/* #undef HAVE_TIFFMERGEFIELDINFO */
/* Define to 1 if you have the `TIFFReadEXIFDirectory' function. */
/* #undef HAVE_TIFFREADEXIFDIRECTORY */
/* Define to 1 if you have the `TIFFSetErrorHandlerExt' function. */
/* #undef HAVE_TIFFSETERRORHANDLEREXT */
/* Define to 1 if you have the `TIFFSetTagExtender' function. */
/* #undef HAVE_TIFFSETTAGEXTENDER */
/* Define to 1 if you have the `TIFFSetWarningHandlerExt' function. */
/* #undef HAVE_TIFFSETWARNINGHANDLEREXT */
/* Define to 1 if you have the `TIFFSwabArrayOfTriples' function. */
/* #undef HAVE_TIFFSWABARRAYOFTRIPLES */
/* Define to 1 if you have the `times' function. */
#ifndef MAGICKCORE_HAVE_TIMES
#define MAGICKCORE_HAVE_TIMES 1
#endif
/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use
`HAVE_STRUCT_TM_TM_ZONE' instead. */
#ifndef MAGICKCORE_HAVE_TM_ZONE
#define MAGICKCORE_HAVE_TM_ZONE 1
#endif
/* Define to 1 if you don't have `tm_zone' but do have the external array
`tzname'. */
/* #undef HAVE_TZNAME */
/* Define to 1 if the system has the type `uintmax_t'. */
#ifndef MAGICKCORE_HAVE_UINTMAX_T
#define MAGICKCORE_HAVE_UINTMAX_T 1
#endif
/* Define to 1 if the system has the type `uintptr_t'. */
#ifndef MAGICKCORE_HAVE_UINTPTR_T
#define MAGICKCORE_HAVE_UINTPTR_T 1
#endif
/* Define to 1 if you have the `ulltostr' function. */
/* #undef HAVE_ULLTOSTR */
/* Define if you have umem memory allocation library */
/* #undef HAVE_UMEM */
/* Define to 1 if you have the <unistd.h> header file. */
#ifndef MAGICKCORE_HAVE_UNISTD_H
#define MAGICKCORE_HAVE_UNISTD_H 1
#endif
/* Define to 1 if the system has the type `unsigned long long int'. */
#ifndef MAGICKCORE_HAVE_UNSIGNED_LONG_LONG_INT
#define MAGICKCORE_HAVE_UNSIGNED_LONG_LONG_INT 1
#endif
/* Define to 1 if you have the `uselocale' function. */
#ifndef MAGICKCORE_HAVE_USELOCALE
#define MAGICKCORE_HAVE_USELOCALE 1
#endif
/* Define to 1 if you have the `usleep' function. */
#ifndef MAGICKCORE_HAVE_USLEEP
#define MAGICKCORE_HAVE_USLEEP 1
#endif
/* Define to 1 if you have the `utime' function. */
#ifndef MAGICKCORE_HAVE_UTIME
#define MAGICKCORE_HAVE_UTIME 1
#endif
/* Define to 1 if you have the <utime.h> header file. */
#ifndef MAGICKCORE_HAVE_UTIME_H
#define MAGICKCORE_HAVE_UTIME_H 1
#endif
/* Define to 1 if you have the `vfork' function. */
#ifndef MAGICKCORE_HAVE_VFORK
#define MAGICKCORE_HAVE_VFORK 1
#endif
/* Define to 1 if you have the <vfork.h> header file. */
/* #undef HAVE_VFORK_H */
/* Define to 1 if you have the `vfprintf' function. */
#ifndef MAGICKCORE_HAVE_VFPRINTF
#define MAGICKCORE_HAVE_VFPRINTF 1
#endif
/* Define to 1 if you have the `vfprintf_l' function. */
/* #undef HAVE_VFPRINTF_L */
/* Define to 1 if you have the `vprintf' function. */
#ifndef MAGICKCORE_HAVE_VPRINTF
#define MAGICKCORE_HAVE_VPRINTF 1
#endif
/* Define to 1 if you have the `vsnprintf' function. */
#ifndef MAGICKCORE_HAVE_VSNPRINTF
#define MAGICKCORE_HAVE_VSNPRINTF 1
#endif
/* Define to 1 if you have the `vsnprintf_l' function. */
/* #undef HAVE_VSNPRINTF_L */
/* Define to 1 if you have the `vsprintf' function. */
#ifndef MAGICKCORE_HAVE_VSPRINTF
#define MAGICKCORE_HAVE_VSPRINTF 1
#endif
/* Define to 1 if you have the `waitpid' function. */
#ifndef MAGICKCORE_HAVE_WAITPID
#define MAGICKCORE_HAVE_WAITPID 1
#endif
/* Define to 1 if you have the <wchar.h> header file. */
#ifndef MAGICKCORE_HAVE_WCHAR_H
#define MAGICKCORE_HAVE_WCHAR_H 1
#endif
/* Define to 1 if you have the <windows.h> header file. */
/* #undef HAVE_WINDOWS_H */
/* Define to 1 if `fork' works. */
#ifndef MAGICKCORE_HAVE_WORKING_FORK
#define MAGICKCORE_HAVE_WORKING_FORK 1
#endif
/* Define to 1 if `vfork' works. */
#ifndef MAGICKCORE_HAVE_WORKING_VFORK
#define MAGICKCORE_HAVE_WORKING_VFORK 1
#endif
/* Define to 1 if you have the <xlocale.h> header file. */
#ifndef MAGICKCORE_HAVE_XLOCALE_H
#define MAGICKCORE_HAVE_XLOCALE_H 1
#endif
/* Define to 1 if you have the `_aligned_malloc' function. */
/* #undef HAVE__ALIGNED_MALLOC */
/* Define to 1 if the system has the type `_Bool'. */
#ifndef MAGICKCORE_HAVE__BOOL
#define MAGICKCORE_HAVE__BOOL 1
#endif
/* Define to 1 if you have the `_exit' function. */
#ifndef MAGICKCORE_HAVE__EXIT
#define MAGICKCORE_HAVE__EXIT 1
#endif
/* Define to 1 if you have the `_NSGetExecutablePath' function. */
/* #undef HAVE__NSGETEXECUTABLEPATH */
/* Define to 1 if you have the `_pclose' function. */
/* #undef HAVE__PCLOSE */
/* Define to 1 if you have the `_popen' function. */
/* #undef HAVE__POPEN */
/* Define to 1 if you have the `_wfopen' function. */
/* #undef HAVE__WFOPEN */
/* Define to 1 if you have the `_wstat' function. */
/* #undef HAVE__WSTAT */
/* define if your compiler has __attribute__ */
#ifndef MAGICKCORE_HAVE___ATTRIBUTE__
#define MAGICKCORE_HAVE___ATTRIBUTE__ 1
#endif
/* Whether hdri is enabled or not */
#ifndef MAGICKCORE_HDRI_ENABLE_OBSOLETE_IN_H
#define MAGICKCORE_HDRI_ENABLE_OBSOLETE_IN_H 1
#endif
/* Define if you have libheif library */
/* #undef HEIC_DELEGATE */
/* Define if you have jemalloc memory allocation library */
/* #undef HasJEMALLOC */
/* Directory where ImageMagick architecture headers live. */
#ifndef MAGICKCORE_INCLUDEARCH_PATH
#define MAGICKCORE_INCLUDEARCH_PATH "/usr/local/include/ImageMagick-7/"
#endif
/* Directory where ImageMagick headers live. */
#ifndef MAGICKCORE_INCLUDE_PATH
#define MAGICKCORE_INCLUDE_PATH "/usr/local/include/ImageMagick-7/"
#endif
/* ImageMagick is formally installed under prefix */
#ifndef MAGICKCORE_INSTALLED_SUPPORT
#define MAGICKCORE_INSTALLED_SUPPORT 1
#endif
/* Define if you have JBIG library */
/* #undef JBIG_DELEGATE */
/* Define if you have JPEG library */
/* #undef JPEG_DELEGATE */
/* Define if you have brunsli library */
/* #undef JXL_DELEGATE */
/* Define if you have LCMS library */
/* #undef LCMS_DELEGATE */
/* Define if you have OPENJP2 library */
/* #undef LIBOPENJP2_DELEGATE */
/* Directory where architecture-dependent files live. */
#ifndef MAGICKCORE_LIBRARY_PATH
#define MAGICKCORE_LIBRARY_PATH "/usr/local/lib/ImageMagick-7.0.9/"
#endif
/* Subdirectory of lib where ImageMagick architecture dependent files are
installed. */
#ifndef MAGICKCORE_LIBRARY_RELATIVE_PATH
#define MAGICKCORE_LIBRARY_RELATIVE_PATH "ImageMagick-7.0.9"
#endif
/* Binaries in libraries path base name (will be during install linked to bin)
*/
#ifndef MAGICKCORE_LIB_BIN_BASEDIRNAME
#define MAGICKCORE_LIB_BIN_BASEDIRNAME "bin"
#endif
/* Define if you have LQR library */
/* #undef LQR_DELEGATE */
/* Define if using libltdl to support dynamically loadable modules and OpenCL
*/
/* #undef LTDL_DELEGATE */
/* Native module suffix */
/* #undef LTDL_MODULE_EXT */
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#ifndef MAGICKCORE_LT_OBJDIR
#define MAGICKCORE_LT_OBJDIR ".libs/"
#endif
/* Define if you have LZMA library */
/* #undef LZMA_DELEGATE */
/* Define to prepend to default font search path. */
/* #undef MAGICK_FONT_PATH */
/* Target Host CPU */
#ifndef MAGICKCORE_MAGICK_TARGET_CPU
#define MAGICKCORE_MAGICK_TARGET_CPU i686
#endif
/* Target Host OS */
#ifndef MAGICKCORE_MAGICK_TARGET_OS
#define MAGICKCORE_MAGICK_TARGET_OS linux-android
#endif
/* Target Host Vendor */
#ifndef MAGICKCORE_MAGICK_TARGET_VENDOR
#define MAGICKCORE_MAGICK_TARGET_VENDOR pc
#endif
/* Module directory name without ABI part. */
#ifndef MAGICKCORE_MODULES_BASEDIRNAME
#define MAGICKCORE_MODULES_BASEDIRNAME "modules"
#endif
/* Module directory dirname */
/* #undef MODULES_DIRNAME */
/* Magick API method prefix */
/* #undef NAMESPACE_PREFIX */
/* Magick API method prefix tag */
/* #undef NAMESPACE_PREFIX_TAG */
/* Define to 1 if assertions should be disabled. */
/* #undef NDEBUG */
/* Define if you have OPENEXR library */
/* #undef OPENEXR_DELEGATE */
/* Name of package */
#ifndef MAGICKCORE_PACKAGE
#define MAGICKCORE_PACKAGE "ImageMagick"
#endif
/* Define to the address where bug reports for this package should be sent. */
#ifndef MAGICKCORE_PACKAGE_BUGREPORT
#define MAGICKCORE_PACKAGE_BUGREPORT "https://github.com/ImageMagick/ImageMagick/issues"
#endif
/* Define to the full name of this package. */
#ifndef MAGICKCORE_PACKAGE_NAME
#define MAGICKCORE_PACKAGE_NAME "ImageMagick"
#endif
/* Define to the full name and version of this package. */
#ifndef MAGICKCORE_PACKAGE_STRING
#define MAGICKCORE_PACKAGE_STRING "ImageMagick 7.0.9-13"
#endif
/* Define to the one symbol short name of this package. */
#ifndef MAGICKCORE_PACKAGE_TARNAME
#define MAGICKCORE_PACKAGE_TARNAME "ImageMagick"
#endif
/* Define to the home page for this package. */
#ifndef MAGICKCORE_PACKAGE_URL
#define MAGICKCORE_PACKAGE_URL "https://imagemagick.org"
#endif
/* Define to the version of this package. */
#ifndef MAGICKCORE_PACKAGE_VERSION
#define MAGICKCORE_PACKAGE_VERSION "7.0.9-13"
#endif
/* Define if you have PANGOCAIRO library */
/* #undef PANGOCAIRO_DELEGATE */
/* Define if you have PANGO library */
/* #undef PANGO_DELEGATE */
/* enable pipes (|) in filenames */
/* #undef PIPES_SUPPORT */
/* Define if you have PNG library */
/* #undef PNG_DELEGATE */
/* Define to necessary symbol if this constant uses a non-standard name on
your system. */
/* #undef PTHREAD_CREATE_JOINABLE */
/* Pixel cache threshold in MB (defaults to available memory) */
/* #undef PixelCacheThreshold */
/* Number of bits in a pixel Quantum (8/16/32/64) */
#ifndef MAGICKCORE_QUANTUM_DEPTH_OBSOLETE_IN_H
#define MAGICKCORE_QUANTUM_DEPTH_OBSOLETE_IN_H 16
#endif
/* Define if you have RAQM library */
/* #undef RAQM_DELEGATE */
/* Define if you have LIBRAW library */
/* #undef RAW_R_DELEGATE */
/* Define if you have RSVG library */
/* #undef RSVG_DELEGATE */
/* Define to the type of arg 1 for `select'. */
#ifndef MAGICKCORE_SELECT_TYPE_ARG1
#define MAGICKCORE_SELECT_TYPE_ARG1 int
#endif
/* Define to the type of args 2, 3 and 4 for `select'. */
#ifndef MAGICKCORE_SELECT_TYPE_ARG234
#define MAGICKCORE_SELECT_TYPE_ARG234 (fd_set *)
#endif
/* Define to the type of arg 5 for `select'. */
#ifndef MAGICKCORE_SELECT_TYPE_ARG5
#define MAGICKCORE_SELECT_TYPE_ARG5 (struct timeval *)
#endif
/* Sharearch directory name without ABI part. */
#ifndef MAGICKCORE_SHAREARCH_BASEDIRNAME
#define MAGICKCORE_SHAREARCH_BASEDIRNAME "config"
#endif
/* Sharearch directory dirname */
/* #undef SHAREARCH_DIRNAME */
/* Directory where architecture-independent configuration files live. */
#ifndef MAGICKCORE_SHARE_PATH
#define MAGICKCORE_SHARE_PATH "/usr/local/share/ImageMagick-7/"
#endif
/* Subdirectory of lib where architecture-independent configuration files
live. */
#ifndef MAGICKCORE_SHARE_RELATIVE_PATH
#define MAGICKCORE_SHARE_RELATIVE_PATH "ImageMagick-7"
#endif
/* The size of `double', as computed by sizeof. */
#ifndef MAGICKCORE_SIZEOF_DOUBLE
#define MAGICKCORE_SIZEOF_DOUBLE 8
#endif
/* The size of `double_t', as computed by sizeof. */
#ifndef MAGICKCORE_SIZEOF_DOUBLE_T
#define MAGICKCORE_SIZEOF_DOUBLE_T 8
#endif
/* The size of `float', as computed by sizeof. */
#ifndef MAGICKCORE_SIZEOF_FLOAT
#define MAGICKCORE_SIZEOF_FLOAT 4
#endif
/* The size of `float_t', as computed by sizeof. */
#ifndef MAGICKCORE_SIZEOF_FLOAT_T
#define MAGICKCORE_SIZEOF_FLOAT_T 4
#endif
/* The size of `long double', as computed by sizeof. */
#ifndef MAGICKCORE_SIZEOF_LONG_DOUBLE
#define MAGICKCORE_SIZEOF_LONG_DOUBLE 8
#endif
/* The size of `unsigned long long', as computed by sizeof. */
#ifndef MAGICKCORE_SIZEOF_UNSIGNED_LONG_LONG
#define MAGICKCORE_SIZEOF_UNSIGNED_LONG_LONG 8
#endif
/* The size of `void *', as computed by sizeof. */
#ifndef MAGICKCORE_SIZEOF_VOID_P
#define MAGICKCORE_SIZEOF_VOID_P 4
#endif
/* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
/* #undef STAT_MACROS_BROKEN */
/* Define to 1 if you have the ANSI C header files. */
#ifndef MAGICKCORE_STDC_HEADERS
#define MAGICKCORE_STDC_HEADERS 1
#endif
/* Define to 1 if strerror_r returns char *. */
#ifndef MAGICKCORE_STRERROR_R_CHAR_P
#define MAGICKCORE_STRERROR_R_CHAR_P 1
#endif
/* Define if you have POSIX threads libraries and header files. */
#ifndef MAGICKCORE_THREAD_SUPPORT
#define MAGICKCORE_THREAD_SUPPORT 1
#endif
/* Define if you have TIFF library */
/* #undef TIFF_DELEGATE */
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#ifndef MAGICKCORE_TIME_WITH_SYS_TIME
#define MAGICKCORE_TIME_WITH_SYS_TIME 1
#endif
/* Define to 1 if your <sys/time.h> declares `struct tm'. */
/* #undef TM_IN_SYS_TIME */
/* Enable extensions on AIX 3, Interix. */
#ifndef _ALL_SOURCE
# define _ALL_SOURCE 1
#endif
/* Enable GNU extensions on systems that have them. */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
/* Enable threading extensions on Solaris. */
#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS 1
#endif
/* Enable extensions on HP NonStop. */
#ifndef _TANDEM_SOURCE
# define _TANDEM_SOURCE 1
#endif
/* Enable general extensions on Solaris. */
#ifndef __EXTENSIONS__
# define __EXTENSIONS__ 1
#endif
/* Version number of package */
#ifndef MAGICKCORE_VERSION
#define MAGICKCORE_VERSION "7.0.9-13"
#endif
/* Define if you have WEBPMUX library */
/* #undef WEBPMUX_DELEGATE */
/* Define if you have WEBP library */
/* #undef WEBP_DELEGATE */
/* Define to use the Windows GDI32 library */
/* #undef WINGDI32_DELEGATE */
/* Define if using the dmalloc debugging malloc package */
/* #undef WITH_DMALLOC */
/* Define if you have WMF library */
/* #undef WMF_DELEGATE */
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Location of X11 configure files */
#ifndef MAGICKCORE_X11_CONFIGURE_PATH
#define MAGICKCORE_X11_CONFIGURE_PATH ""
#endif
/* Define if you have X11 library */
/* #undef X11_DELEGATE */
/* Define if you have XML library */
/* #undef XML_DELEGATE */
/* Define to 1 if the X Window System is missing or not being used. */
#ifndef MAGICKCORE_X_DISPLAY_MISSING
#define MAGICKCORE_X_DISPLAY_MISSING 1
#endif
/* Build self-contained, embeddable, zero-configuration ImageMagick */
/* #undef ZERO_CONFIGURATION_SUPPORT */
/* Define if you have ZLIB library */
/* #undef ZLIB_DELEGATE */
/* Define if you have ZSTD library */
/* #undef ZSTD_DELEGATE */
/* Enable large inode numbers on Mac OS X 10.5. */
#ifndef _DARWIN_USE_64_BIT_INODE
# define _DARWIN_USE_64_BIT_INODE 1
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
#ifndef MAGICKCORE__FILE_OFFSET_BITS
#define MAGICKCORE__FILE_OFFSET_BITS 64
#endif
/* enable run-time bounds-checking */
/* #undef _FORTIFY_SOURCE */
/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
/* #undef _LARGEFILE_SOURCE */
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define to 1 if on MINIX. */
/* #undef _MINIX */
/* Define this for the OpenCL Accelerator */
/* #undef _OPENCL */
/* Define to 2 if the system does not provide POSIX.1 features except with
this defined. */
/* #undef _POSIX_1_SOURCE */
/* Define to 1 if you need to in order for `stat' and other things to work. */
/* #undef _POSIX_SOURCE */
/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT32_T */
/* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT64_T */
/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT8_T */
/* Define to 1 if type `char' is unsigned and you are not using gcc. */
#ifndef __CHAR_UNSIGNED__
/* # undef __CHAR_UNSIGNED__ */
#endif
/* Define to appropriate substitute if compiler does not have __func__ */
/* #undef __func__ */
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef gid_t */
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
/* #undef inline */
#endif
/* Define to the type of a signed integer type of width exactly 16 bits if
such a type exists and the standard includes do not define it. */
/* #undef int16_t */
/* Define to the type of a signed integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
/* #undef int32_t */
/* Define to the type of a signed integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
/* #undef int64_t */
/* Define to the type of a signed integer type of width exactly 8 bits if such
a type exists and the standard includes do not define it. */
/* #undef int8_t */
/* Define to the widest signed integer type if <stdint.h> and <inttypes.h> do
not define. */
/* #undef intmax_t */
/* Define to the type of a signed integer type wide enough to hold a pointer,
if such a type exists, and if the system does not define it. */
/* #undef intptr_t */
/* Define to a type if <wchar.h> does not define. */
/* #undef mbstate_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef mode_t */
/* Define to `long int' if <sys/types.h> does not define. */
/* #undef off_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef pid_t */
/* Define to the equivalent of the C99 'restrict' keyword, or to
nothing if this is not supported. Do not define if restrict is
supported directly. */
#ifndef _magickcore_restrict
#define _magickcore_restrict __restrict
#endif
/* Work around a bug in Sun C++: it does not support _Restrict or
__restrict__, even though the corresponding Sun C compiler ends up with
"#define restrict _Restrict" or "#define restrict __restrict__" in the
previous line. Perhaps some future version of Sun C++ will work with
restrict; if so, hopefully it defines __RESTRICT like Sun C does. */
#if defined __SUNPRO_CC && !defined __RESTRICT
# define _Restrict
# define __restrict__
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef uid_t */
/* Define to the type of an unsigned integer type of width exactly 16 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint16_t */
/* Define to the type of an unsigned integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint32_t */
/* Define to the type of an unsigned integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint64_t */
/* Define to the type of an unsigned integer type of width exactly 8 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint8_t */
/* Define to the widest unsigned integer type if <stdint.h> and <inttypes.h>
do not define. */
/* #undef uintmax_t */
/* Define to the type of an unsigned integer type wide enough to hold a
pointer, if such a type exists, and if the system does not define it. */
/* #undef uintptr_t */
/* Define as `fork' if `vfork' does not work. */
/* #undef vfork */
/* Define to empty if the keyword `volatile' does not work. Warning: valid
code using `volatile' can become incorrect without. Disable with care. */
/* #undef volatile */
/* once: _MAGICKCORE_MAGICK_BASECONFIG_H */
#endif
| 27.891805 | 88 | 0.755044 | [
"shape"
] |
36f0d474e9e8ce09a0014965344e1ab139be1d94 | 33,492 | c | C | spa/plugins/bluez5/sco-source.c | thiolliere/pipewire | 6e2f78fffccdae266a271dcf1d6cd72b3dd1e36b | [
"MIT"
] | null | null | null | spa/plugins/bluez5/sco-source.c | thiolliere/pipewire | 6e2f78fffccdae266a271dcf1d6cd72b3dd1e36b | [
"MIT"
] | null | null | null | spa/plugins/bluez5/sco-source.c | thiolliere/pipewire | 6e2f78fffccdae266a271dcf1d6cd72b3dd1e36b | [
"MIT"
] | null | null | null | /* Spa SCO Source
*
* Copyright © 2019 Collabora Ltd.
*
* 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <unistd.h>
#include <stddef.h>
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <spa/support/plugin.h>
#include <spa/support/loop.h>
#include <spa/support/log.h>
#include <spa/support/system.h>
#include <spa/utils/list.h>
#include <spa/utils/keys.h>
#include <spa/utils/names.h>
#include <spa/monitor/device.h>
#include <spa/node/node.h>
#include <spa/node/utils.h>
#include <spa/node/io.h>
#include <spa/node/keys.h>
#include <spa/param/param.h>
#include <spa/param/audio/format.h>
#include <spa/param/audio/format-utils.h>
#include <spa/pod/filter.h>
#include <sbc/sbc.h>
#include "defs.h"
struct props {
uint32_t min_latency;
uint32_t max_latency;
};
#define MAX_BUFFERS 32
struct buffer {
uint32_t id;
unsigned int outstanding:1;
struct spa_buffer *buf;
struct spa_meta_header *h;
struct spa_list link;
};
struct port {
struct spa_audio_info current_format;
int frame_size;
unsigned int have_format:1;
uint64_t info_all;
struct spa_port_info info;
struct spa_io_buffers *io;
struct spa_io_rate_match *rate_match;
struct spa_param_info params[8];
struct buffer buffers[MAX_BUFFERS];
uint32_t n_buffers;
struct spa_list free;
struct spa_list ready;
struct buffer *current_buffer;
uint32_t ready_offset;
};
struct impl {
struct spa_handle handle;
struct spa_node node;
struct spa_log *log;
struct spa_loop *data_loop;
struct spa_system *data_system;
struct spa_hook_list hooks;
struct spa_callbacks callbacks;
uint64_t info_all;
struct spa_node_info info;
struct spa_param_info params[8];
struct props props;
struct spa_bt_transport *transport;
struct spa_hook transport_listener;
struct port port;
unsigned int started:1;
struct spa_io_clock *clock;
struct spa_io_position *position;
/* mSBC */
sbc_t msbc;
bool msbc_seq_initialized;
uint8_t msbc_seq;
/* mSBC frame parsing */
uint8_t msbc_buffer[MSBC_ENCODED_SIZE];
uint8_t msbc_buffer_pos;
struct timespec now;
};
#define NAME "sco-source"
#define CHECK_PORT(this,d,p) ((d) == SPA_DIRECTION_OUTPUT && (p) == 0)
static const uint32_t default_min_latency = 128;
static const uint32_t default_max_latency = 512;
static void reset_props(struct props *props)
{
props->min_latency = default_min_latency;
props->max_latency = default_max_latency;
}
static int impl_node_enum_params(void *object, int seq,
uint32_t id, uint32_t start, uint32_t num,
const struct spa_pod *filter)
{
struct impl *this = object;
struct spa_pod *param;
struct spa_pod_builder b = { 0 };
uint8_t buffer[1024];
struct spa_result_node_params result;
uint32_t count = 0;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_return_val_if_fail(num != 0, -EINVAL);
result.id = id;
result.next = start;
next:
result.index = result.next++;
spa_pod_builder_init(&b, buffer, sizeof(buffer));
switch (id) {
case SPA_PARAM_PropInfo:
{
struct props *p = &this->props;
switch (result.index) {
case 0:
param = spa_pod_builder_add_object(&b,
SPA_TYPE_OBJECT_PropInfo, id,
SPA_PROP_INFO_id, SPA_POD_Id(SPA_PROP_minLatency),
SPA_PROP_INFO_name, SPA_POD_String("The minimum latency"),
SPA_PROP_INFO_type, SPA_POD_CHOICE_RANGE_Int(p->min_latency, 1, INT32_MAX));
break;
case 1:
param = spa_pod_builder_add_object(&b,
SPA_TYPE_OBJECT_PropInfo, id,
SPA_PROP_INFO_id, SPA_POD_Id(SPA_PROP_maxLatency),
SPA_PROP_INFO_name, SPA_POD_String("The maximum latency"),
SPA_PROP_INFO_type, SPA_POD_CHOICE_RANGE_Int(p->max_latency, 1, INT32_MAX));
break;
default:
return 0;
}
break;
}
case SPA_PARAM_Props:
{
struct props *p = &this->props;
switch (result.index) {
case 0:
param = spa_pod_builder_add_object(&b,
SPA_TYPE_OBJECT_Props, id,
SPA_PROP_minLatency, SPA_POD_Int(p->min_latency),
SPA_PROP_maxLatency, SPA_POD_Int(p->max_latency));
break;
default:
return 0;
}
break;
}
default:
return -ENOENT;
}
if (spa_pod_filter(&b, &result.param, param, filter) < 0)
goto next;
spa_node_emit_result(&this->hooks, seq, 0, SPA_RESULT_TYPE_NODE_PARAMS, &result);
if (++count != num)
goto next;
return 0;
}
static int impl_node_set_io(void *object, uint32_t id, void *data, size_t size)
{
struct impl *this = object;
spa_return_val_if_fail(this != NULL, -EINVAL);
switch (id) {
case SPA_IO_Clock:
this->clock = data;
break;
case SPA_IO_Position:
this->position = data;
break;
default:
return -ENOENT;
}
return 0;
}
static void emit_node_info(struct impl *this, bool full);
static int apply_props(struct impl *this, const struct spa_pod *param)
{
struct props new_props = this->props;
int changed = 0;
if (param == NULL) {
reset_props(&new_props);
} else {
spa_pod_parse_object(param,
SPA_TYPE_OBJECT_Props, NULL,
SPA_PROP_minLatency, SPA_POD_OPT_Int(&new_props.min_latency),
SPA_PROP_maxLatency, SPA_POD_OPT_Int(&new_props.max_latency));
}
changed = (memcmp(&new_props, &this->props, sizeof(struct props)) != 0);
this->props = new_props;
return changed;
}
static int impl_node_set_param(void *object, uint32_t id, uint32_t flags,
const struct spa_pod *param)
{
struct impl *this = object;
spa_return_val_if_fail(this != NULL, -EINVAL);
switch (id) {
case SPA_PARAM_Props:
{
if (apply_props(this, param) > 0) {
this->info.change_mask |= SPA_NODE_CHANGE_MASK_PARAMS;
this->params[1].flags ^= SPA_PARAM_INFO_SERIAL;
emit_node_info(this, false);
}
break;
}
default:
return -ENOENT;
}
return 0;
}
static void reset_buffers(struct port *port)
{
uint32_t i;
spa_list_init(&port->free);
spa_list_init(&port->ready);
port->current_buffer = NULL;
for (i = 0; i < port->n_buffers; i++) {
struct buffer *b = &port->buffers[i];
spa_list_append(&port->free, &b->link);
b->outstanding = false;
}
}
static void recycle_buffer(struct impl *this, struct port *port, uint32_t buffer_id)
{
struct buffer *b = &port->buffers[buffer_id];
if (b->outstanding) {
spa_log_trace(this->log, NAME " %p: recycle buffer %u", this, buffer_id);
spa_list_append(&port->free, &b->link);
b->outstanding = false;
}
}
/* Append data to msbc buffer, syncing buffer start to frame headers */
static void msbc_buffer_append_byte(struct impl *this, uint8_t byte)
{
/* Parse mSBC frame header */
if (this->msbc_buffer_pos == 0) {
if (byte != 0x01) {
this->msbc_buffer_pos = 0;
return;
}
}
else if (this->msbc_buffer_pos == 1) {
if (!((byte & 0x0F) == 0x08 &&
((byte >> 4) & 1) == ((byte >> 5) & 1) &&
((byte >> 6) & 1) == ((byte >> 7) & 1))) {
this->msbc_buffer_pos = 0;
return;
}
}
else if (this->msbc_buffer_pos == 2) {
/* .. and beginning of MSBC frame: SYNCWORD + 2 nul bytes */
if (byte != 0xAD) {
this->msbc_buffer_pos = 0;
return;
}
}
else if (this->msbc_buffer_pos == 3) {
if (byte != 0x00) {
this->msbc_buffer_pos = 0;
return;
}
}
else if (this->msbc_buffer_pos == 4) {
if (byte != 0x00) {
this->msbc_buffer_pos = 0;
return;
}
}
else if (this->msbc_buffer_pos >= MSBC_ENCODED_SIZE) {
/* Packet completed. Reset. */
this->msbc_buffer_pos = 0;
msbc_buffer_append_byte(this, byte);
return;
}
this->msbc_buffer[this->msbc_buffer_pos] = byte;
++this->msbc_buffer_pos;
}
/*
Helper function for easier debugging
Caveat: If size_read is not a multiple of 16, then the last bytes
will not be printed / logged
*/
static void hexdump_to_log(void *log, uint8_t *read_data, int size_read)
{
int rowsize = 16*3;
int line_idx = 0;
char hexline[16*3] = "";
int i;
for (i = 0; i < size_read; ++i) {
snprintf(&hexline[line_idx], 4, "%02X ", read_data[i]);
line_idx += 3;
if (line_idx == rowsize) {
spa_log_trace(log, "Processing read data: read_data %02i: %s", i-15, hexline);
line_idx = 0;
}
}
}
/* helper function to detect if a packet consists only of zeros */
static bool is_zero_packet(uint8_t *data, int size)
{
for (int i = 0; i < size; ++i) {
if (data[i] != 0) {
return false;
}
}
return true;
}
static void preprocess_and_decode_msbc_data(void *userdata, uint8_t *read_data, int size_read)
{
struct impl *this = userdata;
struct port *port = &this->port;
struct spa_data *datas = port->current_buffer->buf->datas;
spa_log_trace(this->log, "handling mSBC data");
/* print hexdump of package */
bool flag_hexdump_to_log = false;
if (flag_hexdump_to_log) {
hexdump_to_log(this->log, read_data, size_read);
}
/* check if the packet contains only zeros - if so ignore the packet.
This is necessary, because some kernels insert bogus "all-zero" packets
into the datastream.
See https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/549 */
if (is_zero_packet(read_data, size_read)) {
return;
}
int i;
for (i = 0; i < size_read; ++i) {
msbc_buffer_append_byte(this, read_data[i]);
/* Handle found mSBC packets.
*
* XXX: if there's no space for the decoded audio in
* XXX: the current buffer, we'll drop data.
*/
if (this->msbc_buffer_pos == MSBC_ENCODED_SIZE) {
spa_log_trace(this->log, "Received full mSBC packet, start processing it");
if (port->ready_offset + MSBC_DECODED_SIZE <= datas[0].maxsize) {
int seq, processed;
size_t written;
spa_log_trace(this->log,
"Output buffer has space, processing mSBC packet");
/* Check sequence number */
seq = ((this->msbc_buffer[1] >> 4) & 1) |
((this->msbc_buffer[1] >> 6) & 2);
spa_log_trace(this->log, "mSBC packet seq=%u", seq);
if (!this->msbc_seq_initialized) {
this->msbc_seq_initialized = true;
this->msbc_seq = seq;
} else if (seq != this->msbc_seq) {
spa_log_info(this->log,
"missing mSBC packet: %u != %u", seq, this->msbc_seq);
this->msbc_seq = seq;
/* TODO: Implement PLC. */
}
this->msbc_seq = (this->msbc_seq + 1) % 4;
/* decode frame */
processed = sbc_decode(
&this->msbc, this->msbc_buffer + 2, MSBC_ENCODED_SIZE - 3,
(uint8_t *)datas[0].data + port->ready_offset, MSBC_DECODED_SIZE,
&written);
if (processed < 0) {
spa_log_warn(this->log, "sbc_decode failed: %d", processed);
/* TODO: manage errors */
continue;
}
port->ready_offset += written;
} else {
spa_log_warn(this->log, "Output buffer full, dropping mSBC packet");
}
}
}
}
static int sco_source_cb(void *userdata, uint8_t *read_data, int size_read)
{
struct impl *this = userdata;
struct port *port = &this->port;
struct spa_io_buffers *io = port->io;
struct spa_data *datas;
uint32_t max_out_size;
if (this->transport == NULL) {
spa_log_debug(this->log, "no transport, stop reading");
goto stop;
}
/* get buffer */
if (!port->current_buffer) {
if (spa_list_is_empty(&port->free)) {
spa_log_warn(this->log, "buffer not available");
return 0;
}
port->current_buffer = spa_list_first(&port->free, struct buffer, link);
spa_list_remove(&port->current_buffer->link);
port->ready_offset = 0;
}
datas = port->current_buffer->buf->datas;
if (this->transport->codec == HFP_AUDIO_CODEC_MSBC) {
max_out_size = MSBC_DECODED_SIZE;
} else {
max_out_size = this->transport->read_mtu;
}
/* update the current pts */
spa_system_clock_gettime(this->data_system, CLOCK_MONOTONIC, &this->now);
/* handle data read from socket */
spa_log_debug(this->log, "read socket data %d", size_read);
if (this->transport->codec == HFP_AUDIO_CODEC_MSBC) {
preprocess_and_decode_msbc_data(userdata, read_data, size_read);
} else {
uint8_t *packet;
packet = (uint8_t *)datas[0].data + port->ready_offset;
spa_memmove(packet, read_data, size_read);
port->ready_offset += size_read;
}
/* send buffer if full */
if ((max_out_size + port->ready_offset) > (this->props.max_latency * port->frame_size)) {
uint64_t sample_count;
datas[0].chunk->offset = 0;
datas[0].chunk->size = port->ready_offset;
datas[0].chunk->stride = port->frame_size;
sample_count = datas[0].chunk->size / port->frame_size;
spa_list_append(&port->ready, &port->current_buffer->link);
port->current_buffer = NULL;
if (this->clock) {
this->clock->nsec = SPA_TIMESPEC_TO_NSEC(&this->now);
this->clock->duration = sample_count * this->clock->rate.denom / port->current_format.info.raw.rate;
this->clock->position += this->clock->duration;
this->clock->delay = 0;
this->clock->rate_diff = 1.0f;
this->clock->next_nsec = this->clock->nsec;
}
}
/* done if there are no buffers ready */
if (spa_list_is_empty(&port->ready))
return 0;
/* process the buffer if IO does not have any */
if (io->status != SPA_STATUS_HAVE_DATA) {
struct buffer *b;
if (io->buffer_id < port->n_buffers)
recycle_buffer(this, port, io->buffer_id);
b = spa_list_first(&port->ready, struct buffer, link);
spa_list_remove(&b->link);
b->outstanding = true;
io->buffer_id = b->id;
io->status = SPA_STATUS_HAVE_DATA;
}
/* notify ready */
spa_node_call_ready(&this->callbacks, SPA_STATUS_HAVE_DATA);
return 0;
stop:
return 1;
}
static int do_add_source(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct impl *this = user_data;
spa_bt_sco_io_set_source_cb(this->transport->sco_io, sco_source_cb, this);
return 0;
}
static int do_start(struct impl *this)
{
bool do_accept;
int res;
/* Dont do anything if the node has already started */
if (this->started)
return 0;
/* Make sure the transport is valid */
spa_return_val_if_fail (this->transport != NULL, -EIO);
/* Do accept if Gateway; otherwise do connect for Head Unit */
do_accept = this->transport->profile & SPA_BT_PROFILE_HEADSET_AUDIO_GATEWAY;
/* acquire the socked fd (false -> connect | true -> accept) */
if ((res = spa_bt_transport_acquire(this->transport, do_accept)) < 0)
return res;
/* Reset the buffers and sample count */
reset_buffers(&this->port);
/* Init mSBC if needed */
if (this->transport->codec == HFP_AUDIO_CODEC_MSBC) {
sbc_init_msbc(&this->msbc, 0);
/* Libsbc expects audio samples by default in host endianity, mSBC requires little endian */
this->msbc.endian = SBC_LE;
this->msbc_seq_initialized = false;
this->msbc_buffer_pos = 0;
}
/* Start socket i/o */
spa_bt_transport_ensure_sco_io(this->transport, this->data_loop);
spa_loop_invoke(this->data_loop, do_add_source, 0, NULL, 0, true, this);
/* Set the started flag */
this->started = true;
return 0;
}
static int do_remove_source(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct impl *this = user_data;
if (this->transport)
spa_bt_sco_io_set_source_cb(this->transport->sco_io, NULL, NULL);
return 0;
}
static int do_stop(struct impl *this)
{
int res = 0;
if (!this->started)
return 0;
spa_log_debug(this->log, "sco-source %p: stop", this);
spa_loop_invoke(this->data_loop, do_remove_source, 0, NULL, 0, true, this);
this->started = false;
if (this->transport) {
/* Release the transport; it is responsible for closing the fd */
res = spa_bt_transport_release(this->transport);
}
return res;
}
static int impl_node_send_command(void *object, const struct spa_command *command)
{
struct impl *this = object;
struct port *port;
int res;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_return_val_if_fail(command != NULL, -EINVAL);
port = &this->port;
switch (SPA_NODE_COMMAND_ID(command)) {
case SPA_NODE_COMMAND_Start:
if (!port->have_format)
return -EIO;
if (port->n_buffers == 0)
return -EIO;
if ((res = do_start(this)) < 0)
return res;
break;
case SPA_NODE_COMMAND_Pause:
case SPA_NODE_COMMAND_Suspend:
if ((res = do_stop(this)) < 0)
return res;
break;
default:
return -ENOTSUP;
}
return 0;
}
static const struct spa_dict_item node_info_items[] = {
{ SPA_KEY_DEVICE_API, "bluez5" },
{ SPA_KEY_MEDIA_CLASS, "Audio/Source" },
{ SPA_KEY_NODE_DRIVER, "true" },
{ SPA_KEY_NODE_PAUSE_ON_IDLE, "false" },
};
static void emit_node_info(struct impl *this, bool full)
{
if (full)
this->info.change_mask = this->info_all;
if (this->info.change_mask) {
this->info.props = &SPA_DICT_INIT_ARRAY(node_info_items);
spa_node_emit_info(&this->hooks, &this->info);
this->info.change_mask = 0;
}
}
static void emit_port_info(struct impl *this, struct port *port, bool full)
{
if (full)
port->info.change_mask = port->info_all;
if (port->info.change_mask) {
spa_node_emit_port_info(&this->hooks,
SPA_DIRECTION_OUTPUT, 0, &port->info);
port->info.change_mask = 0;
}
}
static int
impl_node_add_listener(void *object,
struct spa_hook *listener,
const struct spa_node_events *events,
void *data)
{
struct impl *this = object;
struct spa_hook_list save;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_hook_list_isolate(&this->hooks, &save, listener, events, data);
emit_node_info(this, true);
emit_port_info(this, &this->port, true);
spa_hook_list_join(&this->hooks, &save);
return 0;
}
static int
impl_node_set_callbacks(void *object,
const struct spa_node_callbacks *callbacks,
void *data)
{
struct impl *this = object;
spa_return_val_if_fail(this != NULL, -EINVAL);
this->callbacks = SPA_CALLBACKS_INIT(callbacks, data);
return 0;
}
static int impl_node_sync(void *object, int seq)
{
struct impl *this = object;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_node_emit_result(&this->hooks, seq, 0, 0, NULL);
return 0;
}
static int impl_node_add_port(void *object, enum spa_direction direction, uint32_t port_id,
const struct spa_dict *props)
{
return -ENOTSUP;
}
static int impl_node_remove_port(void *object, enum spa_direction direction, uint32_t port_id)
{
return -ENOTSUP;
}
static int
impl_node_port_enum_params(void *object, int seq,
enum spa_direction direction, uint32_t port_id,
uint32_t id, uint32_t start, uint32_t num,
const struct spa_pod *filter)
{
struct impl *this = object;
struct port *port;
struct spa_pod *param;
struct spa_pod_builder b = { 0 };
uint8_t buffer[1024];
struct spa_result_node_params result;
uint32_t count = 0;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_return_val_if_fail(num != 0, -EINVAL);
spa_return_val_if_fail(CHECK_PORT(this, direction, port_id), -EINVAL);
port = &this->port;
result.id = id;
result.next = start;
next:
result.index = result.next++;
spa_pod_builder_init(&b, buffer, sizeof(buffer));
switch (id) {
case SPA_PARAM_EnumFormat:
if (result.index > 0)
return 0;
if (this->transport == NULL)
return -EIO;
/* set the info structure */
struct spa_audio_info_raw info = { 0, };
info.format = SPA_AUDIO_FORMAT_S16_LE;
info.channels = 1;
info.position[0] = SPA_AUDIO_CHANNEL_MONO;
/* CVSD format has a rate of 8kHz
* MSBC format has a rate of 16kHz */
if (this->transport->codec == HFP_AUDIO_CODEC_MSBC)
info.rate = 16000;
else
info.rate = 8000;
/* build the param */
param = spa_format_audio_raw_build(&b, id, &info);
break;
case SPA_PARAM_Format:
if (!port->have_format)
return -EIO;
if (result.index > 0)
return 0;
param = spa_format_audio_raw_build(&b, id, &port->current_format.info.raw);
break;
case SPA_PARAM_Buffers:
if (!port->have_format)
return -EIO;
if (result.index > 0)
return 0;
param = spa_pod_builder_add_object(&b,
SPA_TYPE_OBJECT_ParamBuffers, id,
SPA_PARAM_BUFFERS_buffers, SPA_POD_CHOICE_RANGE_Int(2, 1, MAX_BUFFERS),
SPA_PARAM_BUFFERS_blocks, SPA_POD_Int(1),
SPA_PARAM_BUFFERS_size, SPA_POD_CHOICE_RANGE_Int(
this->props.max_latency * port->frame_size,
this->props.min_latency * port->frame_size,
INT32_MAX),
SPA_PARAM_BUFFERS_stride, SPA_POD_Int(port->frame_size),
SPA_PARAM_BUFFERS_align, SPA_POD_Int(16));
break;
case SPA_PARAM_Meta:
switch (result.index) {
case 0:
param = spa_pod_builder_add_object(&b,
SPA_TYPE_OBJECT_ParamMeta, id,
SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Header),
SPA_PARAM_META_size, SPA_POD_Int(sizeof(struct spa_meta_header)));
break;
default:
return 0;
}
break;
case SPA_PARAM_IO:
switch (result.index) {
case 0:
param = spa_pod_builder_add_object(&b,
SPA_TYPE_OBJECT_ParamIO, id,
SPA_PARAM_IO_id, SPA_POD_Id(SPA_IO_Buffers),
SPA_PARAM_IO_size, SPA_POD_Int(sizeof(struct spa_io_buffers)));
break;
case 1:
param = spa_pod_builder_add_object(&b,
SPA_TYPE_OBJECT_ParamIO, id,
SPA_PARAM_IO_id, SPA_POD_Id(SPA_IO_RateMatch),
SPA_PARAM_IO_size, SPA_POD_Int(sizeof(struct spa_io_rate_match)));
break;
default:
return 0;
}
break;
default:
return -ENOENT;
}
if (spa_pod_filter(&b, &result.param, param, filter) < 0)
goto next;
spa_node_emit_result(&this->hooks, seq, 0, SPA_RESULT_TYPE_NODE_PARAMS, &result);
if (++count != num)
goto next;
return 0;
}
static int clear_buffers(struct impl *this, struct port *port)
{
do_stop(this);
if (port->n_buffers > 0) {
spa_list_init(&port->free);
spa_list_init(&port->ready);
port->n_buffers = 0;
}
port->current_buffer = NULL;
return 0;
}
static int port_set_format(struct impl *this, struct port *port,
uint32_t flags,
const struct spa_pod *format)
{
int err;
if (format == NULL) {
spa_log_debug(this->log, "clear format");
clear_buffers(this, port);
port->have_format = false;
} else {
struct spa_audio_info info = { 0 };
if ((err = spa_format_parse(format, &info.media_type, &info.media_subtype)) < 0)
return err;
if (info.media_type != SPA_MEDIA_TYPE_audio ||
info.media_subtype != SPA_MEDIA_SUBTYPE_raw)
return -EINVAL;
if (spa_format_audio_raw_parse(format, &info.info.raw) < 0)
return -EINVAL;
port->frame_size = info.info.raw.channels * 2;
port->current_format = info;
port->have_format = true;
}
port->info.change_mask |= SPA_PORT_CHANGE_MASK_PARAMS;
if (port->have_format) {
port->info.change_mask |= SPA_PORT_CHANGE_MASK_FLAGS;
port->info.flags = SPA_PORT_FLAG_LIVE;
port->info.change_mask |= SPA_PORT_CHANGE_MASK_RATE;
port->info.rate = SPA_FRACTION(1, port->current_format.info.raw.rate);
port->params[3] = SPA_PARAM_INFO(SPA_PARAM_Format, SPA_PARAM_INFO_READWRITE);
port->params[4] = SPA_PARAM_INFO(SPA_PARAM_Buffers, SPA_PARAM_INFO_READ);
} else {
port->params[3] = SPA_PARAM_INFO(SPA_PARAM_Format, SPA_PARAM_INFO_WRITE);
port->params[4] = SPA_PARAM_INFO(SPA_PARAM_Buffers, 0);
}
emit_port_info(this, port, false);
return 0;
}
static int
impl_node_port_set_param(void *object,
enum spa_direction direction, uint32_t port_id,
uint32_t id, uint32_t flags,
const struct spa_pod *param)
{
struct impl *this = object;
struct port *port;
int res;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_return_val_if_fail(CHECK_PORT(node, direction, port_id), -EINVAL);
port = &this->port;
switch (id) {
case SPA_PARAM_Format:
res = port_set_format(this, port, flags, param);
break;
default:
res = -ENOENT;
break;
}
return res;
}
static int
impl_node_port_use_buffers(void *object,
enum spa_direction direction, uint32_t port_id,
uint32_t flags,
struct spa_buffer **buffers, uint32_t n_buffers)
{
struct impl *this = object;
struct port *port;
uint32_t i;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_return_val_if_fail(CHECK_PORT(this, direction, port_id), -EINVAL);
port = &this->port;
spa_log_debug(this->log, "use buffers %d", n_buffers);
if (!port->have_format)
return -EIO;
clear_buffers(this, port);
for (i = 0; i < n_buffers; i++) {
struct buffer *b = &port->buffers[i];
struct spa_data *d = buffers[i]->datas;
b->buf = buffers[i];
b->id = i;
b->h = spa_buffer_find_meta_data(buffers[i], SPA_META_Header, sizeof(*b->h));
if (d[0].data == NULL) {
spa_log_error(this->log, NAME " %p: need mapped memory", this);
return -EINVAL;
}
spa_list_append(&port->free, &b->link);
b->outstanding = false;
}
port->n_buffers = n_buffers;
return 0;
}
static int
impl_node_port_set_io(void *object,
enum spa_direction direction,
uint32_t port_id,
uint32_t id,
void *data, size_t size)
{
struct impl *this = object;
struct port *port;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_return_val_if_fail(CHECK_PORT(this, direction, port_id), -EINVAL);
port = &this->port;
switch (id) {
case SPA_IO_Buffers:
port->io = data;
break;
case SPA_IO_RateMatch:
port->rate_match = data;
break;
default:
return -ENOENT;
}
return 0;
}
static int impl_node_port_reuse_buffer(void *object, uint32_t port_id, uint32_t buffer_id)
{
struct impl *this = object;
struct port *port;
spa_return_val_if_fail(this != NULL, -EINVAL);
spa_return_val_if_fail(port_id == 0, -EINVAL);
port = &this->port;
if (port->n_buffers == 0)
return -EIO;
if (buffer_id >= port->n_buffers)
return -EINVAL;
recycle_buffer(this, port, buffer_id);
return 0;
}
static int impl_node_process(void *object)
{
struct impl *this = object;
struct port *port;
struct spa_io_buffers *io;
struct buffer *buffer;
spa_return_val_if_fail(this != NULL, -EINVAL);
port = &this->port;
io = port->io;
spa_return_val_if_fail(io != NULL, -EIO);
/* Return if we already have a buffer */
if (io->status == SPA_STATUS_HAVE_DATA)
return SPA_STATUS_HAVE_DATA;
/* Recycle */
if (io->buffer_id < port->n_buffers) {
recycle_buffer(this, port, io->buffer_id);
io->buffer_id = SPA_ID_INVALID;
}
/* Return if there are no buffers ready to be processed */
if (spa_list_is_empty(&port->ready))
return SPA_STATUS_OK;
/* Get the new buffer from the ready list */
buffer = spa_list_first(&port->ready, struct buffer, link);
spa_list_remove(&buffer->link);
buffer->outstanding = true;
/* Set the new buffer in IO */
io->buffer_id = buffer->id;
io->status = SPA_STATUS_HAVE_DATA;
/* Notify we have a buffer ready to be processed */
return SPA_STATUS_HAVE_DATA;
}
static const struct spa_node_methods impl_node = {
SPA_VERSION_NODE_METHODS,
.add_listener = impl_node_add_listener,
.set_callbacks = impl_node_set_callbacks,
.sync = impl_node_sync,
.enum_params = impl_node_enum_params,
.set_param = impl_node_set_param,
.set_io = impl_node_set_io,
.send_command = impl_node_send_command,
.add_port = impl_node_add_port,
.remove_port = impl_node_remove_port,
.port_enum_params = impl_node_port_enum_params,
.port_set_param = impl_node_port_set_param,
.port_use_buffers = impl_node_port_use_buffers,
.port_set_io = impl_node_port_set_io,
.port_reuse_buffer = impl_node_port_reuse_buffer,
.process = impl_node_process,
};
static int do_transport_destroy(struct spa_loop *loop,
bool async,
uint32_t seq,
const void *data,
size_t size,
void *user_data)
{
struct impl *this = user_data;
this->transport = NULL;
return 0;
}
static void transport_destroy(void *data)
{
struct impl *this = data;
spa_log_debug(this->log, "transport %p destroy", this->transport);
spa_loop_invoke(this->data_loop, do_transport_destroy, 0, NULL, 0, true, this);
}
static const struct spa_bt_transport_events transport_events = {
SPA_VERSION_BT_TRANSPORT_EVENTS,
.destroy = transport_destroy,
};
static int impl_get_interface(struct spa_handle *handle, const char *type, void **interface)
{
struct impl *this;
spa_return_val_if_fail(handle != NULL, -EINVAL);
spa_return_val_if_fail(interface != NULL, -EINVAL);
this = (struct impl *) handle;
if (strcmp(type, SPA_TYPE_INTERFACE_Node) == 0)
*interface = &this->node;
else
return -ENOENT;
return 0;
}
static int impl_clear(struct spa_handle *handle)
{
struct impl *this = (struct impl *) handle;
if (this->transport)
spa_hook_remove(&this->transport_listener);
return 0;
}
static size_t
impl_get_size(const struct spa_handle_factory *factory,
const struct spa_dict *params)
{
return sizeof(struct impl);
}
static int
impl_init(const struct spa_handle_factory *factory,
struct spa_handle *handle,
const struct spa_dict *info,
const struct spa_support *support,
uint32_t n_support)
{
struct impl *this;
struct port *port;
const char *str;
spa_return_val_if_fail(factory != NULL, -EINVAL);
spa_return_val_if_fail(handle != NULL, -EINVAL);
handle->get_interface = impl_get_interface;
handle->clear = impl_clear;
this = (struct impl *) handle;
this->log = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_Log);
this->data_loop = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_DataLoop);
this->data_system = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_DataSystem);
if (this->data_loop == NULL) {
spa_log_error(this->log, "a data loop is needed");
return -EINVAL;
}
if (this->data_system == NULL) {
spa_log_error(this->log, "a data system is needed");
return -EINVAL;
}
this->node.iface = SPA_INTERFACE_INIT(
SPA_TYPE_INTERFACE_Node,
SPA_VERSION_NODE,
&impl_node, this);
spa_hook_list_init(&this->hooks);
reset_props(&this->props);
/* set the node info */
this->info_all = SPA_NODE_CHANGE_MASK_FLAGS |
SPA_NODE_CHANGE_MASK_PROPS |
SPA_NODE_CHANGE_MASK_PARAMS;
this->info = SPA_NODE_INFO_INIT();
this->info.flags = SPA_NODE_FLAG_RT;
this->params[0] = SPA_PARAM_INFO(SPA_PARAM_PropInfo, SPA_PARAM_INFO_READ);
this->params[1] = SPA_PARAM_INFO(SPA_PARAM_Props, SPA_PARAM_INFO_READWRITE);
this->params[2] = SPA_PARAM_INFO(SPA_PARAM_IO, SPA_PARAM_INFO_READ);
this->info.params = this->params;
this->info.n_params = 3;
/* set the port info */
port = &this->port;
port->info_all = SPA_PORT_CHANGE_MASK_FLAGS |
SPA_PORT_CHANGE_MASK_PARAMS;
port->info = SPA_PORT_INFO_INIT();
port->info.change_mask = SPA_PORT_CHANGE_MASK_FLAGS;
port->info.flags = SPA_PORT_FLAG_LIVE |
SPA_PORT_FLAG_TERMINAL;
port->params[0] = SPA_PARAM_INFO(SPA_PARAM_EnumFormat, SPA_PARAM_INFO_READ);
port->params[1] = SPA_PARAM_INFO(SPA_PARAM_Meta, SPA_PARAM_INFO_READ);
port->params[2] = SPA_PARAM_INFO(SPA_PARAM_IO, SPA_PARAM_INFO_READ);
port->params[3] = SPA_PARAM_INFO(SPA_PARAM_Format, SPA_PARAM_INFO_WRITE);
port->params[4] = SPA_PARAM_INFO(SPA_PARAM_Buffers, 0);
port->info.params = port->params;
port->info.n_params = 5;
/* Init the buffer lists */
spa_list_init(&port->ready);
spa_list_init(&port->free);
if (info && (str = spa_dict_lookup(info, SPA_KEY_API_BLUEZ5_TRANSPORT)))
sscanf(str, "pointer:%p", &this->transport);
if (this->transport == NULL) {
spa_log_error(this->log, "a transport is needed");
return -EINVAL;
}
spa_bt_transport_add_listener(this->transport,
&this->transport_listener, &transport_events, this);
return 0;
}
static const struct spa_interface_info impl_interfaces[] = {
{SPA_TYPE_INTERFACE_Node,},
};
static int
impl_enum_interface_info(const struct spa_handle_factory *factory,
const struct spa_interface_info **info, uint32_t *index)
{
spa_return_val_if_fail(factory != NULL, -EINVAL);
spa_return_val_if_fail(info != NULL, -EINVAL);
spa_return_val_if_fail(index != NULL, -EINVAL);
switch (*index) {
case 0:
*info = &impl_interfaces[*index];
break;
default:
return 0;
}
(*index)++;
return 1;
}
static const struct spa_dict_item info_items[] = {
{ SPA_KEY_FACTORY_AUTHOR, "Collabora Ltd. <contact@collabora.com>" },
{ SPA_KEY_FACTORY_DESCRIPTION, "Capture bluetooth audio with hsp/hfp" },
{ SPA_KEY_FACTORY_USAGE, SPA_KEY_API_BLUEZ5_TRANSPORT"=<transport>" },
};
static const struct spa_dict info = SPA_DICT_INIT_ARRAY(info_items);
struct spa_handle_factory spa_sco_source_factory = {
SPA_VERSION_HANDLE_FACTORY,
SPA_NAME_API_BLUEZ5_SCO_SOURCE,
&info,
impl_get_size,
impl_init,
impl_enum_interface_info,
};
| 25.488584 | 103 | 0.697779 | [
"object"
] |
36f5427a50b14b1b7ed34394df1cbb38bafa382e | 4,332 | h | C | src/libqhullcpp/QhullFacetList.h | qnzhou/qhull | d901974562b76b89947eea320423130851b2f164 | [
"Qhull"
] | 107 | 2017-08-29T15:49:40.000Z | 2022-03-18T08:27:48.000Z | src/libqhullcpp/QhullFacetList.h | qnzhou/qhull | d901974562b76b89947eea320423130851b2f164 | [
"Qhull"
] | 590 | 2016-09-24T12:46:36.000Z | 2022-03-24T18:27:18.000Z | src/libqhullcpp/QhullFacetList.h | qnzhou/qhull | d901974562b76b89947eea320423130851b2f164 | [
"Qhull"
] | 46 | 2016-09-26T07:20:17.000Z | 2022-02-17T19:55:17.000Z | /****************************************************************************
**
** Copyright (c) 2008-2015 C.B. Barber. All rights reserved.
** $Id: //main/2015/qhull/src/libqhullcpp/QhullFacetList.h#2 $$Change: 2066 $
** $DateTime: 2016/01/18 19:29:17 $$Author: bbarber $
**
****************************************************************************/
#ifndef QHULLFACETLIST_H
#define QHULLFACETLIST_H
#include "libqhullcpp/QhullLinkedList.h"
#include "libqhullcpp/QhullFacet.h"
#include <ostream>
#ifndef QHULL_NO_STL
#include <vector>
#endif
namespace orgQhull {
#//!\name Used here
class Qhull;
class QhullFacet;
class QhullQh;
#//!\name Defined here
//! QhullFacetList -- List of QhullFacet/facetT, as a C++ class.
//!\see QhullFacetSet.h
class QhullFacetList;
//! QhullFacetListIterator -- if(f.isGood()){ ... }
typedef QhullLinkedListIterator<QhullFacet> QhullFacetListIterator;
class QhullFacetList : public QhullLinkedList<QhullFacet> {
#//!\name Fields
private:
bool select_all; //! True if include bad facets. Default is false.
#//!\name Constructors
public:
QhullFacetList(const Qhull &q, facetT *b, facetT *e);
QhullFacetList(QhullQh *qqh, facetT *b, facetT *e);
QhullFacetList(QhullFacet b, QhullFacet e) : QhullLinkedList<QhullFacet>(b, e), select_all(false) {}
//Copy constructor copies pointer but not contents. Needed for return by value and parameter passing.
QhullFacetList(const QhullFacetList &other) : QhullLinkedList<QhullFacet>(*other.begin(), *other.end()), select_all(other.select_all) {}
QhullFacetList & operator=(const QhullFacetList &other) { QhullLinkedList<QhullFacet>::operator =(other); select_all= other.select_all; return *this; }
~QhullFacetList() {}
private: //!Disable default constructor. See QhullLinkedList
QhullFacetList();
public:
#//!\name Conversion
#ifndef QHULL_NO_STL
std::vector<QhullFacet> toStdVector() const;
std::vector<QhullVertex> vertices_toStdVector() const;
#endif //QHULL_NO_STL
#ifdef QHULL_USES_QT
QList<QhullFacet> toQList() const;
QList<QhullVertex> vertices_toQList() const;
#endif //QHULL_USES_QT
#//!\name GetSet
//! Filtered by facet.isGood(). May be 0 when !isEmpty().
countT count() const;
bool contains(const QhullFacet &f) const;
countT count(const QhullFacet &f) const;
bool isSelectAll() const { return select_all; }
QhullQh * qh() const { return first().qh(); }
void selectAll() { select_all= true; }
void selectGood() { select_all= false; }
//!< operator==() does not depend on isGood()
#//!\name IO
struct PrintFacetList{
const QhullFacetList *facet_list;
const char * print_message; //!< non-null message
PrintFacetList(const QhullFacetList &fl, const char *message) : facet_list(&fl), print_message(message) {}
};//PrintFacetList
PrintFacetList print(const char *message) const { return PrintFacetList(*this, message); }
struct PrintFacets{
const QhullFacetList *facet_list;
PrintFacets(const QhullFacetList &fl) : facet_list(&fl) {}
};//PrintFacets
PrintFacets printFacets() const { return PrintFacets(*this); }
struct PrintVertices{
const QhullFacetList *facet_list;
PrintVertices(const QhullFacetList &fl) : facet_list(&fl) {}
};//PrintVertices
PrintVertices printVertices() const { return PrintVertices(*this); }
};//class QhullFacetList
}//namespace orgQhull
#//!\name == Global namespace =========================================
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacetList::PrintFacetList &p);
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacetList::PrintFacets &p);
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacetList::PrintVertices &p);
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacetList &fs);
#endif // QHULLFACETLIST_H
| 40.485981 | 160 | 0.612419 | [
"vector"
] |
36f825b25b422efde43cdbd6733173b051ef8175 | 4,459 | h | C | libstacker/src/focas.h | JoeAndrew/OpenSkyStacker | d55b4b5bbfdffa893410f3ddc594848847f6d0e5 | [
"MIT"
] | 77 | 2017-06-02T22:45:44.000Z | 2022-03-10T14:46:04.000Z | libstacker/src/focas.h | JoeAndrew/OpenSkyStacker | d55b4b5bbfdffa893410f3ddc594848847f6d0e5 | [
"MIT"
] | 38 | 2017-03-20T04:25:39.000Z | 2021-05-20T03:28:46.000Z | libstacker/src/focas.h | JoeAndrew/OpenSkyStacker | d55b4b5bbfdffa893410f3ddc594848847f6d0e5 | [
"MIT"
] | 16 | 2017-06-03T00:19:54.000Z | 2021-05-19T16:23:09.000Z | /* This code was derived from the FOCAS program, whose copyright can be found below. */
/* */
/* Copyright(c) 1982 Association of Universities for Research in Astronomy Inc. */
/* */
/* The FOCAS software is publicly available, but is NOT in the public domain. */
/* The difference is that copyrights granting rights for unrestricted use and */
/* redistribution have been placed on all of the software to identify its authors. */
/* You are allowed and encouraged to take this software and use it as you wish, */
/* subject to the restrictions outlined below. */
/* */
/* Permission to use, copy, modify, and distribute this software and its */
/* documentation is hereby granted without fee, provided that the above */
/* copyright notice appear in all copies and that both that copyright notice */
/* and this permission notice appear in supporting documentation, and that */
/* references to the Association of Universities for Research in Astronomy */
/* Inc. (AURA), the National Optical Astronomy Observatories (NOAO), or the */
/* Faint Object Classification and Analysis System (FOCAS) not be used in */
/* advertising or publicity pertaining to distribution of the software without */
/* specific, written prior permission from NOAO. NOAO makes no */
/* representations about the suitability of this software for any purpose. It */
/* is provided "as is" without express or implied warranty. */
/* */
/* NOAO DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL */
/* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL NOAO */
/* BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */
/* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION */
/* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN */
/* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef FOCAS_H
#define FOCAS_H
#include "libstacker/model.h"
#include "hfti.h"
#include <qdebug.h>
#include <cmath>
#include <algorithm>
#include "opencv2/core/core.hpp"
namespace openskystacker {
/*! @file focas.h
@brief Variables and functions from the FOCAS library.
*/
#define TOL 0.002 /*!< Default matching tolerance */
#define NOBJS 40 /*!< Default number of objects */
#define MIN_MATCH 6 /*!< Min # of matched objects for transform */
#define MAX_MATCH 120 /*!< Max # of matches to use (~MAX_OBJS) */
#define MIN_OBJS 10 /*!< Min # of objects to use */
#define MAX_OBJS 100 /*!< Max # of objects to use */
#define CLIP 3 /*!< Sigma clipping factor */
#define PM 57.2958 /*!< Radian to degree conversion */
//! Generates a list of triangles to be used for the alignment algorithm.
/*!
@param List The list of stars to generate triangles from.
*/
std::vector<Triangle> generateTriangleList(std::vector<Star> List);
int sidesPos(int i, int j, int n);
std::vector<std::vector<int> > findMatches(int nobjs, int *k, std::vector<Triangle> List_triangA, std::vector<Triangle> List_triangB);
std::vector<std::vector<float> > findTransform(std::vector<std::vector<int> > matches,
int m, std::vector<Star> List1, std::vector<Star> List2, int *ok = 0);
void sortTriangles(std::vector<Triangle> *List_Triang_, int l, int r);
void binSearchTriangles(float key, std::vector<Triangle> *List_triang_, int *first, int *last);
void checkTolerance(int nobjs, Triangle List_triangA, std::vector<Triangle> *List_triangB_,
int first, int last, int Table_match[]);
// void h12(int mode, int lpivot, int l1, int m, float u[][MAX_MATCH], int iue, float *up, float c[][MAX_MATCH], int ice, int icv, int ncv);
// void hfti(cv::Mat a, int mda, int m, int n, cv::Mat b, int mdb, int nb, float tau, int krank, float rnorm[], float h[], float g[], int ip[]);
}
#endif // FOCAS_H
| 57.166667 | 144 | 0.611796 | [
"object",
"vector",
"model",
"transform"
] |
36fce000a6d730904102148aa2f0b9d734ced9d1 | 7,042 | c | C | src/common/readmesh.c | NREL/Radiance | 2fcca99ace2f2435f32a09525ad31f2b3be3c1bc | [
"BSD-3-Clause-LBNL"
] | 154 | 2015-01-27T15:02:36.000Z | 2022-01-06T18:14:18.000Z | src/common/readmesh.c | NREL/Radiance | 2fcca99ace2f2435f32a09525ad31f2b3be3c1bc | [
"BSD-3-Clause-LBNL"
] | 35 | 2015-05-11T21:41:31.000Z | 2021-12-17T13:23:57.000Z | src/common/readmesh.c | NREL/Radiance | 2fcca99ace2f2435f32a09525ad31f2b3be3c1bc | [
"BSD-3-Clause-LBNL"
] | 64 | 2015-01-21T00:52:40.000Z | 2022-02-07T12:15:09.000Z | #ifndef lint
static const char RCSid[] = "$Id: readmesh.c,v 2.18 2021/07/12 17:42:51 greg Exp $";
#endif
/*
* Routines for reading a compiled mesh from a file
*/
#include <time.h>
#include "platform.h"
#include "standard.h"
#include "octree.h"
#include "object.h"
#include "mesh.h"
#include "resolu.h"
static char *meshfn; /* input file name */
static FILE *meshfp; /* mesh file pointer */
static int objsize; /* sizeof(OBJECT) from writer */
static void
mesherror(etyp, msg) /* mesh read error */
int etyp;
char *msg;
{
char msgbuf[128];
sprintf(msgbuf, "(%s): %s", meshfn, msg);
error(etyp, msgbuf);
}
static long
mgetint(siz) /* get a siz-byte integer */
int siz;
{
long r = getint(siz, meshfp);
if (r == EOF && feof(meshfp))
mesherror(USER, "truncated mesh file");
return(r);
}
static double
mgetflt() /* get a floating point number */
{
double r = getflt(meshfp);
if (r == (double)EOF && feof(meshfp))
mesherror(USER, "truncated mesh file");
return(r);
}
static OCTREE
getfullnode() /* get a set, return fullnode */
{
OBJECT set[MAXSET+1];
int i;
if ((set[0] = mgetint(objsize)) > MAXSET)
mesherror(USER, "bad set in getfullnode");
for (i = 1; i <= set[0]; i++)
set[i] = mgetint(objsize);
return(fullnode(set));
}
static OCTREE
gettree() /* get a pre-ordered octree */
{
OCTREE ot;
int i;
switch (getc(meshfp)) {
case OT_EMPTY:
return(EMPTY);
case OT_FULL:
return(getfullnode());
case OT_TREE:
if ((ot = octalloc()) == EMPTY)
mesherror(SYSTEM, "out of tree space in readmesh");
for (i = 0; i < 8; i++)
octkid(ot, i) = gettree();
return(ot);
case EOF:
mesherror(USER, "truncated mesh octree");
default:
mesherror(USER, "damaged mesh octree");
}
return (OCTREE)0; /* pro forma return */
}
static void
skiptree() /* skip octree on input */
{
int i;
switch (getc(meshfp)) {
case OT_EMPTY:
return;
case OT_FULL:
for (i = mgetint(objsize)*objsize; i-- > 0; )
if (getc(meshfp) == EOF)
mesherror(USER, "truncated mesh octree");
return;
case OT_TREE:
for (i = 0; i < 8; i++)
skiptree();
return;
case EOF:
mesherror(USER, "truncated mesh octree");
default:
mesherror(USER, "damaged mesh octree");
}
}
static void
getpatch(pp) /* load a mesh patch */
MESHPATCH *pp;
{
int flags;
int i, j;
/* vertex flags */
flags = mgetint(1);
if (!(flags & MT_V) || flags & ~(MT_V|MT_N|MT_UV))
mesherror(USER, "bad patch flags");
/* allocate vertices */
pp->nverts = mgetint(2);
if ((pp->nverts <= 0) | (pp->nverts > 256))
mesherror(USER, "bad number of patch vertices");
pp->xyz = (uint32 (*)[3])malloc(pp->nverts*3*sizeof(uint32));
if (pp->xyz == NULL)
goto nomem;
if (flags & MT_N) {
pp->norm = (int32 *)calloc(pp->nverts, sizeof(int32));
if (pp->norm == NULL)
goto nomem;
} else
pp->norm = NULL;
if (flags & MT_UV) {
pp->uv = (uint32 (*)[2])calloc(pp->nverts, 2*sizeof(uint32));
if (pp->uv == NULL)
goto nomem;
} else
pp->uv = NULL;
/* vertex xyz locations */
for (i = 0; i < pp->nverts; i++)
for (j = 0; j < 3; j++)
pp->xyz[i][j] = mgetint(4);
/* vertex normals */
if (flags & MT_N)
for (i = 0; i < pp->nverts; i++)
pp->norm[i] = mgetint(4);
/* uv coordinates */
if (flags & MT_UV)
for (i = 0; i < pp->nverts; i++)
for (j = 0; j < 2; j++)
pp->uv[i][j] = mgetint(4);
/* local triangles */
pp->ntris = mgetint(2);
if ((pp->ntris < 0) | (pp->ntris > 512))
mesherror(USER, "bad number of local triangles");
if (pp->ntris) {
pp->tri = (struct PTri *)malloc(pp->ntris *
sizeof(struct PTri));
if (pp->tri == NULL)
goto nomem;
for (i = 0; i < pp->ntris; i++) {
pp->tri[i].v1 = mgetint(1);
pp->tri[i].v2 = mgetint(1);
pp->tri[i].v3 = mgetint(1);
}
} else
pp->tri = NULL;
/* local triangle material(s) */
if (mgetint(2) > 1) {
pp->trimat = (int16 *)malloc(pp->ntris*sizeof(int16));
if (pp->trimat == NULL)
goto nomem;
for (i = 0; i < pp->ntris; i++)
pp->trimat[i] = mgetint(2);
} else {
pp->solemat = mgetint(2);
pp->trimat = NULL;
}
/* joiner triangles */
pp->nj1tris = mgetint(2);
if ((pp->nj1tris < 0) | (pp->nj1tris > 256))
mesherror(USER, "bad number of joiner triangles");
if (pp->nj1tris) {
pp->j1tri = (struct PJoin1 *)malloc(pp->nj1tris *
sizeof(struct PJoin1));
if (pp->j1tri == NULL)
goto nomem;
for (i = 0; i < pp->nj1tris; i++) {
pp->j1tri[i].v1j = mgetint(4);
pp->j1tri[i].v2 = mgetint(1);
pp->j1tri[i].v3 = mgetint(1);
pp->j1tri[i].mat = mgetint(2);
}
} else
pp->j1tri = NULL;
/* double joiner triangles */
pp->nj2tris = mgetint(2);
if ((pp->nj2tris < 0) | (pp->nj2tris > 256))
mesherror(USER, "bad number of double joiner triangles");
if (pp->nj2tris) {
pp->j2tri = (struct PJoin2 *)malloc(pp->nj2tris *
sizeof(struct PJoin2));
if (pp->j2tri == NULL)
goto nomem;
for (i = 0; i < pp->nj2tris; i++) {
pp->j2tri[i].v1j = mgetint(4);
pp->j2tri[i].v2j = mgetint(4);
pp->j2tri[i].v3 = mgetint(1);
pp->j2tri[i].mat = mgetint(2);
}
} else
pp->j2tri = NULL;
return;
nomem:
error(SYSTEM, "out of mesh memory in getpatch");
}
void
readmesh(mp, path, flags) /* read in mesh structures */
MESH *mp;
char *path;
int flags;
{
char *err;
char sbuf[64];
int i;
/* check what's loaded */
flags &= (IO_INFO|IO_BOUNDS|IO_TREE|IO_SCENE) & ~mp->ldflags;
/* open input file */
if (path == NULL) {
meshfn = "standard input";
meshfp = stdin;
} else if ((meshfp = fopen(meshfn=path, "r")) == NULL) {
sprintf(errmsg, "cannot open mesh file \"%s\"", path);
error(SYSTEM, errmsg);
}
SET_FILE_BINARY(meshfp);
/* read header */
checkheader(meshfp, MESHFMT, flags&IO_INFO ? stdout : (FILE *)NULL);
/* read format number */
objsize = getint(2, meshfp) - MESHMAGIC;
if ((objsize <= 0) | (objsize > MAXOBJSIZ) | (objsize > sizeof(long)))
mesherror(USER, "incompatible mesh format");
/* read boundaries */
if (flags & IO_BOUNDS) {
for (i = 0; i < 3; i++)
mp->mcube.cuorg[i] = atof(getstr(sbuf, meshfp));
mp->mcube.cusize = atof(getstr(sbuf, meshfp));
for (i = 0; i < 2; i++) {
mp->uvlim[0][i] = mgetflt();
mp->uvlim[1][i] = mgetflt();
}
} else {
for (i = 0; i < 4; i++)
getstr(sbuf, meshfp);
for (i = 0; i < 4; i++)
mgetflt();
}
/* read the octree */
if (flags & IO_TREE)
mp->mcube.cutree = gettree();
else if (flags & IO_SCENE)
skiptree();
/* read materials and patches */
if (flags & IO_SCENE) {
mp->mat0 = nobjects;
readscene(meshfp, objsize);
mp->nmats = nobjects - mp->mat0;
mp->npatches = mgetint(4);
mp->patch = (MESHPATCH *)calloc(mp->npatches,
sizeof(MESHPATCH));
if (mp->patch == NULL)
mesherror(SYSTEM, "out of patch memory");
for (i = 0; i < mp->npatches; i++)
getpatch(&mp->patch[i]);
}
/* clean up */
if (meshfp != stdin)
fclose(meshfp);
mp->ldflags |= flags;
/* verify data */
if ((err = checkmesh(mp)) != NULL)
mesherror(USER, err);
}
| 23.473333 | 84 | 0.586907 | [
"mesh",
"object"
] |
36fd2a630b79548595bcd4370b5d569e121d45d3 | 9,417 | h | C | firmware/mpcnc-marlin/RC7_MPCNC_LCD_9916/SdVolume.h | AravinthPanch/araBot | 1c45a2aeceb3c956a5eba3835b87569046a4df5e | [
"Apache-2.0"
] | 9 | 2018-07-15T08:50:19.000Z | 2021-10-12T04:17:55.000Z | firmware/mpcnc-marlin/RC7_MPCNC_LCD_9916/SdVolume.h | AravinthPanch/araBot | 1c45a2aeceb3c956a5eba3835b87569046a4df5e | [
"Apache-2.0"
] | null | null | null | firmware/mpcnc-marlin/RC7_MPCNC_LCD_9916/SdVolume.h | AravinthPanch/araBot | 1c45a2aeceb3c956a5eba3835b87569046a4df5e | [
"Apache-2.0"
] | null | null | null | /**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Arduino SdFat Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino Sd2Card Library
*/
#include "Marlin.h"
#if ENABLED(SDSUPPORT)
#ifndef SdVolume_h
#define SdVolume_h
/**
* \file
* \brief SdVolume class
*/
#include "SdFatConfig.h"
#include "Sd2Card.h"
#include "SdFatStructs.h"
//==============================================================================
// SdVolume class
/**
* \brief Cache for an SD data block
*/
union cache_t {
/** Used to access cached file data blocks. */
uint8_t data[512];
/** Used to access cached FAT16 entries. */
uint16_t fat16[256];
/** Used to access cached FAT32 entries. */
uint32_t fat32[128];
/** Used to access cached directory entries. */
dir_t dir[16];
/** Used to access a cached Master Boot Record. */
mbr_t mbr;
/** Used to access to a cached FAT boot sector. */
fat_boot_t fbs;
/** Used to access to a cached FAT32 boot sector. */
fat32_boot_t fbs32;
/** Used to access to a cached FAT32 FSINFO sector. */
fat32_fsinfo_t fsinfo;
};
//------------------------------------------------------------------------------
/**
* \class SdVolume
* \brief Access FAT16 and FAT32 volumes on SD and SDHC cards.
*/
class SdVolume {
public:
/** Create an instance of SdVolume */
SdVolume() : fatType_(0) {}
/** Clear the cache and returns a pointer to the cache. Used by the WaveRP
* recorder to do raw write to the SD card. Not for normal apps.
* \return A pointer to the cache buffer or zero if an error occurs.
*/
cache_t* cacheClear() {
if (!cacheFlush()) return 0;
cacheBlockNumber_ = 0XFFFFFFFF;
return &cacheBuffer_;
}
/** Initialize a FAT volume. Try partition one first then try super
* floppy format.
*
* \param[in] dev The Sd2Card where the volume is located.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure. Reasons for
* failure include not finding a valid partition, not finding a valid
* FAT file system or an I/O error.
*/
bool init(Sd2Card* dev) { return init(dev, 1) ? true : init(dev, 0);}
bool init(Sd2Card* dev, uint8_t part);
// inline functions that return volume info
/** \return The volume's cluster size in blocks. */
uint8_t blocksPerCluster() const {return blocksPerCluster_;}
/** \return The number of blocks in one FAT. */
uint32_t blocksPerFat() const {return blocksPerFat_;}
/** \return The total number of clusters in the volume. */
uint32_t clusterCount() const {return clusterCount_;}
/** \return The shift count required to multiply by blocksPerCluster. */
uint8_t clusterSizeShift() const {return clusterSizeShift_;}
/** \return The logical block number for the start of file data. */
uint32_t dataStartBlock() const {return dataStartBlock_;}
/** \return The number of FAT structures on the volume. */
uint8_t fatCount() const {return fatCount_;}
/** \return The logical block number for the start of the first FAT. */
uint32_t fatStartBlock() const {return fatStartBlock_;}
/** \return The FAT type of the volume. Values are 12, 16 or 32. */
uint8_t fatType() const {return fatType_;}
int32_t freeClusterCount();
/** \return The number of entries in the root directory for FAT16 volumes. */
uint32_t rootDirEntryCount() const {return rootDirEntryCount_;}
/** \return The logical block number for the start of the root directory
on FAT16 volumes or the first cluster number on FAT32 volumes. */
uint32_t rootDirStart() const {return rootDirStart_;}
/** Sd2Card object for this volume
* \return pointer to Sd2Card object.
*/
Sd2Card* sdCard() {return sdCard_;}
/** Debug access to FAT table
*
* \param[in] n cluster number.
* \param[out] v value of entry
* \return true for success or false for failure
*/
bool dbgFat(uint32_t n, uint32_t* v) {return fatGet(n, v);}
//------------------------------------------------------------------------------
private:
// Allow SdBaseFile access to SdVolume private data.
friend class SdBaseFile;
// value for dirty argument in cacheRawBlock to indicate read from cache
static bool const CACHE_FOR_READ = false;
// value for dirty argument in cacheRawBlock to indicate write to cache
static bool const CACHE_FOR_WRITE = true;
#if USE_MULTIPLE_CARDS
cache_t cacheBuffer_; // 512 byte cache for device blocks
uint32_t cacheBlockNumber_; // Logical number of block in the cache
Sd2Card* sdCard_; // Sd2Card object for cache
bool cacheDirty_; // cacheFlush() will write block if true
uint32_t cacheMirrorBlock_; // block number for mirror FAT
#else // USE_MULTIPLE_CARDS
static cache_t cacheBuffer_; // 512 byte cache for device blocks
static uint32_t cacheBlockNumber_; // Logical number of block in the cache
static Sd2Card* sdCard_; // Sd2Card object for cache
static bool cacheDirty_; // cacheFlush() will write block if true
static uint32_t cacheMirrorBlock_; // block number for mirror FAT
#endif // USE_MULTIPLE_CARDS
uint32_t allocSearchStart_; // start cluster for alloc search
uint8_t blocksPerCluster_; // cluster size in blocks
uint32_t blocksPerFat_; // FAT size in blocks
uint32_t clusterCount_; // clusters in one FAT
uint8_t clusterSizeShift_; // shift to convert cluster count to block count
uint32_t dataStartBlock_; // first data block number
uint8_t fatCount_; // number of FATs on volume
uint32_t fatStartBlock_; // start block for first FAT
uint8_t fatType_; // volume type (12, 16, OR 32)
uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir
uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32
//----------------------------------------------------------------------------
bool allocContiguous(uint32_t count, uint32_t* curCluster);
uint8_t blockOfCluster(uint32_t position) const {
return (position >> 9) & (blocksPerCluster_ - 1);
}
uint32_t clusterStartBlock(uint32_t cluster) const {
return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_);
}
uint32_t blockNumber(uint32_t cluster, uint32_t position) const {
return clusterStartBlock(cluster) + blockOfCluster(position);
}
cache_t* cache() {return &cacheBuffer_;}
uint32_t cacheBlockNumber() {return cacheBlockNumber_;}
#if USE_MULTIPLE_CARDS
bool cacheFlush();
bool cacheRawBlock(uint32_t blockNumber, bool dirty);
#else // USE_MULTIPLE_CARDS
static bool cacheFlush();
static bool cacheRawBlock(uint32_t blockNumber, bool dirty);
#endif // USE_MULTIPLE_CARDS
// used by SdBaseFile write to assign cache to SD location
void cacheSetBlockNumber(uint32_t blockNumber, bool dirty) {
cacheDirty_ = dirty;
cacheBlockNumber_ = blockNumber;
}
void cacheSetDirty() {cacheDirty_ |= CACHE_FOR_WRITE;}
bool chainSize(uint32_t beginCluster, uint32_t* size);
bool fatGet(uint32_t cluster, uint32_t* value);
bool fatPut(uint32_t cluster, uint32_t value);
bool fatPutEOC(uint32_t cluster) {
return fatPut(cluster, 0x0FFFFFFF);
}
bool freeChain(uint32_t cluster);
bool isEOC(uint32_t cluster) const {
if (FAT12_SUPPORT && fatType_ == 12) return cluster >= FAT12EOC_MIN;
if (fatType_ == 16) return cluster >= FAT16EOC_MIN;
return cluster >= FAT32EOC_MIN;
}
bool readBlock(uint32_t block, uint8_t* dst) {
return sdCard_->readBlock(block, dst);
}
bool writeBlock(uint32_t block, const uint8_t* dst) {
return sdCard_->writeBlock(block, dst);
}
//------------------------------------------------------------------------------
// Deprecated functions - suppress cpplint warnings with NOLINT comment
#if ALLOW_DEPRECATED_FUNCTIONS && !defined(DOXYGEN)
public:
/** \deprecated Use: bool SdVolume::init(Sd2Card* dev);
* \param[in] dev The SD card where the volume is located.
* \return true for success or false for failure.
*/
bool init(Sd2Card& dev) {return init(&dev);} // NOLINT
/** \deprecated Use: bool SdVolume::init(Sd2Card* dev, uint8_t vol);
* \param[in] dev The SD card where the volume is located.
* \param[in] part The partition to be used.
* \return true for success or false for failure.
*/
bool init(Sd2Card& dev, uint8_t part) { // NOLINT
return init(&dev, part);
}
#endif // ALLOW_DEPRECATED_FUNCTIONS
};
#endif // SdVolume
#endif
| 41.302632 | 82 | 0.672826 | [
"object",
"3d"
] |
36fdc405b2fa1934712cf3c39aefe20e1b53ffdd | 4,573 | h | C | iOSOpenDev/frameworks/iTunesStoreUI.framework/Headers/SUWebView.h | bzxy/cydia | f8c838cdbd86e49dddf15792e7aa56e2af80548d | [
"MIT"
] | 678 | 2017-11-17T08:33:19.000Z | 2022-03-26T10:40:20.000Z | iOSOpenDev/frameworks/iTunesStoreUI.framework/Headers/SUWebView.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 22 | 2019-04-16T05:51:53.000Z | 2021-11-08T06:18:45.000Z | iOSOpenDev/frameworks/iTunesStoreUI.framework/Headers/SUWebView.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 170 | 2018-06-10T07:59:20.000Z | 2022-03-22T16:19:33.000Z | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iTunesStoreUI.framework/iTunesStoreUI
*/
#import <iTunesStoreUI/XXUnknownSuperclass.h>
#import <iTunesStoreUI/SUScriptInterfaceDelegate.h>
#import <iTunesStoreUI/iTunesStoreUI-Structs.h>
@class SUScriptInterface, NSString, SUScriptDebugDelegate, NSMutableArray, SUWebViewDelegate, SSAuthenticationContext, WebDataSource, WebView;
@protocol SUWebViewDelegate;
@interface SUWebView : XXUnknownSuperclass <SUScriptInterfaceDelegate> {
SSAuthenticationContext *_authenticationContext; // 52 = 0x34
SUScriptDebugDelegate *_debugDelegate; // 56 = 0x38
SUWebViewDelegate *_delegateProxy; // 60 = 0x3c
unsigned _openURLsExternally : 1; // 64 = 0x40
SUScriptInterface *_scriptInterface; // 68 = 0x44
NSMutableArray *_scrollRequests; // 72 = 0x48
unsigned _scrollingDisabled : 1; // 76 = 0x4c
unsigned _sourceIsTrusted : 1; // 76 = 0x4c
int _synchronousLayoutCount; // 80 = 0x50
}
@property(readonly, assign, nonatomic) WebView *webView; // G=0xa9ed;
@property(readonly, assign, nonatomic) OpaqueJSContext *globalExecutionContext; // G=0x9ee5;
@property(readonly, assign, nonatomic) id windowScriptObject; // G=0xa329;
@property(readonly, assign, nonatomic) WebDataSource *webDataSource; // G=0xa2f1;
@property(readonly, assign, nonatomic) SUScriptInterface *scriptInterface; // G=0xa011; @synthesize=_scriptInterface
@property(readonly, assign, nonatomic) NSString *title; // G=0xa2c9;
@property(assign, nonatomic) BOOL sourceIsTrusted; // G=0xa2b5; S=0xa26d;
@property(assign, nonatomic, getter=isScrollingEnabled) BOOL scrollingEnabled; // G=0x9fe5; S=0xa205;
@property(assign, nonatomic) BOOL openURLsExternally; // G=0x9ffd; S=0xa1e1;
@property(copy, nonatomic) SSAuthenticationContext *authenticationContext; // G=0xb13d; S=0xb14d; @synthesize=_authenticationContext
@property(assign, nonatomic) id<SUWebViewDelegate> delegate; // @dynamic
// declared property setter: - (void)setAuthenticationContext:(id)context; // 0xb14d
// declared property getter: - (id)authenticationContext; // 0xb13d
- (void)_performNextScrollRequest; // 0xaf79
- (id)_newLabelForElement:(id)element withText:(id)text; // 0xad2d
- (id)_newImageViewForElement:(id)element; // 0xac61
- (id)_localStoragePath; // 0xabb1
- (CGRect)_frameForElement:(id)element; // 0xaafd
- (void)_finishActiveScrollRequest; // 0xaa4d
- (id)_DOMDocument; // 0xaa15
// declared property getter: - (id)webView; // 0xa9ed
- (void)resetScriptInterface; // 0xa995
- (void)reloadWindowScriptObject:(id)object; // 0xa899
- (void)view:(id)view didSetFrame:(CGRect)frame oldFrame:(CGRect)frame3; // 0xa7e9
- (id)superviewForImageSheetForWebView:(id)webView; // 0xa7e5
- (void)scriptInterface:(id)interface receivedEventOfType:(int)type userInfo:(id)info; // 0xa785
- (void)scriptInterface:(id)interface parsedPropertyList:(id)list ofType:(int)type; // 0xa725
- (void)scriptInterface:(id)interface animatePurchaseForIdentifier:(id)identifier; // 0xa5ed
- (id)parentViewControllerForScriptInterface:(id)scriptInterface; // 0xa5bd
- (OpaqueJSContext *)javaScriptContextForScriptInterface:(id)scriptInterface; // 0xa5ad
- (void)_setRichTextReaderViewportSettings; // 0xa5a9
- (void)stopLoading; // 0xa55d
- (void)scrollViewDidEndScrollingAnimation:(id)scrollView; // 0xa4e1
// declared property getter: - (id)windowScriptObject; // 0xa329
// declared property getter: - (id)webDataSource; // 0xa2f1
// declared property getter: - (id)title; // 0xa2c9
// declared property getter: - (BOOL)sourceIsTrusted; // 0xa2b5
// declared property setter: - (void)setSourceIsTrusted:(BOOL)trusted; // 0xa26d
// declared property setter: - (void)setScrollingEnabled:(BOOL)enabled; // 0xa205
// declared property setter: - (void)setOpenURLsExternally:(BOOL)externally; // 0xa1e1
- (void)scrollElementToVisible:(id)visible animated:(BOOL)animated completionHandler:(id)handler; // 0xa0c5
// declared property getter: - (id)scriptInterface; // 0xa011
// declared property getter: - (BOOL)openURLsExternally; // 0x9ffd
// declared property getter: - (BOOL)isScrollingEnabled; // 0x9fe5
- (void)loadArchive:(id)archive; // 0x9f1d
// declared property getter: - (OpaqueJSContext *)globalExecutionContext; // 0x9ee5
- (CGRect)frameForElementWithIdentifier:(id)identifier; // 0x9e8d
- (void)endSynchronousLayout; // 0x9e01
- (BOOL)copyImage:(CGImageRef *)image rect:(CGRect *)rect forElement:(id)element; // 0x9d75
- (void)beginSynchronousLayout; // 0x9d1d
- (void)dealloc; // 0x9c6d
- (id)initWithFrame:(CGRect)frame; // 0x9895
@end
| 58.628205 | 142 | 0.769954 | [
"object"
] |
36fff7ba856783880859cc31568ab13386a8134b | 8,287 | h | C | lib/Onnxifi/Base.h | ssmetkar/glow | b28a7bd99a4807d1b7e55f02d6ff18c6b8e8f4d1 | [
"Apache-2.0"
] | 1 | 2019-03-10T04:04:29.000Z | 2019-03-10T04:04:29.000Z | lib/Onnxifi/Base.h | Capri2014/glow | e5f72ea7fc136f89ff8e7e997296643a8e4defe4 | [
"Apache-2.0"
] | null | null | null | lib/Onnxifi/Base.h | Capri2014/glow | e5f72ea7fc136f89ff8e7e997296643a8e4defe4 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GLOW_ONNXIFI_BASE_H
#define GLOW_ONNXIFI_BASE_H
#include "glow/Backends/Backend.h"
#include "glow/ExecutionEngine/ExecutionEngine.h"
#include "glow/Importer/ONNXIFIModelLoader.h"
#include "glow/Support/ThreadPool.h"
#include "foxi/onnxifi.h"
#include "foxi/onnxifi_ext.h"
#include <atomic>
#include <condition_variable>
#include <mutex>
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringMap.h"
namespace glow {
namespace onnxifi {
// TODO get rid of this once HostManager is landed.
struct HostManager {
bool addNetwork(Module *M) {
llvm_unreachable("HostManager is not yet implemented.");
}
};
// TODO use the actual type here once available.
using ResultCBTy =
std::function<void(int, int, std::unique_ptr<glow::PlaceholderBindings>)>;
/// BackendId associated with the Glow backend.
class BackendId {
public:
/// Create Glow ONNXIFI backend identifier with the
/// given Glow backend \p kind, \p id, \p concurrency, whether to use onnx
/// or caffe2 for models (\p useInnx), and whether to use HostManager instead
/// of ExecutionEngine for running graphs (useHostManager).
/// NOTE: useHostManager is not yet supported as HostManager is yet to be
/// fully implemented.
explicit BackendId(glow::BackendKind kind, int id, int concurrency,
bool useOnnx, bool useHostManager)
: id_(id), useOnnx_(useOnnx), concurrency_(concurrency),
glowBackend_(createBackend(kind)), useHostManager_(useHostManager) {}
bool isOpSupported(const NodeInfo &NI);
/// Verify that a given onnx graph is supported by the backend by importing
/// the onnx graph to a glow function, lowering this function, and checking
/// that all of the glow nodes that are contained in the lowered graph are
/// compatible with the glow backend.
onnxStatus checkGraphCompatibility(const void *onnxModel,
size_t onnxModelSize);
/// \returns the whether use onnx or not.
bool getUseOnnx() const { return useOnnx_; }
/// \returns the whether use HostManager for inference or not.
bool getUseHostManager() const { return useHostManager_; }
/// \returns HostManager associated with the BackendId.
HostManager &getHostManager() { return hostManager_; }
/// \returns the backend id.
int getID() const { return id_; }
/// \returns concurrency for the backend.
int getConcurrency() const { return concurrency_; }
/// \returns the glow Backend of this BackendId.
glow::Backend *getGlowBackend() { return glowBackend_.get(); }
/// Run the network named by \p networkName using HostManager with bindings \p
/// bindings afterwhich the result callback \p cb will be called.
void runOnHostManager(llvm::StringRef networkName,
std::unique_ptr<PlaceholderBindings> bindings,
ResultCBTy cb) {
// TODO enable once HostManager is landed.
// hostManager_->runNetwork(networkName, std::move(bindings),
// std::move(cb));
}
private:
int id_;
bool useOnnx_;
int concurrency_;
std::unique_ptr<glow::Backend> glowBackend_;
bool useHostManager_;
HostManager hostManager_; // TODO use real HostManager once landed.
};
typedef BackendId *BackendIdPtr;
class Backend {
public:
explicit Backend(BackendIdPtr backendId)
: backendIdPtr_(backendId), threadPool_(backendIdPtr_->getConcurrency()) {
}
/// Whether this backend uses ONNX proto or Caffe2 proto.
bool getUseOnnx() const { return backendIdPtr_->getUseOnnx(); }
/// \returns the whether use HostManager for inference or not.
bool getUseHostManager() const { return backendIdPtr_->getUseHostManager(); }
/// \returns HostManager for the associated BackendId.
HostManager &getHostManager() { return backendIdPtr_->getHostManager(); }
/// Run inference async using backend thread pool.
void runAsync(std::function<void(void)> &&fn);
/// \returns the glow Backend of the associated BackendId.
glow::Backend *getGlowBackend() { return backendIdPtr_->getGlowBackend(); }
// Call BackendId::runOnHostManager
void runOnHostManager(llvm::StringRef networkName,
std::unique_ptr<PlaceholderBindings> bindings,
ResultCBTy cb) {
backendIdPtr_->runOnHostManager(networkName, std::move(bindings),
std::move(cb));
}
private:
BackendIdPtr backendIdPtr_;
// ThreadPool instance for the backend.
ThreadPool threadPool_;
};
typedef Backend *BackendPtr;
class Event {
public:
Event() : fired_{false} {}
/// Signal the event.
bool signal();
/// Wait until the event is signalled.
void wait();
/// Check if event was signalled.
bool isSignalled() { return fired_; }
private:
std::atomic<bool> fired_;
std::mutex mutex_;
std::condition_variable cond_;
};
typedef Event *EventPtr;
class Graph {
public:
explicit Graph(BackendPtr backendPtr) : backendPtr_(backendPtr) {
executionEngine_.setBackend(backendPtr->getGlowBackend(),
/*ownsBackend*/ false);
}
BackendPtr backend() { return backendPtr_; }
/// Init Glow graph based on the ONNX model \p onnxModel and
/// static trained weights \p weightDescriptors.
onnxStatus initGraph(const void *onnxModel, size_t onnxModelSize,
uint32_t weightCount,
const onnxTensorDescriptorV1 *weightDescriptors);
/// Setup Glow graph in preparation for the inference.
/// Set input memory addresses for inputs based on the \p inputDescriptors.
/// Set output memory addresses for outputs based on
/// the \p outputDescriptors.
onnxStatus setIO(uint32_t inputsCount,
const onnxTensorDescriptorV1 *inputDescriptors,
uint32_t outputsCount,
const onnxTensorDescriptorV1 *outputDescriptors);
/// Run inference synchronously.
/// \params inputPlaceholderToBuffer contains mapping between input
/// placeholders and memory addresses input can be read from.
/// \params outputPlaceholderToBuffer contains mapping between output
/// placeholders and memory addresses output needs to be written to.
void run(const llvm::DenseMap<Placeholder *, onnxPointer>
&inputPlaceholderToBuffer,
const llvm::DenseMap<Placeholder *, onnxPointer>
&outputPlaceholderToBuffer);
/// Run inference asynchronously.
/// Inputs are ready when \p inputEvent is signalled.
/// \p outputEvent needs to be signalled when outputs are computed.
void runAsync(EventPtr inputEvent, EventPtr outputEvent);
private:
/// Execution engine to use to run this graph.
glow::ExecutionEngine executionEngine_;
BackendPtr backendPtr_;
Function *function_;
/// Mapping between ONNX name for the input variable and Glow
/// placeholder for input.
llvm::StringMap<Placeholder *> onnxInputToPlaceholder_;
/// Mapping between ONNX name for the output variable and Glow
/// placeholder for output.
llvm::StringMap<Placeholder *> onnxOutputToPlaceholder_;
/// Mapping between input placeholder and the actual memory address.
/// Inputs will be read from these addresses.
llvm::DenseMap<Placeholder *, onnxPointer> inputPlaceholderToBuffer_;
/// Mapping between output placeholder and the actual memory address.
/// Results must be written to these addresses.
llvm::DenseMap<Placeholder *, onnxPointer> outputPlaceholderToBuffer_;
/// Guard setIO and run. Make sequence of setIO and run
/// to be atomic.
std::mutex inputRunMutex_;
};
typedef Graph *GraphPtr;
} // namespace onnxifi
} // namespace glow
#endif // GLOW_ONNXIFI_BASE_H
| 34.67364 | 80 | 0.711114 | [
"model"
] |
3c05ad376ddc5bb86a121b4f3010025f005d0520 | 24,761 | h | C | Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_i2c.h | mrsin/https-github.com-mrsin-STM32F429I_ITG-3200_ADXL345 | 1ca1c4ac5248d4c5f6ee411f34ab5bcaef968a02 | [
"Unlicense"
] | 63 | 2015-08-14T23:27:39.000Z | 2022-03-09T22:46:11.000Z | Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_i2c.h | mrsin/STM32F429I_UART_DMA_loop | 4591f6e284a3709299de6f89ff6a78d02fd57641 | [
"Unlicense"
] | 64 | 2015-09-11T23:13:03.000Z | 2018-10-29T09:38:06.000Z | Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_i2c.h | mrsin/STM32F429I_UART_DMA_loop | 4591f6e284a3709299de6f89ff6a78d02fd57641 | [
"Unlicense"
] | 9 | 2016-01-06T00:06:33.000Z | 2021-12-07T10:38:15.000Z | /**
******************************************************************************
* @file stm32f4xx_hal_i2c.h
* @author MCD Application Team
* @version V1.4.1
* @date 09-October-2015
* @brief Header file of I2C HAL module.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2015 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics 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.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_I2C_H
#define __STM32F4xx_HAL_I2C_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal_def.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @addtogroup I2C
* @{
*/
/* Exported types ------------------------------------------------------------*/
/** @defgroup I2C_Exported_Types I2C Exported Types
* @{
*/
/**
* @brief I2C Configuration Structure definition
*/
typedef struct
{
uint32_t ClockSpeed; /*!< Specifies the clock frequency.
This parameter must be set to a value lower than 400kHz */
uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle.
This parameter can be a value of @ref I2C_duty_cycle_in_fast_mode */
uint32_t OwnAddress1; /*!< Specifies the first device own address.
This parameter can be a 7-bit or 10-bit address. */
uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected.
This parameter can be a value of @ref I2C_addressing_mode */
uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected.
This parameter can be a value of @ref I2C_dual_addressing_mode */
uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected
This parameter can be a 7-bit address. */
uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected.
This parameter can be a value of @ref I2C_general_call_addressing_mode */
uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected.
This parameter can be a value of @ref I2C_nostretch_mode */
}I2C_InitTypeDef;
/**
* @brief HAL State structures definition
*/
typedef enum
{
HAL_I2C_STATE_RESET = 0x00, /*!< I2C not yet initialized or disabled */
HAL_I2C_STATE_READY = 0x01, /*!< I2C initialized and ready for use */
HAL_I2C_STATE_BUSY = 0x02, /*!< I2C internal process is ongoing */
HAL_I2C_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */
HAL_I2C_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */
HAL_I2C_STATE_MEM_BUSY_TX = 0x32, /*!< Memory Data Transmission process is ongoing */
HAL_I2C_STATE_MEM_BUSY_RX = 0x42, /*!< Memory Data Reception process is ongoing */
HAL_I2C_STATE_TIMEOUT = 0x03, /*!< I2C timeout state */
HAL_I2C_STATE_ERROR = 0x04 /*!< I2C error state */
}HAL_I2C_StateTypeDef;
/**
* @brief I2C handle Structure definition
*/
typedef struct
{
I2C_TypeDef *Instance; /*!< I2C registers base address */
I2C_InitTypeDef Init; /*!< I2C communication parameters */
uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */
uint16_t XferSize; /*!< I2C transfer size */
__IO uint16_t XferCount; /*!< I2C transfer counter */
DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */
DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */
HAL_LockTypeDef Lock; /*!< I2C locking object */
__IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */
__IO uint32_t ErrorCode; /*!< I2C Error code */
}I2C_HandleTypeDef;
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup I2C_Exported_Constants I2C Exported Constants
* @{
*/
/** @defgroup I2C_Error_Code I2C Error Code
* @brief I2C Error Code
* @{
*/
#define HAL_I2C_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */
#define HAL_I2C_ERROR_BERR ((uint32_t)0x00000001) /*!< BERR error */
#define HAL_I2C_ERROR_ARLO ((uint32_t)0x00000002) /*!< ARLO error */
#define HAL_I2C_ERROR_AF ((uint32_t)0x00000004) /*!< AF error */
#define HAL_I2C_ERROR_OVR ((uint32_t)0x00000008) /*!< OVR error */
#define HAL_I2C_ERROR_DMA ((uint32_t)0x00000010) /*!< DMA transfer error */
#define HAL_I2C_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout Error */
/**
* @}
*/
/** @defgroup I2C_duty_cycle_in_fast_mode I2C duty cycle in fast mode
* @{
*/
#define I2C_DUTYCYCLE_2 ((uint32_t)0x00000000)
#define I2C_DUTYCYCLE_16_9 I2C_CCR_DUTY
/**
* @}
*/
/** @defgroup I2C_addressing_mode I2C addressing mode
* @{
*/
#define I2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00004000)
#define I2C_ADDRESSINGMODE_10BIT (I2C_OAR1_ADDMODE | ((uint32_t)0x00004000))
/**
* @}
*/
/** @defgroup I2C_dual_addressing_mode I2C dual addressing mode
* @{
*/
#define I2C_DUALADDRESS_DISABLE ((uint32_t)0x00000000)
#define I2C_DUALADDRESS_ENABLE I2C_OAR2_ENDUAL
/**
* @}
*/
/** @defgroup I2C_general_call_addressing_mode I2C general call addressing mode
* @{
*/
#define I2C_GENERALCALL_DISABLE ((uint32_t)0x00000000)
#define I2C_GENERALCALL_ENABLE I2C_CR1_ENGC
/**
* @}
*/
/** @defgroup I2C_nostretch_mode I2C nostretch mode
* @{
*/
#define I2C_NOSTRETCH_DISABLE ((uint32_t)0x00000000)
#define I2C_NOSTRETCH_ENABLE I2C_CR1_NOSTRETCH
/**
* @}
*/
/** @defgroup I2C_Memory_Address_Size I2C Memory Address Size
* @{
*/
#define I2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001)
#define I2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000010)
/**
* @}
*/
/** @defgroup I2C_Interrupt_configuration_definition I2C Interrupt configuration definition
* @{
*/
#define I2C_IT_BUF I2C_CR2_ITBUFEN
#define I2C_IT_EVT I2C_CR2_ITEVTEN
#define I2C_IT_ERR I2C_CR2_ITERREN
/**
* @}
*/
/** @defgroup I2C_Flag_definition I2C Flag definition
* @{
*/
#define I2C_FLAG_SMBALERT ((uint32_t)0x00018000)
#define I2C_FLAG_TIMEOUT ((uint32_t)0x00014000)
#define I2C_FLAG_PECERR ((uint32_t)0x00011000)
#define I2C_FLAG_OVR ((uint32_t)0x00010800)
#define I2C_FLAG_AF ((uint32_t)0x00010400)
#define I2C_FLAG_ARLO ((uint32_t)0x00010200)
#define I2C_FLAG_BERR ((uint32_t)0x00010100)
#define I2C_FLAG_TXE ((uint32_t)0x00010080)
#define I2C_FLAG_RXNE ((uint32_t)0x00010040)
#define I2C_FLAG_STOPF ((uint32_t)0x00010010)
#define I2C_FLAG_ADD10 ((uint32_t)0x00010008)
#define I2C_FLAG_BTF ((uint32_t)0x00010004)
#define I2C_FLAG_ADDR ((uint32_t)0x00010002)
#define I2C_FLAG_SB ((uint32_t)0x00010001)
#define I2C_FLAG_DUALF ((uint32_t)0x00100080)
#define I2C_FLAG_SMBHOST ((uint32_t)0x00100040)
#define I2C_FLAG_SMBDEFAULT ((uint32_t)0x00100020)
#define I2C_FLAG_GENCALL ((uint32_t)0x00100010)
#define I2C_FLAG_TRA ((uint32_t)0x00100004)
#define I2C_FLAG_BUSY ((uint32_t)0x00100002)
#define I2C_FLAG_MSL ((uint32_t)0x00100001)
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/** @defgroup I2C_Exported_Macros I2C Exported Macros
* @{
*/
/** @brief Reset I2C handle state
* @param __HANDLE__: specifies the I2C Handle.
* This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral.
* @retval None
*/
#define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET)
/** @brief Enable or disable the specified I2C interrupts.
* @param __HANDLE__: specifies the I2C Handle.
* This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral.
* @param __INTERRUPT__: specifies the interrupt source to enable or disable.
* This parameter can be one of the following values:
* @arg I2C_IT_BUF: Buffer interrupt enable
* @arg I2C_IT_EVT: Event interrupt enable
* @arg I2C_IT_ERR: Error interrupt enable
* @retval None
*/
#define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__))
#define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__)))
/** @brief Checks if the specified I2C interrupt source is enabled or disabled.
* @param __HANDLE__: specifies the I2C Handle.
* This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral.
* @param __INTERRUPT__: specifies the I2C interrupt source to check.
* This parameter can be one of the following values:
* @arg I2C_IT_BUF: Buffer interrupt enable
* @arg I2C_IT_EVT: Event interrupt enable
* @arg I2C_IT_ERR: Error interrupt enable
* @retval The new state of __INTERRUPT__ (TRUE or FALSE).
*/
#define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET)
/** @brief Checks whether the specified I2C flag is set or not.
* @param __HANDLE__: specifies the I2C Handle.
* This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral.
* @param __FLAG__: specifies the flag to check.
* This parameter can be one of the following values:
* @arg I2C_FLAG_SMBALERT: SMBus Alert flag
* @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag
* @arg I2C_FLAG_PECERR: PEC error in reception flag
* @arg I2C_FLAG_OVR: Overrun/Underrun flag
* @arg I2C_FLAG_AF: Acknowledge failure flag
* @arg I2C_FLAG_ARLO: Arbitration lost flag
* @arg I2C_FLAG_BERR: Bus error flag
* @arg I2C_FLAG_TXE: Data register empty flag
* @arg I2C_FLAG_RXNE: Data register not empty flag
* @arg I2C_FLAG_STOPF: Stop detection flag
* @arg I2C_FLAG_ADD10: 10-bit header sent flag
* @arg I2C_FLAG_BTF: Byte transfer finished flag
* @arg I2C_FLAG_ADDR: Address sent flag
* Address matched flag
* @arg I2C_FLAG_SB: Start bit flag
* @arg I2C_FLAG_DUALF: Dual flag
* @arg I2C_FLAG_SMBHOST: SMBus host header
* @arg I2C_FLAG_SMBDEFAULT: SMBus default header
* @arg I2C_FLAG_GENCALL: General call header flag
* @arg I2C_FLAG_TRA: Transmitter/Receiver flag
* @arg I2C_FLAG_BUSY: Bus busy flag
* @arg I2C_FLAG_MSL: Master/Slave flag
* @retval The new state of __FLAG__ (TRUE or FALSE).
*/
#define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) ((((uint8_t)((__FLAG__) >> 16)) == 0x01)?((((__HANDLE__)->Instance->SR1) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)): \
((((__HANDLE__)->Instance->SR2) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK)))
/** @brief Clears the I2C pending flags which are cleared by writing 0 in a specific bit.
* @param __HANDLE__: specifies the I2C Handle.
* This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral.
* @param __FLAG__: specifies the flag to clear.
* This parameter can be any combination of the following values:
* @arg I2C_FLAG_SMBALERT: SMBus Alert flag
* @arg I2C_FLAG_TIMEOUT: Timeout or Tlow error flag
* @arg I2C_FLAG_PECERR: PEC error in reception flag
* @arg I2C_FLAG_OVR: Overrun/Underrun flag (Slave mode)
* @arg I2C_FLAG_AF: Acknowledge failure flag
* @arg I2C_FLAG_ARLO: Arbitration lost flag (Master mode)
* @arg I2C_FLAG_BERR: Bus error flag
* @retval None
*/
#define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR1 = ~((__FLAG__) & I2C_FLAG_MASK))
/** @brief Clears the I2C ADDR pending flag.
* @param __HANDLE__: specifies the I2C Handle.
* This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral.
* @retval None
*/
#define __HAL_I2C_CLEAR_ADDRFLAG(__HANDLE__) \
do{ \
__IO uint32_t tmpreg; \
tmpreg = (__HANDLE__)->Instance->SR1; \
tmpreg = (__HANDLE__)->Instance->SR2; \
UNUSED(tmpreg); \
} while(0)
/** @brief Clears the I2C STOPF pending flag.
* @param __HANDLE__: specifies the I2C Handle.
* This parameter can be I2C where x: 1, 2, or 3 to select the I2C peripheral.
* @retval None
*/
#define __HAL_I2C_CLEAR_STOPFLAG(__HANDLE__) \
do{ \
__IO uint32_t tmpreg; \
tmpreg = (__HANDLE__)->Instance->SR1; \
(__HANDLE__)->Instance->CR1 |= I2C_CR1_PE; \
UNUSED(tmpreg); \
} while(0)
#define __HAL_I2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE)
#define __HAL_I2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE)
/**
* @}
*/
/* Include I2C HAL Extension module */
#include "stm32f4xx_hal_i2c_ex.h"
/* Exported functions --------------------------------------------------------*/
/** @addtogroup I2C_Exported_Functions
* @{
*/
/** @addtogroup I2C_Exported_Functions_Group1
* @{
*/
/* Initialization/de-initialization functions **********************************/
HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c);
HAL_StatusTypeDef HAL_I2C_DeInit (I2C_HandleTypeDef *hi2c);
void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c);
/**
* @}
*/
/** @addtogroup I2C_Exported_Functions_Group2
* @{
*/
/* I/O operation functions *****************************************************/
/******* Blocking mode: Polling */
HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout);
/******* Non-Blocking mode: Interrupt */
HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size);
/******* Non-Blocking mode: DMA */
HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size);
HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size);
/******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */
void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c);
void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c);
/**
* @}
*/
/** @addtogroup I2C_Exported_Functions_Group3
* @{
*/
/* Peripheral Control and State functions **************************************/
HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c);
uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c);
/**
* @}
*/
/**
* @}
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup I2C_Private_Constants I2C Private Constants
* @{
*/
#define I2C_FLAG_MASK ((uint32_t)0x0000FFFF)
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup I2C_Private_Macros I2C Private Macros
* @{
*/
#define I2C_FREQRANGE(__PCLK__) ((__PCLK__)/1000000)
#define I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (((__SPEED__) <= 100000) ? ((__FREQRANGE__) + 1) : ((((__FREQRANGE__) * 300) / 1000) + 1))
#define I2C_SPEED_STANDARD(__PCLK__, __SPEED__) (((((__PCLK__)/((__SPEED__) << 1)) & I2C_CCR_CCR) < 4)? 4:((__PCLK__) / ((__SPEED__) << 1)))
#define I2C_SPEED_FAST(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__DUTYCYCLE__) == I2C_DUTYCYCLE_2)? ((__PCLK__) / ((__SPEED__) * 3)) : (((__PCLK__) / ((__SPEED__) * 25)) | I2C_DUTYCYCLE_16_9))
#define I2C_SPEED(__PCLK__, __SPEED__, __DUTYCYCLE__) (((__SPEED__) <= 100000)? (I2C_SPEED_STANDARD((__PCLK__), (__SPEED__))) : \
((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__)) & I2C_CCR_CCR) == 0)? 1 : \
((I2C_SPEED_FAST((__PCLK__), (__SPEED__), (__DUTYCYCLE__))) | I2C_CCR_FS))
#define I2C_7BIT_ADD_WRITE(__ADDRESS__) ((uint8_t)((__ADDRESS__) & (~I2C_OAR1_ADD0)))
#define I2C_7BIT_ADD_READ(__ADDRESS__) ((uint8_t)((__ADDRESS__) | I2C_OAR1_ADD0))
#define I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF))))
#define I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF0))))
#define I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF1))))
#define I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8)))
#define I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF))))
/** @defgroup I2C_IS_RTC_Definitions I2C Private macros to check input parameters
* @{
*/
#define IS_I2C_DUTY_CYCLE(CYCLE) (((CYCLE) == I2C_DUTYCYCLE_2) || \
((CYCLE) == I2C_DUTYCYCLE_16_9))
#define IS_I2C_ADDRESSING_MODE(ADDRESS) (((ADDRESS) == I2C_ADDRESSINGMODE_7BIT) || \
((ADDRESS) == I2C_ADDRESSINGMODE_10BIT))
#define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLE) || \
((ADDRESS) == I2C_DUALADDRESS_ENABLE))
#define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLE) || \
((CALL) == I2C_GENERALCALL_ENABLE))
#define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLE) || \
((STRETCH) == I2C_NOSTRETCH_ENABLE))
#define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \
((SIZE) == I2C_MEMADD_SIZE_16BIT))
#define IS_I2C_CLOCK_SPEED(SPEED) (((SPEED) > 0) && ((SPEED) <= 400000))
#define IS_I2C_OWN_ADDRESS1(ADDRESS1) (((ADDRESS1) & (uint32_t)(0xFFFFFC00)) == 0)
#define IS_I2C_OWN_ADDRESS2(ADDRESS2) (((ADDRESS2) & (uint32_t)(0xFFFFFF01)) == 0)
/**
* @}
*/
/**
* @}
*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup I2C_Private_Functions I2C Private Functions
* @{
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F4xx_HAL_I2C_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 46.195896 | 191 | 0.610274 | [
"object"
] |
3c0787e2405c27387dda7b127d795ab2a79cbdf3 | 1,949 | h | C | MinecraftC/Minecraft.h | lionkor/MinecraftC | adf0a28fcc46e1af98e1275903435c7004025ac8 | [
"MIT"
] | null | null | null | MinecraftC/Minecraft.h | lionkor/MinecraftC | adf0a28fcc46e1af98e1275903435c7004025ac8 | [
"MIT"
] | null | null | null | MinecraftC/Minecraft.h | lionkor/MinecraftC | adf0a28fcc46e1af98e1275903435c7004025ac8 | [
"MIT"
] | null | null | null | #pragma once
#include <SDL2/SDL.h>
#include "GameMode/GameMode.h"
#include "Render/LevelRenderer.h"
#include "Particle/ParticleManager.h"
#include "GUI/GUIScreen.h"
#include "GUI/HUDScreen.h"
#include "Render/Renderer.h"
#include "Level/LevelIO.h"
#include "Timer.h"
#include "SessionData.h"
#include "ProgressBarDisplay.h"
typedef void * MinecraftApplet;
typedef struct Minecraft
{
GameMode GameMode;
bool FullScreen;
int Width, FrameWidth;
int Height, FrameHeight;
Timer Timer;
Level Level;
LevelRenderer LevelRenderer;
Player Player;
ParticleManager ParticleManager;
SessionData Session;
char * Host;
SDL_Window * Window;
SDL_GLContext Context;
bool LevelLoaded;
bool Waiting;
TextureManager TextureManager;
FontRenderer Font;
GUIScreen CurrentScreen;
ProgressBarDisplay ProgressBar;
Renderer Renderer;
LevelIO LevelIO;
//SoundManager SoundManager;
//ResourceDownloadThread ResourceThread;
int Ticks;
int BlockHitTime;
char * LevelName;
int LevelID;
//Robot Robot;
HUDScreen HUD;
bool Online;
//NetworkManager NetworkManager;
//SoundPlayer SoundPlayer;
MovingObjectPosition Selected;
GameSettings Settings;
struct MinecraftApplet * Applet;
char * Server;
int Port;
bool Running;
String Debug;
bool HasMouse;
int LastClick;
bool Raining;
char * WorkingDirectory;
} * Minecraft;
Minecraft MinecraftCreate(MinecraftApplet applet, int width, int height, bool fullScreen);
void MinecraftSetCurrentScreen(Minecraft minecraft, GUIScreen screen);
void MinecraftShutdown(Minecraft minecraft);
void MinecraftRun(Minecraft minecraft);
void MinecraftGrabMouse(Minecraft minecraft);
void MinecraftPause(Minecraft minecraft);
bool MinecraftIsOnline(Minecraft minecraft);
void MinecraftGenerateLevel(Minecraft minecraft, int size);
bool MinecraftLoadOnlineLevel(Minecraft minecraft, char * username, int userID);
void MinecraftSetLevel(Minecraft minecraft, Level level);
void MinecraftDestroy(Minecraft minecraft);
| 26.337838 | 90 | 0.800924 | [
"render"
] |
3c079cffaa6944cbc895b2dce8b86c628a63baf2 | 353 | h | C | include/raytracing/primitive/FlatUVMeshTriangle.h | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | include/raytracing/primitive/FlatUVMeshTriangle.h | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | include/raytracing/primitive/FlatUVMeshTriangle.h | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | #pragma once
#include "raytracing/primitive/FlatMeshTriangle.h"
namespace rt
{
class FlatUVMeshTriangle : public FlatMeshTriangle
{
public:
FlatUVMeshTriangle() {}
FlatUVMeshTriangle(std::shared_ptr<Mesh> mesh, int i1, int i2, int i3);
virtual bool Hit(const Ray& ray, double& t, ShadeRec& s) const override;
}; // FlatUVMeshTriangle
} | 19.611111 | 76 | 0.733711 | [
"mesh"
] |
3c07b01f3f9c10e390c905a30d74dc7d60db90d9 | 15,330 | h | C | src/ClientData.h | hassan-c/audacity | 9fca022f59723ff9d5a457d06451b173db1df4fb | [
"CC-BY-3.0"
] | null | null | null | src/ClientData.h | hassan-c/audacity | 9fca022f59723ff9d5a457d06451b173db1df4fb | [
"CC-BY-3.0"
] | 1 | 2021-07-24T13:45:07.000Z | 2021-07-24T13:45:07.000Z | src/ClientData.h | hassan-c/audacity | 9fca022f59723ff9d5a457d06451b173db1df4fb | [
"CC-BY-3.0"
] | null | null | null | /**********************************************************************
Audacity: A Digital Audio Editor
ClientData.h
Paul Licameli
**********************************************************************/
#ifndef __AUDACITY_CLIENT_DATA__
#define __AUDACITY_CLIENT_DATA__
#include "ClientDataHelpers.h"
#include <functional>
#include <iterator>
#include <utility>
#include <vector>
#include "InconsistencyException.h"
namespace ClientData {
// A convenient default parameter for class template Site below
struct AUDACITY_DLL_API Base
{
virtual ~Base() {}
};
// Need a truly one-argument alias template below for the default
// template-template argument of Site
// (unique_ptr has two, the second is defaulted)
template< typename Object > using UniquePtr = std::unique_ptr< Object >;
// A convenient base class defining abstract virtual Clone() for a given kind
// of pointer
template<
template<typename> class Owner = UniquePtr
> struct Cloneable
{
using Base = Cloneable;
using PointerType = Owner< Base >;
virtual ~Cloneable() {}
virtual PointerType Clone() const = 0;
};
/*
\brief ClientData::Site class template enables decoupling of the
implementation of core data structures, inheriting it, from compilation and
link dependency on the details of other user interface modules, while also
allowing the latter to associate their own extra data caches with each
instance of the core class, and the caches can have a coterminous lifetime.
This can implement an "observer pattern" in which the core object pushes
notifications to client-side handlers, or it can just implement storage
and retrieval services for the client.
typical usage pattern in core code:
class Host;
class AbstractClientData // Abstract base class for attached data
{
virtual ~AbstractClientData(); // minimum for memory management
// optional extra observer protocols
virtual void NotificationMethod(
// maybe host passes reference to self, maybe not
// Host &host
) = 0;
};
class Host
: public ClientData::Site< Host, AbstractClientData >
// That inheritance is a case of CRTP
// (the "curiously recurring template pattern")
// in which the base class takes the derived class as a template argument
{
public:
Host()
{
// If using an Observer protocol, force early creation of all client
// data:
BuildAll();
}
void NotifyAll()
{
// Visit all non-null objects
ForEach( []( AbstractClientData &data ){
data.NotificationMethod(
// *this
);
} );
}
}
typical usage pattern in client module -- observer pattern, and retrieval
class MyClientData : public AbstractClientData
{
public:
MyClientData( Host &host )
{
// ... use host, maybe keep a back pointer to it, maybe not,
// depending how Host declares NotificationMethod ...
// ... Maybe Host too is an abstract class and we invoke some
// virtual function of it ...
}
void NotificationMethod(
// Host &host
) override
{
// ... Observer actions
// (If there is more than one separately compiled module using this
// protocol, beware that the sequence of notifications is unspecified)
}
private:
int mExtraStuff;
};
// Registration of a factory at static initialization time, to be called
// when a Host uses BuildAll, or else lazily when client code uses
// Host::Get()
static const Host::RegisteredFactory key{
[]( Host &host ){ return std::make_unique< MyClientData >( host ); }
};
// Use of that key at other times, not dependent on notifications from
// the core
void DoSomething( Host &host )
{
// This may force lazy construction of ClientData, always returning
// an object (or else throwing)
auto &data = host.Get< MyClientData >( key );
auto val = data.mExtraStuff;
// ...
}
void DoAnotherThing( Host &host )
{
// Does not force lazy construction of ClientData
auto *pData = host.Find< MyClientData >( key );
if ( pData ) {
auto val = data.mExtraStuff;
// ...
}
}
void DoYetAnotherThing( Host &host )
{
// Reassign the pointer in this client's slot
host.Assign( key, MyReplacementObject( host ) );
}
About laziness: If the client only needs retrieval, it might need
construction of data only on demand. But if the host is meant to push
notifications to the clients, then the host class is responsible for forcing
early building of all ClientData when host is constructed, as in the example
above.
About unusual registration sequences: if registration of a factory
happens after some host objects are already in existence, their associated
client data fail to be created if you rely only on BuildAll in the Host
constructor. Early deregistration of factories is permitted, in which case
any later constructed host objects will carry null pointers in the associated
slot, and a small "leak" in the space of per-host slots will persist until
the program exits. All such usage is not recommended.
*/
template<
typename Host,
typename ClientData = Base,
// Remaining parameters are often defaulted
CopyingPolicy ObjectCopyingPolicy = SkipCopying,
// The kind of pointer Host will hold to ClientData; you might want to
// use std::shared_ptr, std::weak_ptr, or wxWeakRef instead
template<typename> class Pointer = UniquePtr,
// Thread safety policies for the tables of ClientData objects in each Host
// object, and for the static factory function registry
LockingPolicy ObjectLockingPolicy = NoLocking,
LockingPolicy RegistryLockingPolicy = NoLocking
>
class Site
{
public:
~Site()
{
static_assert( std::has_virtual_destructor<ClientData>::value,
"ClientData::Site requires a data class with a virtual destructor" );
}
// Associated type aliases
using DataType = ClientData;
using DataPointer = Pointer< ClientData >;
using DataFactory = std::function< DataPointer( Host& ) >;
Site()
{
auto factories = GetFactories();
auto size = factories.mObject.size();
mData.reserve( size );
}
Site( const Site &other )
: mData( other.mData )
{ }
Site& operator =( const Site & other )
{ mData = other.mData; return *this; }
Site( Site && other )
: mData( std::move(other.mData) )
{ }
Site& operator =( Site && other )
{ mData = std::move(other.mData); return *this; }
size_t size() const { return mData.size(); }
/// \brief a type meant to be stored by client code in a static variable,
/// and used as a retrieval key to get the manufactured client object back
/// from the host object.
/// It can be destroyed to de-register the factory, but usually not before
/// destruction of statics at program exit.
class RegisteredFactory
{
public:
RegisteredFactory( DataFactory factory )
{
auto factories = GetFactories();
mIndex = factories.mObject.size();
factories.mObject.emplace_back( std::move( factory ) );
}
RegisteredFactory( RegisteredFactory &&other )
{
mIndex = other.mIndex;
mOwner = other.mOwner;
other.mOwner = false;
}
~RegisteredFactory()
{
if (mOwner) {
auto factories = GetFactories();
// Should always be true, the factory vector never shrinks:
if ( mIndex < factories.mObject.size() )
factories.mObject[mIndex] = nullptr;
}
}
private:
friend Site;
bool mOwner{ true };
size_t mIndex;
};
// member functions for use by clients
// \brief Get a reference to an object, creating it on demand if needed, and
// down-cast it with static_cast. Throws on failure to create it.
// (Lifetime of the object may depend on the Host's lifetime and also on the
// client's use of Assign(). Site is not responsible for guarantees.)
template< typename Subclass = ClientData >
Subclass &Get( const RegisteredFactory &key )
{
auto data = GetData();
return DoGet< Subclass >( data, key );
}
// const counterpart of the previous
template< typename Subclass = const ClientData >
auto Get( const RegisteredFactory &key ) const -> typename
std::enable_if< std::is_const< Subclass >::value, Subclass & >::type
{
auto data = GetData();
return DoGet< Subclass >( data, key );
}
// \brief Get a (bare) pointer to an object, or null, and down-cast it with
// static_cast. Do not create any object.
// (Lifetime of the object may depend on the Host's lifetime and also on the
// client's use of Assign(). Site is not responsible for guarantees.)
template< typename Subclass = ClientData >
Subclass *Find( const RegisteredFactory &key )
{
auto data = GetData();
return DoFind< Subclass >( data, key );
}
// const counterpart of the previous
template< typename Subclass = const ClientData >
auto Find( const RegisteredFactory &key ) const -> typename
std::enable_if< std::is_const< Subclass >::value, Subclass * >::type
{
auto data = GetData();
return DoFind< Subclass >( data, key );
}
// \brief Reassign Host's pointer to ClientData.
// If there is object locking, then reassignments to the same slot in the
// same host object are serialized.
template< typename ReplacementPointer >
void Assign( const RegisteredFactory &key, ReplacementPointer &&replacement )
{
auto index = key.mIndex;
auto data = GetData();
EnsureIndex( data, index );
auto iter = GetIterator( data, index );
// Copy or move as appropriate:
*iter = std::forward< ReplacementPointer >( replacement );
}
protected:
// member functions for use by Host
// \brief Invoke function on each ClientData object that has been created in
// this, but do not cause the creation of any.
template< typename Function >
void ForEach( const Function &function )
{
auto data = GetData();
for( auto &pObject : data.mObject ) {
const auto &ptr = Dereferenceable(pObject);
if ( ptr )
function( *ptr );
}
}
// const counterpart of previous, only compiles with a function that takes
// a value or const reference argument
template< typename Function >
void ForEach( const Function &function ) const
{
auto data = GetData();
for( auto &pObject : data.mObject ) {
const auto &ptr = Dereferenceable(pObject);
if ( ptr ) {
const auto &c_ref = *ptr;
function( c_ref );
}
}
}
// \brief For each registered factory, if the corresponding object in this
// is absent, then invoke the factory and store the result.
void BuildAll()
{
// Note that we cannot call this function in the Site constructor as we
// might wish, because we pass *this to the factories, but this is not yet
// fully constructed as the ultimate derived class. So delayed calls to
// this function are needed.
size_t size;
{
auto factories = GetFactories();
size = factories.mObject.size();
// Release lock on factories before getting one on data -- otherwise
// there would be a deadlock possibility inside Ensure
}
auto data = GetData();
EnsureIndex( data, size - 1 );
auto iter = GetIterator( data, 0 );
for ( size_t ii = 0; ii < size; ++ii, ++iter )
static_cast< void >( Build( data, iter, ii ) );
}
private:
using DataFactories =
Lockable< std::vector< DataFactory >, RegistryLockingPolicy >;
using DataContainer =
Lockable<
Copyable< std::vector< DataPointer >, ObjectCopyingPolicy >,
ObjectLockingPolicy
>;
decltype( Dereferenceable( std::declval<DataPointer&>() ) )
Slot( Locked<DataContainer> &data, const RegisteredFactory &key, bool create )
{
auto index = key.mIndex;
EnsureIndex( data, index );
auto iter = GetIterator( data, index );
auto &pointer = create ? Build( data, iter, index ) : *iter;
return Dereferenceable( pointer );
}
template< typename Subclass >
Subclass &DoGet( Locked<DataContainer> &data, const RegisteredFactory &key )
{
const auto &d = Slot( data, key, true );
if (!d)
// Oops, a factory was deregistered too soon, or returned a null, or
// the pointer was reassigned null
THROW_INCONSISTENCY_EXCEPTION;
return static_cast< Subclass& >( *d );
}
template< typename Subclass >
Subclass *DoFind( Locked<DataContainer> &data, const RegisteredFactory &key )
{
const auto &d = Slot( data, key, false );
if (!d)
return nullptr;
else
return static_cast< Subclass* >( &*d );
}
static Locked< DataFactories > GetFactories()
{
// C++11 does not need extra thread synch for static initialization
// Note that linker eliminates duplicates of this function
static DataFactories factories;
// But give back a scoped lock to the user of this function, in case
// there is contention to resize the vector
return Locked< DataFactories >{ factories };
}
Locked<DataContainer> GetData()
{
return Locked< DataContainer >{ mData };
}
Locked<const DataContainer> GetData() const
{
return Locked< const DataContainer >{ mData };
}
static void EnsureIndex( Locked<DataContainer> &data, size_t index )
{
if (data.mObject.size() <= index)
data.mObject.resize(index + 1);
}
static typename DataContainer::iterator inline
GetIterator( Locked<DataContainer> &data, size_t index )
{
// This function might help generalize Site with different kinds of
// containers for pointers to ClientData that are not random-access.
// Perhaps non-relocation of elements will be needed.
// Perhaps another template-template parameter could vary the kind of
// container.
auto result = data.mObject.begin();
std::advance( result, index );
return result;
}
DataPointer &Build( Locked<DataContainer> &,
typename DataContainer::iterator iter, size_t index )
{
// If there is no object at index, then invoke the factory, else do
// nothing.
// The factory may be null or may return null, in which case do nothing.
auto &result = *iter;
if (!Dereferenceable(result)) {
// creation on demand
auto factories = GetFactories();
auto &factory = factories.mObject[index];
result = factory
? factory( static_cast< Host& >( *this ) )
: DataPointer{};
}
return result;
}
// Container of pointers returned by factories, per instance of Host class
// This is the only non-static data member that Site injects into the
// derived class.
DataContainer mData;
};
}
#endif
| 32.410148 | 81 | 0.643509 | [
"object",
"vector"
] |
3c0839b5696c6298da13c65e9621aa1f8ed000c2 | 1,327 | h | C | src/UIItem.h | ncnnnnn/kys-cpp-prtest | dad990a3bdf9299732f5332f6f5a5e3fc241f6ef | [
"FTL"
] | 1,565 | 2016-07-12T17:11:28.000Z | 2022-03-31T07:43:53.000Z | src/UIItem.h | ncnnnnn/kys-cpp-prtest | dad990a3bdf9299732f5332f6f5a5e3fc241f6ef | [
"FTL"
] | 21 | 2018-06-10T14:15:06.000Z | 2022-02-28T06:01:38.000Z | src/UIItem.h | ncnnnnn/kys-cpp-prtest | dad990a3bdf9299732f5332f6f5a5e3fc241f6ef | [
"FTL"
] | 268 | 2016-07-11T07:05:55.000Z | 2022-02-18T01:49:11.000Z | #pragma once
#include "Button.h"
#include "Menu.h"
#include "Types.h"
class UIItem : public Menu
{
public:
UIItem();
~UIItem();
//这里注意,用来显示物品图片的按钮的纹理编号实际就是物品编号
std::vector<std::shared_ptr<Button>> item_buttons_;
std::shared_ptr<TextBox> cursor_;
int leftup_index_ = 0; //左上角第一个物品在当前种类列表中的索引
int max_leftup_ = 0;
const int item_each_line_ = 7;
const int line_count_ = 3;
std::shared_ptr<MenuText> title_;
int force_item_type_ = -1;
bool select_user_ = true;
int focus_ = 0; //焦点位置:0分类栏,1物品栏
std::shared_ptr<MenuText> getTitle() { return title_; }
void setForceItemType(int f);
void setSelectUser(bool s) { select_user_ = s; }
int getItemDetailType(Item* item);
Item* getAvailableItem(int i);
void geItemsByType(int item_type);
void checkCurrentItem();
virtual void draw() override { showItemProperty(current_item_); }
virtual void dealEvent(BP_Event& e) override;
void showItemProperty(Item* item);
void showOneProperty(int v, std::string format_str, int size, BP_Color c, int& x, int& y);
Item* current_item_ = nullptr;
std::vector<Item*> available_items_;
Item* getCurrentItem() { return current_item_; }
virtual void onPressedOK() override;
virtual void onPressedCancel() override;
};
| 23.696429 | 94 | 0.682743 | [
"vector"
] |
3c12683ea02cb03fb5fa5cd9155291bc86096b7b | 4,270 | h | C | cpp/jni/javet_types.h | gitter-badger/Javet | a1140c190b9e5c3c69cfeec5dd69aeb09983968b | [
"Apache-2.0"
] | 1 | 2021-12-11T00:13:09.000Z | 2021-12-11T00:13:09.000Z | cpp/jni/javet_types.h | webfolderio/Javet | a1140c190b9e5c3c69cfeec5dd69aeb09983968b | [
"Apache-2.0"
] | null | null | null | cpp/jni/javet_types.h | webfolderio/Javet | a1140c190b9e5c3c69cfeec5dd69aeb09983968b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 caoccao.com Sam Cao
* 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.
*/
#pragma once
#include "javet_v8.h"
// Scope
using V8ContextScope = v8::Context::Scope;
using V8HandleScope = v8::HandleScope;
using V8IsolateScope = v8::Isolate::Scope;
// Local
using V8LocalArray = v8::Local<v8::Array>;
using V8LocalBigInt = v8::Local<v8::BigInt>;
using V8LocalBoolean = v8::Local<v8::Boolean>;
using V8LocalContext = v8::Local<v8::Context>;
using V8LocalData = v8::Local<v8::Data>;
#ifndef ENABLE_NODE
using V8LocalFixedArray = v8::Local<v8::FixedArray>;
#endif
using V8LocalInteger = v8::Local<v8::Integer>;
using V8LocalMap = v8::Local<v8::Map>;
using V8LocalModule = v8::Local<v8::Module>;
using V8LocalNumber = v8::Local<v8::Number>;
using V8LocalObject = v8::Local<v8::Object>;
using V8LocalPrimitive = v8::Local<v8::Primitive>;
using V8LocalPrimitiveArray = v8::Local<v8::PrimitiveArray>;
using V8LocalPromise = v8::Local<v8::Promise>;
using V8LocalProxy = v8::Local<v8::Proxy>;
using V8LocalRegExp = v8::Local<v8::RegExp>;
using V8LocalScript = v8::Local<v8::Script>;
using V8LocalSet = v8::Local<v8::Set>;
using V8LocalString = v8::Local<v8::String>;
using V8LocalSymbol = v8::Local<v8::Symbol>;
using V8LocalValue = v8::Local<v8::Value>;
// Maybe Local
using V8MaybeLocalModule = v8::MaybeLocal<v8::Module>;
using V8MaybeLocalPromise = v8::MaybeLocal<v8::Promise>;
using V8MaybeLocalValue = v8::MaybeLocal<v8::Value>;
// Persistent
using V8PersistentArray = v8::Persistent<v8::Array>;
using V8PersistentContext = v8::Persistent<v8::Context>;
using V8PersistentData = v8::Persistent<v8::Data>;
using V8PersistentFunction = v8::Persistent<v8::Function>;
using V8PersistentMap = v8::Persistent<v8::Map>;
using V8PersistentModule = v8::Persistent<v8::Module>;
using V8PersistentObject = v8::Persistent<v8::Object>;
using V8PersistentPromise = v8::Persistent<v8::Promise>;
using V8PersistentProxy = v8::Persistent<v8::Proxy>;
using V8PersistentRegExp = v8::Persistent<v8::RegExp>;
using V8PersistentScript = v8::Persistent<v8::Script>;
using V8PersistentSet = v8::Persistent<v8::Set>;
using V8PersistentSymbol = v8::Persistent<v8::Symbol>;
using V8Platform = v8::Platform;
using V8StringUtf8Value = v8::String::Utf8Value;
using V8StringValue = v8::String::Value;
using V8TryCatch = v8::TryCatch;
// To Java
#define TO_JAVA_LONG(handle) reinterpret_cast<jlong>(handle)
#define TO_JAVA_OBJECT(handle) reinterpret_cast<jobject>(handle)
// To Native
#define TO_NATIVE_INT_64(handle) reinterpret_cast<int64_t>(handle)
// To V8 Persistent
#define TO_V8_PERSISTENT_ARRAY(handle) *reinterpret_cast<V8PersistentArray*>(handle)
#define TO_V8_PERSISTENT_DATA_POINTER(handle) reinterpret_cast<V8PersistentData*>(handle)
#define TO_V8_PERSISTENT_FUNCTION_POINTER(handle) reinterpret_cast<V8PersistentFunction*>(handle)
#define TO_V8_PERSISTENT_MAP(handle) *reinterpret_cast<V8PersistentMap*>(handle)
#define TO_V8_PERSISTENT_MODULE_POINTER(handle) reinterpret_cast<V8PersistentModule*>(handle)
#define TO_V8_PERSISTENT_OBJECT(handle) *reinterpret_cast<V8PersistentObject*>(handle)
#define TO_V8_PERSISTENT_OBJECT_POINTER(handle) reinterpret_cast<V8PersistentObject*>(handle)
#define TO_V8_PERSISTENT_PROMISE(handle) *reinterpret_cast<V8PersistentPromise*>(handle)
#define TO_V8_PERSISTENT_PROXY(handle) *reinterpret_cast<V8PersistentProxy*>(handle)
#define TO_V8_PERSISTENT_REG_EXP(handle) *reinterpret_cast<V8PersistentRegExp*>(handle)
#define TO_V8_PERSISTENT_SCRIPT_POINTER(handle) reinterpret_cast<V8PersistentScript*>(handle)
#define TO_V8_PERSISTENT_SET(handle) *reinterpret_cast<V8PersistentSet*>(handle)
#define TO_V8_PERSISTENT_SYMBOL(handle) *reinterpret_cast<V8PersistentSymbol*>(handle)
| 40.283019 | 97 | 0.781265 | [
"object"
] |
3c1e28172bdd9e7d2991ff2e5c9645c568b7caae | 7,282 | h | C | media/audio/win/audio_unified_win.h | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | 5 | 2018-03-10T13:08:42.000Z | 2021-07-26T15:02:11.000Z | media/audio/win/audio_unified_win.h | sanyaade-mobiledev/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 1 | 2015-07-21T08:02:01.000Z | 2015-07-21T08:02:01.000Z | media/audio/win/audio_unified_win.h | jianglong0156/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright (c) 2012 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 MEDIA_AUDIO_WIN_AUDIO_UNIFIED_WIN_H_
#define MEDIA_AUDIO_WIN_AUDIO_UNIFIED_WIN_H_
#include <Audioclient.h>
#include <MMDeviceAPI.h>
#include <string>
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "base/threading/platform_thread.h"
#include "base/threading/simple_thread.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_handle.h"
#include "media/audio/audio_io.h"
#include "media/audio/audio_parameters.h"
#include "media/base/media_export.h"
namespace media {
class AudioManagerWin;
// Implementation of AudioOutputStream for Windows using the WASAPI Core
// Audio interface where both capturing and rendering takes place on the
// same thread to enable audio I/O.
//
// Best performance is achieved by using a buffer size given by the static
// HardwareBufferSize() method. The user should also ensure that audio I/O
// is supported by calling HasUnifiedDefaultIO().
//
// Implementation notes:
//
// - Certain conditions must be fulfilled to support audio I/O:
// o Both capture and render side must use the same sample rate.
// o Both capture and render side must use the same channel count.
// o See HasUnifiedDefaultIO() for more details.
//
// TODO(henrika):
//
// - Add multi-channel support.
// - Add support for non-matching sample rates.
// - Add support for exclusive mode.
//
class MEDIA_EXPORT WASAPIUnifiedStream
: public AudioOutputStream,
public base::DelegateSimpleThread::Delegate {
public:
// The ctor takes all the usual parameters, plus |manager| which is the
// the audio manager who is creating this object.
WASAPIUnifiedStream(AudioManagerWin* manager,
const AudioParameters& params);
// The dtor is typically called by the AudioManager only and it is usually
// triggered by calling AudioOutputStream::Close().
virtual ~WASAPIUnifiedStream();
// Implementation of AudioOutputStream.
virtual bool Open() OVERRIDE;
virtual void Start(AudioSourceCallback* callback) OVERRIDE;
virtual void Stop() OVERRIDE;
virtual void Close() OVERRIDE;
virtual void SetVolume(double volume) OVERRIDE;
virtual void GetVolume(double* volume) OVERRIDE;
// Returns true if all conditions to support audio IO are fulfilled.
// Input and output sides of the Audio Engine must use the same native
// device period (requires e.g. identical sample rates) and have the same
// channel count.
static bool HasUnifiedDefaultIO();
// Retrieves the number of channels the audio engine uses for its internal
// processing/mixing of shared-mode streams for the default endpoint device
// and in the given direction.
static int HardwareChannelCount(EDataFlow data_flow);
// Retrieves the sample rate the audio engine uses for its internal
// processing/mixing of shared-mode streams for the default endpoint device
// and in the given direction.
static int HardwareSampleRate(EDataFlow data_flow);
// Retrieves the preferred buffer size for the default endpoint device and
// in the given direction. The recommended size is given by the mixing
// sample rate and the native device period for the audio device.
// Unit is in number of audio frames.
// Examples:
// fs = 96000 Hz => 960
// fs = 48000 Hz => 480
// fs = 44100 Hz => 441 or 448 (depends on the audio hardware)
static int HardwareBufferSize(EDataFlow data_flow);
bool started() const {
return audio_io_thread_.get() != NULL;
}
private:
// DelegateSimpleThread::Delegate implementation.
virtual void Run() OVERRIDE;
// Issues the OnError() callback to the |source_|.
void HandleError(HRESULT err);
// Stops and joins the audio thread in case of an error.
void StopAndJoinThread(HRESULT err);
// Helper methods which uses an IAudioClient to create and setup
// IAudio[Render|Capture]Clients.
base::win::ScopedComPtr<IAudioRenderClient> CreateAudioRenderClient(
IAudioClient* audio_client);
base::win::ScopedComPtr<IAudioCaptureClient> CreateAudioCaptureClient(
IAudioClient* audio_client);
// Converts unique endpoint ID to user-friendly device name.
std::string GetDeviceName(LPCWSTR device_id) const;
// Returns the number of channels the audio engine uses for its internal
// processing/mixing of shared-mode streams for the default endpoint device.
int endpoint_channel_count() { return format_.Format.nChannels; }
// Contains the thread ID of the creating thread.
base::PlatformThreadId creating_thread_id_;
// Our creator, the audio manager needs to be notified when we close.
AudioManagerWin* manager_;
// Rendering and capturing is driven by this thread (no message loop).
// All OnMoreIOData() callbacks will be called from this thread.
scoped_ptr<base::DelegateSimpleThread> audio_io_thread_;
// Contains the desired audio format which is set up at construction.
// Extended PCM waveform format structure based on WAVEFORMATEXTENSIBLE.
// Use this for multiple channel and hi-resolution PCM data.
WAVEFORMATPCMEX format_;
// True when successfully opened.
bool opened_;
// Size in bytes of each audio frame (4 bytes for 16-bit stereo PCM).
size_t frame_size_;
// Size in audio frames of each audio packet where an audio packet
// is defined as the block of data which the source is expected to deliver
// in each OnMoreIOData() callback.
size_t packet_size_frames_;
// Length of the audio endpoint buffer.
size_t endpoint_render_buffer_size_frames_;
size_t endpoint_capture_buffer_size_frames_;
// Pointer to the client that will deliver audio samples to be played out.
AudioSourceCallback* source_;
// IMMDevice interfaces which represents audio endpoint devices.
base::win::ScopedComPtr<IMMDevice> endpoint_render_device_;
base::win::ScopedComPtr<IMMDevice> endpoint_capture_device_;
// IAudioClient interfaces which enables a client to create and initialize
// an audio stream between an audio application and the audio engine.
base::win::ScopedComPtr<IAudioClient> audio_output_client_;
base::win::ScopedComPtr<IAudioClient> audio_input_client_;
// IAudioRenderClient interfaces enables a client to write output
// data to a rendering endpoint buffer.
base::win::ScopedComPtr<IAudioRenderClient> audio_render_client_;
// IAudioCaptureClient interfaces enables a client to read input
// data from a capturing endpoint buffer.
base::win::ScopedComPtr<IAudioCaptureClient> audio_capture_client_;
// The audio engine will signal this event each time a buffer has been
// recorded.
base::win::ScopedHandle capture_event_;
// This event will be signaled when streaming shall stop.
base::win::ScopedHandle stop_streaming_event_;
// Container for retrieving data from AudioSourceCallback::OnMoreIOData().
scoped_ptr<AudioBus> render_bus_;
// Container for sending data to AudioSourceCallback::OnMoreIOData().
scoped_ptr<AudioBus> capture_bus_;
DISALLOW_COPY_AND_ASSIGN(WASAPIUnifiedStream);
};
} // namespace media
#endif // MEDIA_AUDIO_WIN_AUDIO_UNIFIED_WIN_H_
| 37.73057 | 78 | 0.76078 | [
"render",
"object"
] |
3c222f09079f9bf87e6873771997862223584bb7 | 1,520 | h | C | source/Classes/Services/ApigeeQueue.h | RobertWalsh/apigee-ios-sdk | f23ca1fa4eed88de2f5c260a47cefe7f57701e06 | [
"Apache-2.0"
] | null | null | null | source/Classes/Services/ApigeeQueue.h | RobertWalsh/apigee-ios-sdk | f23ca1fa4eed88de2f5c260a47cefe7f57701e06 | [
"Apache-2.0"
] | null | null | null | source/Classes/Services/ApigeeQueue.h | RobertWalsh/apigee-ios-sdk | f23ca1fa4eed88de2f5c260a47cefe7f57701e06 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014 Apigee Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
/*!
@abstract The ApigeeQueue class implements the functionality of a standard
queue.
*/
@interface ApigeeQueue : NSObject
/*!
@abstract Initializes the queue and reserves the specified capacity.
@param capacity The desired capacity for the queue.
*/
- (id)initWithCapacity:(NSUInteger)capacity;
/*!
@abstract Retrieves object at the front of the queue.
@return The object at the front of the queue, or nil if there are none.
*/
- (id) dequeue;
/*!
@abstract Retrieves and removes all items currently in the queue.
@return Array of all items that were in the queue at the time call was made.
*/
- (NSArray *) dequeueAll;
/*!
@abstract Adds a new object to the back of the queue.
@param The new object to be added to the queue.
*/
- (void) enqueue:(id) obj;
/*!
@abstract Discards all objects that are currently in the queue.
*/
- (void) removeAllObjects;
@end
| 27.636364 | 77 | 0.730263 | [
"object"
] |
3c2403d4a270c7af9b8ee4bf2057ba52c9e6d9e8 | 1,607 | h | C | test_37/pch.h | Daspien27/TemplateInvestigation | af2280fc57337f5f3fb9adddae8d8798ed3ffa16 | [
"MIT"
] | null | null | null | test_37/pch.h | Daspien27/TemplateInvestigation | af2280fc57337f5f3fb9adddae8d8798ed3ffa16 | [
"MIT"
] | null | null | null | test_37/pch.h | Daspien27/TemplateInvestigation | af2280fc57337f5f3fb9adddae8d8798ed3ffa16 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
struct A_1 {};
struct A_2 {};
struct A_3 {};
struct A_4 {};
struct A_5 {};
struct A_6 {};
struct A_7 {};
struct A_8 {};
struct A_9 {};
struct A_10 {};
struct A_11 {};
struct A_12 {};
struct A_13 {};
struct A_14 {};
struct A_15 {};
struct A_16 {};
struct A_17 {};
struct A_18 {};
struct A_19 {};
struct A_20 {};
struct A_21 {};
struct A_22 {};
struct A_23 {};
struct A_24 {};
struct A_25 {};
struct A_26 {};
struct A_27 {};
struct A_28 {};
struct A_29 {};
struct A_30 {};
struct A_31 {};
struct A_32 {};
struct A_33 {};
struct A_34 {};
struct A_35 {};
struct A_36 {};
struct A_37 {};
struct A_38 {};
struct A_39 {};
struct A_40 {};
struct A_41 {};
struct A_42 {};
struct A_43 {};
struct A_44 {};
struct A_45 {};
struct A_46 {};
struct A_47 {};
struct A_48 {};
struct A_49 {};
struct A_50 {};
struct A_51 {};
struct A_52 {};
struct A_53 {};
struct A_54 {};
struct A_55 {};
struct A_56 {};
struct A_57 {};
struct A_58 {};
struct A_59 {};
struct A_60 {};
struct A_61 {};
struct A_62 {};
struct A_63 {};
struct A_64 {};
struct A_65 {};
struct A_66 {};
struct A_67 {};
struct A_68 {};
struct A_69 {};
struct A_70 {};
struct A_71 {};
struct A_72 {};
struct A_73 {};
struct A_74 {};
struct A_75 {};
struct A_76 {};
struct A_77 {};
struct A_78 {};
struct A_79 {};
struct A_80 {};
struct A_81 {};
struct A_82 {};
struct A_83 {};
struct A_84 {};
struct A_85 {};
struct A_86 {};
struct A_87 {};
struct A_88 {};
struct A_89 {};
struct A_90 {};
struct A_91 {};
struct A_92 {};
struct A_93 {};
struct A_94 {};
struct A_95 {};
struct A_96 {};
struct A_97 {};
struct A_98 {};
struct A_99 {}; | 15.601942 | 17 | 0.624767 | [
"vector"
] |
3c3c0d53af666da5d0c33584c7f32216ab67f1cd | 12,455 | h | C | ios/RayGame.framework/Versions/A/Headers/UIImage+RGUI.h | RayStream/RayGame | e4a14cade82cf2a7b115419421491c8c2f5fe522 | [
"MIT"
] | null | null | null | ios/RayGame.framework/Versions/A/Headers/UIImage+RGUI.h | RayStream/RayGame | e4a14cade82cf2a7b115419421491c8c2f5fe522 | [
"MIT"
] | null | null | null | ios/RayGame.framework/Versions/A/Headers/UIImage+RGUI.h | RayStream/RayGame | e4a14cade82cf2a7b115419421491c8c2f5fe522 | [
"MIT"
] | null | null | null | /**
* Tencent is pleased to support the open source community by making RGUI_iOS available.
* Copyright (C) 2016-2020 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*/
//
// UIImage+RGUI.h
// rgui
//
// Created by RGUI Team on 15/7/20.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#define CGContextInspectSize(size) [RGUIHelper inspectContextSize:size]
#ifdef DEBUG
#define CGContextInspectContext(context) [RGUIHelper inspectContextIfInvalidatedInDebugMode:context]
#else
#define CGContextInspectContext(context) if(![RGUIHelper inspectContextIfInvalidatedInReleaseMode:context]){return nil;}
#endif
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, RGUIImageShape) {
RGUIImageShapeOval, // 椭圆
RGUIImageShapeTriangle, // 尖头向上的三角形
RGUIImageShapeDisclosureIndicator, // 列表 cell 右边的箭头
RGUIImageShapeCheckmark, // 列表 cell 右边的checkmark
RGUIImageShapeDetailButtonImage, // 列表 cell 右边的 i 按钮图片
RGUIImageShapeNavBack, // 返回按钮的箭头
RGUIImageShapeNavClose // 导航栏的关闭icon
};
typedef NS_OPTIONS(NSInteger, RGUIImageBorderPosition) {
RGUIImageBorderPositionAll = 0,
RGUIImageBorderPositionTop = 1 << 0,
RGUIImageBorderPositionLeft = 1 << 1,
RGUIImageBorderPositionBottom = 1 << 2,
RGUIImageBorderPositionRight = 1 << 3,
};
typedef NS_ENUM(NSInteger, RGUIImageResizingMode) {
RGUIImageResizingModeScaleToFill = 0, // 将图片缩放到给定的大小,不考虑宽高比例
RGUIImageResizingModeScaleAspectFit = 10, // 默认的缩放方式,将图片保持宽高比例不变的情况下缩放到不超过给定的大小(但缩放后的大小不一定与给定大小相等),不会产生空白也不会产生裁剪
RGUIImageResizingModeScaleAspectFill = 20, // 将图片保持宽高比例不变的情况下缩放到不超过给定的大小(但缩放后的大小不一定与给定大小相等),若有内容超出则会被裁剪。若裁剪则上下居中裁剪。
RGUIImageResizingModeScaleAspectFillTop, // 将图片保持宽高比例不变的情况下缩放到不超过给定的大小(但缩放后的大小不一定与给定大小相等),若有内容超出则会被裁剪。若裁剪则水平居中、垂直居上裁剪。
RGUIImageResizingModeScaleAspectFillBottom // 将图片保持宽高比例不变的情况下缩放到不超过给定的大小(但缩放后的大小不一定与给定大小相等),若有内容超出则会被裁剪。若裁剪则水平居中、垂直居下裁剪。
};
@interface UIImage (RGUI)
/**
用于绘制一张图并以 UIImage 的形式返回
@param size 要绘制的图片的 size,宽或高均不能为 0
@param opaque 图片是否不透明,YES 表示不透明,NO 表示半透明
@param scale 图片的倍数,0 表示取当前屏幕的倍数
@param actionBlock 实际的图片绘制操作,在这里只管绘制就行,不用手动生成 image
@return 返回绘制完的图片
*/
+ (nullable UIImage *)rgui_imageWithSize:(CGSize)size opaque:(BOOL)opaque scale:(CGFloat)scale actions:(void (^)(CGContextRef contextRef))actionBlock;
/// 当前图片是否是可拉伸/平铺的,也即通过 resizableImageWithCapInsets: 处理过的图片
@property(nonatomic, assign, readonly) BOOL rgui_resizable;
/// 获取当前图片的像素大小,如果是多倍图,会被放大到一倍来算
@property(nonatomic, assign, readonly) CGSize rgui_sizeInPixel;
/**
* 判断一张图是否不存在 alpha 通道,注意 “不存在 alpha 通道” 不等价于 “不透明”。一张不透明的图有可能是存在 alpha 通道但 alpha 值为 1。
*/
- (BOOL)rgui_opaque;
/**
* 获取当前图片的均色,原理是将图片绘制到1px*1px的矩形内,再从当前区域取色,得到图片的均色。
* @link http://www.bobbygeorgescu.com/2011/08/finding-average-color-of-uiimage/ @/link
*
* @return 代表图片平均颜色的UIColor对象
*/
- (UIColor *)rgui_averageColor;
/**
* 置灰当前图片
*
* @return 已经置灰的图片
*/
- (nullable UIImage *)rgui_grayImage;
/**
* 设置一张图片的透明度
*
* @param alpha 要用于渲染透明度
*
* @return 设置了透明度之后的图片
*/
- (nullable UIImage *)rgui_imageWithAlpha:(CGFloat)alpha;
/**
* 保持当前图片的形状不变,使用指定的颜色去重新渲染它,生成一张新图片并返回
*
* @param tintColor 要用于渲染的新颜色
*
* @return 与当前图片形状一致但颜色与参数tintColor相同的新图片
*/
- (nullable UIImage *)rgui_imageWithTintColor:(nullable UIColor *)tintColor;
/**
* 以 CIColorBlendMode 的模式为当前图片叠加一个颜色,生成一张新图片并返回,在叠加过程中会保留图片内的纹理。
*
* @param blendColor 要叠加的颜色
*
* @return 基于当前图片纹理保持不变的情况下颜色变为指定的叠加颜色的新图片
*
* @warning 这个方法可能比较慢,会卡住主线程,建议异步使用
*/
- (nullable UIImage *)rgui_imageWithBlendColor:(nullable UIColor *)blendColor;
/**
* 在当前图片的基础上叠加一张图片,并指定绘制叠加图片的起始位置
*
* 叠加上去的图片将保持原图片的大小不变,不被压缩、拉伸
*
* @param image 要叠加的图片
* @param point 所叠加图片的绘制的起始位置
*
* @return 返回一张与原图大小一致的图片,所叠加的图片若超出原图大小,则超出部分被截掉
*/
- (nullable UIImage *)rgui_imageWithImageAbove:(UIImage *)image atPoint:(CGPoint)point;
/**
* 在当前图片的上下左右增加一些空白(不支持负值),通常用于调节NSAttributedString里的图片与文字的间距
* @param extension 要拓展的大小
* @return 拓展后的图片
*/
- (nullable UIImage *)rgui_imageWithSpacingExtensionInsets:(UIEdgeInsets)extension;
/**
* 切割出在指定位置中的图片
*
* @param rect 要切割的rect
*
* @return 切割后的新图片
*/
- (nullable UIImage *)rgui_imageWithClippedRect:(CGRect)rect;
/**
* 切割出在指定圆角的图片
*
* @param cornerRadius 要切割的圆角值
*
* @return 切割后的新图片
*/
- (nullable UIImage *)rgui_imageWithClippedCornerRadius:(CGFloat)cornerRadius;
/**
* 同上,可以设置 scale
*/
- (nullable UIImage *)rgui_imageWithClippedCornerRadius:(CGFloat)cornerRadius scale:(CGFloat)scale;
/**
* 将原图以 RGUIImageResizingModeScaleAspectFit 的策略缩放,使其缩放后的大小不超过指定的大小,并返回缩放后的图片。缩放后的图片的倍数保持与原图一致。
* @param size 在这个约束的 size 内进行缩放后的大小,处理后返回的图片的 size 会根据 resizingMode 不同而不同,但必定不会超过 size。
*
* @return 处理完的图片
* @see rgui_imageResizedInLimitedSize:resizingMode:scale:
*/
- (nullable UIImage *)rgui_imageResizedInLimitedSize:(CGSize)size;
/**
* 将原图按指定的 RGUIImageResizingMode 缩放,使其缩放后的大小不超过指定的大小,并返回缩放后的图片,缩放后的图片的倍数保持与原图一致。
* @param size 在这个约束的 size 内进行缩放后的大小,处理后返回的图片的 size 会根据 resizingMode 不同而不同,但必定不会超过 size。
* @param resizingMode 希望使用的缩放模式
*
* @return 处理完的图片
* @see rgui_imageResizedInLimitedSize:resizingMode:scale:
*/
- (nullable UIImage *)rgui_imageResizedInLimitedSize:(CGSize)size resizingMode:(RGUIImageResizingMode)resizingMode;
/**
* 将原图按指定的 RGUIImageResizingMode 缩放,使其缩放后的大小不超过指定的大小,并返回缩放后的图片。
* @param size 在这个约束的 size 内进行缩放后的大小,处理后返回的图片的 size 会根据 resizingMode 不同而不同,但必定不会超过 size。
* @param resizingMode 希望使用的缩放模式
* @param scale 用于指定缩放后的图片的倍数
*
* @return 处理完的图片
*/
- (nullable UIImage *)rgui_imageResizedInLimitedSize:(CGSize)size resizingMode:(RGUIImageResizingMode)resizingMode scale:(CGFloat)scale;
/**
* 将原图进行旋转,只能选择上下左右四个方向
*
* @param direction 旋转的方向
*
* @return 处理完的图片
*/
- (nullable UIImage *)rgui_imageWithOrientation:(UIImageOrientation)direction;
/**
* 为图片加上一个border,border的路径为path
*
* @param borderColor border的颜色
* @param path border的路径
*
* @return 带border的UIImage
* @warning 注意通过`path.lineWidth`设置边框大小,同时注意路径要考虑像素对齐(`path.lineWidth / 2.0`)
*/
- (nullable UIImage *)rgui_imageWithBorderColor:(nullable UIColor *)borderColor path:(nullable UIBezierPath *)path;
/**
* 为图片加上一个border,border的路径为borderColor、cornerRadius和borderWidth所创建的path
*
* @param borderColor border的颜色
* @param borderWidth border的宽度
* @param cornerRadius border的圆角
*
* @param dashedLengths 一个CGFloat的数组,例如`CGFloat dashedLengths[] = {2, 4}`。如果不需要虚线,则传0即可
*
* @return 带border的UIImage
*/
- (nullable UIImage *)rgui_imageWithBorderColor:(nullable UIColor *)borderColor borderWidth:(CGFloat)borderWidth cornerRadius:(CGFloat)cornerRadius dashedLengths:(nullable const CGFloat *)dashedLengths;
- (nullable UIImage *)rgui_imageWithBorderColor:(nullable UIColor *)borderColor borderWidth:(CGFloat)borderWidth cornerRadius:(CGFloat)cornerRadius;
/**
* 为图片加上一个border(可以是任意一条边,也可以是多条组合;只能创建矩形的border,不能添加圆角)
*
* @param borderColor border的颜色
* @param borderWidth border的宽度
* @param borderPosition border的位置
*
* @return 带border的UIImage
*/
- (nullable UIImage *)rgui_imageWithBorderColor:(nullable UIColor *)borderColor borderWidth:(CGFloat)borderWidth borderPosition:(RGUIImageBorderPosition)borderPosition;
/**
* 返回一个被mask的图片
*
* @param maskImage mask图片
* @param usingMaskImageMode 是否使用“mask image”的方式,若为 YES,则黑色部分显示,白色部分消失,透明部分显示,其他颜色会按照颜色的灰色度对图片做透明处理。若为 NO,则 maskImage 要求必须为灰度颜色空间的图片(黑白图),白色部分显示,黑色部分消失,透明部分消失,其他灰色度对图片做透明处理。
*
* @return 被mask的图片
*/
- (nullable UIImage *)rgui_imageWithMaskImage:(UIImage *)maskImage usingMaskImageMode:(BOOL)usingMaskImageMode;
/**
将 data 转换成 animated UIImage(如果非 animated 则转换成普通 UIImage),image 倍数为 1(与系统的 [UIImage imageWithData:] 接口一致)
@param data 图片文件的 data
@return 转换成的 UIImage
*/
+ (nullable UIImage *)rgui_animatedImageWithData:(NSData *)data;
/**
将 data 转换成 animated UIImage(如果非 animated 则转换成普通 UIImage)
@param data 图片文件的 data
@param scale 图片的倍数,0 表示获取当前设备的屏幕倍数
@return 转换成的 UIImage
@see http://www.jianshu.com/p/767af9c690a3
@see https://github.com/rs/SDWebImage
*/
+ (nullable UIImage *)rgui_animatedImageWithData:(NSData *)data scale:(CGFloat)scale;
/**
在 mainBundle 里找到对应名字的图片, 注意图片 scale 为 1,与系统的 [UIImage imageWithData:] 接口一致,若需要修改倍数,请使用 -rgui_animatedImageNamed:scale:
@param name 图片名,可指定后缀,若不写后缀,默认为“gif”。不写后缀的情况下会先找“gif”后缀的图片,不存在再找无后缀的文件,仍不存在则返回 nil
@return 转换成的 UIImage
*/
+ (nullable UIImage *)rgui_animatedImageNamed:(NSString *)name;
/**
在 mainBundle 里找到对应名字的图片
@param name 图片名,可指定后缀,若不写后缀,默认为“gif”。不写后缀的情况下会先找“gif”后缀的图片,不存在再找无后缀的文件,仍不存在则返回 nil
@param scale 图片的倍数,0 表示获取当前设备的屏幕倍数
@return 转换成的 UIImage
*/
+ (nullable UIImage *)rgui_animatedImageNamed:(NSString *)name scale:(CGFloat)scale;
/**
* 创建一个size为(4, 4)的纯色的UIImage
*
* @param color 图片的颜色
*
* @return 纯色的UIImage
*/
+ (nullable UIImage *)rgui_imageWithColor:(nullable UIColor *)color;
/**
* 创建一个纯色的UIImage
*
* @param color 图片的颜色
* @param size 图片的大小
* @param cornerRadius 图片的圆角
*
* @return 纯色的UIImage
*/
+ (nullable UIImage *)rgui_imageWithColor:(nullable UIColor *)color size:(CGSize)size cornerRadius:(CGFloat)cornerRadius;
/**
* 创建一个纯色的UIImage,支持为四个角设置不同的圆角
* @param color 图片的颜色
* @param size 图片的大小
* @param cornerRadius 四个角的圆角值的数组,长度必须为4,顺序分别为[左上角、左下角、右下角、右上角]
*/
+ (nullable UIImage *)rgui_imageWithColor:(nullable UIColor *)color size:(CGSize)size cornerRadiusArray:(nullable NSArray<NSNumber *> *)cornerRadius;
/**
* 创建一个带边框路径,没有背景色的路径图片,border的路径为path
*
* @param strokeColor border的颜色
* @param path border的路径
* @param addClip 是否要调path的addClip
*
* @return 带border的UIImage
*/
+ (nullable UIImage *)rgui_imageWithStrokeColor:(nullable UIColor *)strokeColor size:(CGSize)size path:(nullable UIBezierPath *)path addClip:(BOOL)addClip;
/**
* 创建一个带边框路径,没有背景色的路径图片,border的路径为strokeColor、cornerRadius和lineWidth所创建的path
*
* @param strokeColor border的颜色
* @param lineWidth border的宽度
* @param cornerRadius border的圆角
*
* @return 带border的UIImage
*/
+ (nullable UIImage *)rgui_imageWithStrokeColor:(nullable UIColor *)strokeColor size:(CGSize)size lineWidth:(CGFloat)lineWidth cornerRadius:(CGFloat)cornerRadius;
/**
* 创建一个带边框路径,没有背景色的路径图片(可以是任意一条边,也可以是多条组合;只能创建矩形的border,不能添加圆角)
*
* @param strokeColor 路径的颜色
* @param size 图片的大小
* @param lineWidth 路径的大小
* @param borderPosition 图片的路径位置,上左下右
*
* @return 带路径,没有背景色的UIImage
*/
+ (nullable UIImage *)rgui_imageWithStrokeColor:(nullable UIColor *)strokeColor size:(CGSize)size lineWidth:(CGFloat)lineWidth borderPosition:(RGUIImageBorderPosition)borderPosition;
/**
* 创建一个指定大小和颜色的形状图片
* @param shape 图片形状
* @param size 图片大小
* @param tintColor 图片颜色
*/
+ (nullable UIImage *)rgui_imageWithShape:(RGUIImageShape)shape size:(CGSize)size tintColor:(nullable UIColor *)tintColor;
/**
* 创建一个指定大小和颜色的形状图片
* @param shape 图片形状
* @param size 图片大小
* @param lineWidth 路径大小,不会影响最终size
* @param tintColor 图片颜色
*/
+ (nullable UIImage *)rgui_imageWithShape:(RGUIImageShape)shape size:(CGSize)size lineWidth:(CGFloat)lineWidth tintColor:(nullable UIColor *)tintColor;
/**
* 将文字渲染成图片,最终图片和文字一样大
*/
+ (nullable UIImage *)rgui_imageWithAttributedString:(NSAttributedString *)attributedString;
/**
对传进来的 `UIView` 截图,生成一个 `UIImage` 并返回。注意这里使用的是 view.layer 来渲染图片内容。
@param view 要截图的 `UIView`
@return `UIView` 的截图
@warning UIView 的 transform 并不会在截图里生效
*/
+ (nullable UIImage *)rgui_imageWithView:(UIView *)view;
/**
对传进来的 `UIView` 截图,生成一个 `UIImage` 并返回。注意这里使用的是 iOS 7的系统截图接口。
@param view 要截图的 `UIView`
@param afterUpdates 是否要在界面更新完成后才截图
@return `UIView` 的截图
@warning UIView 的 transform 并不会在截图里生效
*/
+ (nullable UIImage *)rgui_imageWithView:(UIView *)view afterScreenUpdates:(BOOL)afterUpdates;
@end
NS_ASSUME_NONNULL_END
| 31.372796 | 308 | 0.744039 | [
"shape",
"transform"
] |
3c429af756002180e98ceb769d0b7e2c7fb035f2 | 11,591 | h | C | kernels/ZendEngine2/object.h | hlooalklampc/tss | 23856e1e8244a89ac1bc30ba56b417a4a1c1687f | [
"MIT"
] | 3 | 2016-07-25T09:17:38.000Z | 2020-11-24T09:52:24.000Z | kernels/ZendEngine2/object.h | hlooalklampc/tss | 23856e1e8244a89ac1bc30ba56b417a4a1c1687f | [
"MIT"
] | null | null | null | kernels/ZendEngine2/object.h | hlooalklampc/tss | 23856e1e8244a89ac1bc30ba56b417a4a1c1687f | [
"MIT"
] | 1 | 2018-03-27T06:29:09.000Z | 2018-03-27T06:29:09.000Z |
/*
+------------------------------------------------------------------------+
| Zephir Language |
+------------------------------------------------------------------------+
| Copyright (c) 2011-2016 Zephir Team (http://www.zephir-lang.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file docs/LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to license@zephir-lang.com so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Andres Gutierrez <andres@zephir-lang.com> |
| Eduar Carvajal <eduar@zephir-lang.com> |
| Vladimir Kolesnikov <vladimir@extrememember.com> |
+------------------------------------------------------------------------+
*/
#ifndef ZEPHIR_KERNEL_OBJECT_H
#define ZEPHIR_KERNEL_OBJECT_H
#include <php.h>
#include <Zend/zend.h>
#include "kernel/globals.h"
#include "kernel/main.h"
/** Class Retrieving/Checking */
int zephir_class_exists(const zval *class_name, int autoload TSRMLS_DC);
int zephir_interface_exists(const zval *interface_name, int autoload TSRMLS_DC);
void zephir_get_class(zval *result, zval *object, int lower TSRMLS_DC);
void zephir_get_class_ns(zval *result, zval *object, int lower TSRMLS_DC);
void zephir_get_ns_class(zval *result, zval *object, int lower TSRMLS_DC);
void zephir_get_called_class(zval *return_value TSRMLS_DC);
zend_class_entry *zephir_fetch_class(const zval *class_name TSRMLS_DC);
zend_class_entry* zephir_fetch_self_class(TSRMLS_D);
zend_class_entry* zephir_fetch_parent_class(TSRMLS_D);
zend_class_entry* zephir_fetch_static_class(TSRMLS_D);
#define ZEPHIR_GET_CLASS_CONSTANT(return_value, ce, const_name) \
do { \
if (FAILURE == zephir_get_class_constant(return_value, ce, const_name, strlen(const_name)+1 TSRMLS_CC)) { \
ZEPHIR_MM_RESTORE(); \
return; \
} \
} while (0)
/** Class constants */
int zephir_get_class_constant(zval *return_value, zend_class_entry *ce, char *constant_name, unsigned int constant_length TSRMLS_DC);
/** Cloning/Instance of*/
int zephir_clone(zval *destiny, zval *obj TSRMLS_DC);
int zephir_instance_of(zval *result, const zval *object, const zend_class_entry *ce TSRMLS_DC);
int zephir_is_instance_of(zval *object, const char *class_name, unsigned int class_length TSRMLS_DC);
int zephir_instance_of_ev(const zval *object, const zend_class_entry *ce TSRMLS_DC);
int zephir_zval_is_traversable(zval *object TSRMLS_DC);
/** Method exists */
int zephir_method_exists(const zval *object, const zval *method_name TSRMLS_DC);
int zephir_method_exists_ex(const zval *object, const char *method_name, unsigned int method_len TSRMLS_DC);
int zephir_method_quick_exists_ex(const zval *object, const char *method_name, unsigned int method_len, unsigned long hash TSRMLS_DC);
/** Isset properties */
int zephir_isset_property(zval *object, const char *property_name, unsigned int property_length TSRMLS_DC);
int zephir_isset_property_quick(zval *object, const char *property_name, unsigned int property_length, unsigned long hash TSRMLS_DC);
int zephir_isset_property_zval(zval *object, const zval *property TSRMLS_DC);
/** Reading properties */
zval* zephir_fetch_property_this_quick(zval *object, const char *property_name, zend_uint property_length, ulong key, int silent TSRMLS_DC);
int zephir_read_property(zval **result, zval *object, const char *property_name, zend_uint property_length, int silent TSRMLS_DC);
int zephir_read_property_zval(zval **result, zval *object, zval *property, int silent TSRMLS_DC);
int zephir_return_property(zval *return_value, zval **return_value_ptr, zval *object, char *property_name, unsigned int property_length TSRMLS_DC);
int zephir_return_property_quick(zval *return_value, zval **return_value_ptr, zval *object, char *property_name, unsigned int property_length, unsigned long key TSRMLS_DC);
int zephir_fetch_property(zval **result, zval *object, const char *property_name, zend_uint property_length, int silent TSRMLS_DC);
int zephir_fetch_property_zval(zval **result, zval *object, zval *property, int silent TSRMLS_DC);
/** Updating properties */
int zephir_update_property_this(zval *object, char *property_name, unsigned int property_length, zval *value TSRMLS_DC);
int zephir_update_property_long(zval *obj, char *property_name, unsigned int property_length, long value TSRMLS_DC);
int zephir_update_property_string(zval *object, char *property_name, unsigned int property_length, char *str, unsigned int str_length TSRMLS_DC);
int zephir_update_property_bool(zval *obj, char *property_name, unsigned int property_length, int value TSRMLS_DC);
int zephir_update_property_null(zval *obj, char *property_name, unsigned int property_length TSRMLS_DC);
int zephir_update_property_zval(zval *obj, const char *property_name, unsigned int property_length, zval *value TSRMLS_DC);
int zephir_update_property_zval_zval(zval *obj, zval *property, zval *value TSRMLS_DC);
int zephir_update_property_empty_array(zend_class_entry *ce, zval *object, char *property, unsigned int property_length TSRMLS_DC);
/** Updating array properties */
int zephir_update_property_array(zval *object, const char *property, zend_uint property_length, const zval *index, zval *value TSRMLS_DC);
int zephir_update_property_array_string(zval *object, char *property, unsigned int property_length, char *index, unsigned int index_length, zval *value TSRMLS_DC);
int zephir_update_property_array_append(zval *object, char *property, unsigned int property_length, zval *value TSRMLS_DC);
int zephir_update_property_array_multi(zval *object, const char *property, zend_uint property_length, zval **value TSRMLS_DC, const char *types, int types_length, int types_count, ...);
/** Increment/Decrement properties */
int zephir_property_incr(zval *object, char *property_name, unsigned int property_length TSRMLS_DC);
int zephir_property_decr(zval *object, char *property_name, unsigned int property_length TSRMLS_DC);
/** Unset properties */
int zephir_unset_property(zval* object, const char* name TSRMLS_DC);
int zephir_unset_property_array(zval *object, char *property, unsigned int property_length, zval *index TSRMLS_DC);
/** Static properties */
int zephir_read_static_property(zval **result, const char *class_name, unsigned int class_length, char *property_name, unsigned int property_length TSRMLS_DC);
int zephir_update_static_property_ce(zend_class_entry *ce, const char *name, int len, zval **value TSRMLS_DC);
int zephir_update_static_property_ce_cache(zend_class_entry *ce, const char *name, int len, zval **value, zend_property_info **property_info TSRMLS_DC);
int zephir_update_static_property(const char *class_name, unsigned int class_length, char *name, unsigned int name_length, zval **value TSRMLS_DC);
int zephir_read_static_property_ce(zval **result, zend_class_entry *ce, const char *property, int len TSRMLS_DC);
int zephir_read_class_property(zval **result, int type, const char *property, int len TSRMLS_DC);
zval* zephir_fetch_static_property_ce(zend_class_entry *ce, const char *property, int len TSRMLS_DC);
int zephir_update_static_property_array_multi_ce(zend_class_entry *ce, const char *property, zend_uint property_length, zval **value TSRMLS_DC, const char *types, int types_length, int types_count, ...);
/** Create instances */
int zephir_create_instance(zval *return_value, const zval *class_name TSRMLS_DC);
int zephir_create_instance_params(zval *return_value, const zval *class_name, zval *params TSRMLS_DC);
/** Create closures */
int zephir_create_closure_ex(zval *return_value, zval *this_ptr, zend_class_entry *ce, const char *method_name, zend_uint method_length TSRMLS_DC);
/**
* Reads a property from this_ptr (with pre-calculated key)
* Variables must be defined in the class definition. This function ignores magic methods or dynamic properties
*/
ZEPHIR_ATTR_NONNULL static inline int zephir_read_property_this_quick(zval **result, zval *object, const char *property_name, zend_uint property_length, ulong key, int silent TSRMLS_DC)
{
zval *tmp = zephir_fetch_property_this_quick(object, property_name, property_length, key, silent TSRMLS_CC);
if (EXPECTED(tmp != NULL)) {
*result = tmp;
Z_ADDREF_PP(result);
return SUCCESS;
}
ALLOC_INIT_ZVAL(*result);
return FAILURE;
}
/**
* Reads a property from this_ptr
* Variables must be defined in the class definition. This function ignores magic methods or dynamic properties
*/
ZEPHIR_ATTR_NONNULL static inline int zephir_read_property_this(zval **result, zval *object, const char *property_name, zend_uint property_length, int silent TSRMLS_DC)
{
#ifdef __GNUC__
if (__builtin_constant_p(property_name) && __builtin_constant_p(property_length)) {
return zephir_read_property_this_quick(result, object, property_name, property_length, zend_inline_hash_func(property_name, property_length + 1), silent TSRMLS_CC);
}
#endif
return zephir_read_property_this_quick(result, object, property_name, property_length, zend_hash_func(property_name, property_length + 1), silent TSRMLS_CC);
}
ZEPHIR_ATTR_NONNULL static inline zval* zephir_fetch_nproperty_this_quick(zval *object, const char *property_name, zend_uint property_length, ulong key, int silent TSRMLS_DC)
{
#ifdef __GNUC__
if (__builtin_constant_p(property_name) && __builtin_constant_p(property_length)) {
zval *result = zephir_fetch_property_this_quick(object, property_name, property_length, key, silent TSRMLS_CC);
return result ? result : EG(uninitialized_zval_ptr);
}
#endif
zval *result = zephir_fetch_property_this_quick(object, property_name, property_length, key, silent TSRMLS_CC);
return result ? result : EG(uninitialized_zval_ptr);
}
ZEPHIR_ATTR_NONNULL static inline zval* zephir_fetch_nproperty_this(zval *object, const char *property_name, zend_uint property_length, int silent TSRMLS_DC)
{
#ifdef __GNUC__
if (__builtin_constant_p(property_name) && __builtin_constant_p(property_length)) {
return zephir_fetch_nproperty_this_quick(object, property_name, property_length, zend_inline_hash_func(property_name, property_length + 1), silent TSRMLS_CC);
}
#endif
return zephir_fetch_nproperty_this_quick(object, property_name, property_length, zend_hash_func(property_name, property_length + 1), silent TSRMLS_CC);
}
ZEPHIR_ATTR_NONNULL static inline zval* zephir_fetch_property_this(zval *object, const char *property_name, zend_uint property_length, int silent TSRMLS_DC)
{
#ifdef __GNUC__
if (__builtin_constant_p(property_name) && __builtin_constant_p(property_length)) {
return zephir_fetch_property_this_quick(object, property_name, property_length, zend_inline_hash_func(property_name, property_length + 1), silent TSRMLS_CC);
}
#endif
return zephir_fetch_property_this_quick(object, property_name, property_length, zend_hash_func(property_name, property_length + 1), silent TSRMLS_CC);
}
#endif
#define zephir_fetch_safe_class(destination, var) \
{ \
if (Z_TYPE_P(var) == IS_STRING) { \
ZEPHIR_CPY_WRT(destination, var); \
} else { \
ZEPHIR_INIT_NVAR(destination); \
ZVAL_STRING(destination, "<undefined class>", 1); \
} \
}
| 58.540404 | 203 | 0.758433 | [
"object"
] |
3c43f4443fe311d9502bd79ff7b21a6e9cee3c4b | 43,704 | h | C | libraries/proto/generated/koinos/contracts/pow/pow.pb.h | koinos/koinos-proto-cpp | c453f4eb2ad10b1a22c3c06f5c769a65c6806075 | [
"MIT"
] | null | null | null | libraries/proto/generated/koinos/contracts/pow/pow.pb.h | koinos/koinos-proto-cpp | c453f4eb2ad10b1a22c3c06f5c769a65c6806075 | [
"MIT"
] | 3 | 2021-09-13T20:50:48.000Z | 2021-12-14T16:59:05.000Z | libraries/proto/generated/koinos/contracts/pow/pow.pb.h | koinos/koinos-proto-cpp | c453f4eb2ad10b1a22c3c06f5c769a65c6806075 | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: koinos/contracts/pow/pow.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_koinos_2fcontracts_2fpow_2fpow_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_koinos_2fcontracts_2fpow_2fpow_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3017000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3017003 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_koinos_2fcontracts_2fpow_2fpow_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_koinos_2fcontracts_2fpow_2fpow_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[4]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_koinos_2fcontracts_2fpow_2fpow_2eproto;
namespace koinos {
namespace contracts {
namespace pow {
class difficulty_metadata;
struct difficulty_metadataDefaultTypeInternal;
extern difficulty_metadataDefaultTypeInternal _difficulty_metadata_default_instance_;
class get_difficulty_metadata_arguments;
struct get_difficulty_metadata_argumentsDefaultTypeInternal;
extern get_difficulty_metadata_argumentsDefaultTypeInternal _get_difficulty_metadata_arguments_default_instance_;
class get_difficulty_metadata_result;
struct get_difficulty_metadata_resultDefaultTypeInternal;
extern get_difficulty_metadata_resultDefaultTypeInternal _get_difficulty_metadata_result_default_instance_;
class pow_signature_data;
struct pow_signature_dataDefaultTypeInternal;
extern pow_signature_dataDefaultTypeInternal _pow_signature_data_default_instance_;
} // namespace pow
} // namespace contracts
} // namespace koinos
PROTOBUF_NAMESPACE_OPEN
template<> ::koinos::contracts::pow::difficulty_metadata* Arena::CreateMaybeMessage<::koinos::contracts::pow::difficulty_metadata>(Arena*);
template<> ::koinos::contracts::pow::get_difficulty_metadata_arguments* Arena::CreateMaybeMessage<::koinos::contracts::pow::get_difficulty_metadata_arguments>(Arena*);
template<> ::koinos::contracts::pow::get_difficulty_metadata_result* Arena::CreateMaybeMessage<::koinos::contracts::pow::get_difficulty_metadata_result>(Arena*);
template<> ::koinos::contracts::pow::pow_signature_data* Arena::CreateMaybeMessage<::koinos::contracts::pow::pow_signature_data>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace koinos {
namespace contracts {
namespace pow {
// ===================================================================
class difficulty_metadata final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:koinos.contracts.pow.difficulty_metadata) */ {
public:
inline difficulty_metadata() : difficulty_metadata(nullptr) {}
~difficulty_metadata() override;
explicit constexpr difficulty_metadata(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
difficulty_metadata(const difficulty_metadata& from);
difficulty_metadata(difficulty_metadata&& from) noexcept
: difficulty_metadata() {
*this = ::std::move(from);
}
inline difficulty_metadata& operator=(const difficulty_metadata& from) {
CopyFrom(from);
return *this;
}
inline difficulty_metadata& operator=(difficulty_metadata&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const difficulty_metadata& default_instance() {
return *internal_default_instance();
}
static inline const difficulty_metadata* internal_default_instance() {
return reinterpret_cast<const difficulty_metadata*>(
&_difficulty_metadata_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(difficulty_metadata& a, difficulty_metadata& b) {
a.Swap(&b);
}
inline void Swap(difficulty_metadata* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(difficulty_metadata* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline difficulty_metadata* New() const final {
return new difficulty_metadata();
}
difficulty_metadata* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<difficulty_metadata>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const difficulty_metadata& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const difficulty_metadata& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(difficulty_metadata* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "koinos.contracts.pow.difficulty_metadata";
}
protected:
explicit difficulty_metadata(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kTargetFieldNumber = 1,
kDifficultyFieldNumber = 3,
kLastBlockTimeFieldNumber = 2,
kTargetBlockIntervalFieldNumber = 4,
};
// bytes target = 1;
void clear_target();
const std::string& target() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_target(ArgT0&& arg0, ArgT... args);
std::string* mutable_target();
PROTOBUF_MUST_USE_RESULT std::string* release_target();
void set_allocated_target(std::string* target);
private:
const std::string& _internal_target() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_target(const std::string& value);
std::string* _internal_mutable_target();
public:
// bytes difficulty = 3;
void clear_difficulty();
const std::string& difficulty() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_difficulty(ArgT0&& arg0, ArgT... args);
std::string* mutable_difficulty();
PROTOBUF_MUST_USE_RESULT std::string* release_difficulty();
void set_allocated_difficulty(std::string* difficulty);
private:
const std::string& _internal_difficulty() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_difficulty(const std::string& value);
std::string* _internal_mutable_difficulty();
public:
// uint64 last_block_time = 2 [jstype = JS_STRING];
void clear_last_block_time();
::PROTOBUF_NAMESPACE_ID::uint64 last_block_time() const;
void set_last_block_time(::PROTOBUF_NAMESPACE_ID::uint64 value);
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_last_block_time() const;
void _internal_set_last_block_time(::PROTOBUF_NAMESPACE_ID::uint64 value);
public:
// uint64 target_block_interval = 4 [jstype = JS_STRING];
void clear_target_block_interval();
::PROTOBUF_NAMESPACE_ID::uint64 target_block_interval() const;
void set_target_block_interval(::PROTOBUF_NAMESPACE_ID::uint64 value);
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_target_block_interval() const;
void _internal_set_target_block_interval(::PROTOBUF_NAMESPACE_ID::uint64 value);
public:
// @@protoc_insertion_point(class_scope:koinos.contracts.pow.difficulty_metadata)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr target_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr difficulty_;
::PROTOBUF_NAMESPACE_ID::uint64 last_block_time_;
::PROTOBUF_NAMESPACE_ID::uint64 target_block_interval_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_koinos_2fcontracts_2fpow_2fpow_2eproto;
};
// -------------------------------------------------------------------
class get_difficulty_metadata_arguments final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:koinos.contracts.pow.get_difficulty_metadata_arguments) */ {
public:
inline get_difficulty_metadata_arguments() : get_difficulty_metadata_arguments(nullptr) {}
~get_difficulty_metadata_arguments() override;
explicit constexpr get_difficulty_metadata_arguments(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
get_difficulty_metadata_arguments(const get_difficulty_metadata_arguments& from);
get_difficulty_metadata_arguments(get_difficulty_metadata_arguments&& from) noexcept
: get_difficulty_metadata_arguments() {
*this = ::std::move(from);
}
inline get_difficulty_metadata_arguments& operator=(const get_difficulty_metadata_arguments& from) {
CopyFrom(from);
return *this;
}
inline get_difficulty_metadata_arguments& operator=(get_difficulty_metadata_arguments&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const get_difficulty_metadata_arguments& default_instance() {
return *internal_default_instance();
}
static inline const get_difficulty_metadata_arguments* internal_default_instance() {
return reinterpret_cast<const get_difficulty_metadata_arguments*>(
&_get_difficulty_metadata_arguments_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
friend void swap(get_difficulty_metadata_arguments& a, get_difficulty_metadata_arguments& b) {
a.Swap(&b);
}
inline void Swap(get_difficulty_metadata_arguments* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(get_difficulty_metadata_arguments* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline get_difficulty_metadata_arguments* New() const final {
return new get_difficulty_metadata_arguments();
}
get_difficulty_metadata_arguments* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<get_difficulty_metadata_arguments>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const get_difficulty_metadata_arguments& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const get_difficulty_metadata_arguments& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(get_difficulty_metadata_arguments* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "koinos.contracts.pow.get_difficulty_metadata_arguments";
}
protected:
explicit get_difficulty_metadata_arguments(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// @@protoc_insertion_point(class_scope:koinos.contracts.pow.get_difficulty_metadata_arguments)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_koinos_2fcontracts_2fpow_2fpow_2eproto;
};
// -------------------------------------------------------------------
class get_difficulty_metadata_result final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:koinos.contracts.pow.get_difficulty_metadata_result) */ {
public:
inline get_difficulty_metadata_result() : get_difficulty_metadata_result(nullptr) {}
~get_difficulty_metadata_result() override;
explicit constexpr get_difficulty_metadata_result(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
get_difficulty_metadata_result(const get_difficulty_metadata_result& from);
get_difficulty_metadata_result(get_difficulty_metadata_result&& from) noexcept
: get_difficulty_metadata_result() {
*this = ::std::move(from);
}
inline get_difficulty_metadata_result& operator=(const get_difficulty_metadata_result& from) {
CopyFrom(from);
return *this;
}
inline get_difficulty_metadata_result& operator=(get_difficulty_metadata_result&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const get_difficulty_metadata_result& default_instance() {
return *internal_default_instance();
}
static inline const get_difficulty_metadata_result* internal_default_instance() {
return reinterpret_cast<const get_difficulty_metadata_result*>(
&_get_difficulty_metadata_result_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
friend void swap(get_difficulty_metadata_result& a, get_difficulty_metadata_result& b) {
a.Swap(&b);
}
inline void Swap(get_difficulty_metadata_result* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(get_difficulty_metadata_result* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline get_difficulty_metadata_result* New() const final {
return new get_difficulty_metadata_result();
}
get_difficulty_metadata_result* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<get_difficulty_metadata_result>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const get_difficulty_metadata_result& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const get_difficulty_metadata_result& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(get_difficulty_metadata_result* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "koinos.contracts.pow.get_difficulty_metadata_result";
}
protected:
explicit get_difficulty_metadata_result(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kValueFieldNumber = 1,
};
// .koinos.contracts.pow.difficulty_metadata value = 1;
bool has_value() const;
private:
bool _internal_has_value() const;
public:
void clear_value();
const ::koinos::contracts::pow::difficulty_metadata& value() const;
PROTOBUF_MUST_USE_RESULT ::koinos::contracts::pow::difficulty_metadata* release_value();
::koinos::contracts::pow::difficulty_metadata* mutable_value();
void set_allocated_value(::koinos::contracts::pow::difficulty_metadata* value);
private:
const ::koinos::contracts::pow::difficulty_metadata& _internal_value() const;
::koinos::contracts::pow::difficulty_metadata* _internal_mutable_value();
public:
void unsafe_arena_set_allocated_value(
::koinos::contracts::pow::difficulty_metadata* value);
::koinos::contracts::pow::difficulty_metadata* unsafe_arena_release_value();
// @@protoc_insertion_point(class_scope:koinos.contracts.pow.get_difficulty_metadata_result)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::koinos::contracts::pow::difficulty_metadata* value_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_koinos_2fcontracts_2fpow_2fpow_2eproto;
};
// -------------------------------------------------------------------
class pow_signature_data final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:koinos.contracts.pow.pow_signature_data) */ {
public:
inline pow_signature_data() : pow_signature_data(nullptr) {}
~pow_signature_data() override;
explicit constexpr pow_signature_data(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
pow_signature_data(const pow_signature_data& from);
pow_signature_data(pow_signature_data&& from) noexcept
: pow_signature_data() {
*this = ::std::move(from);
}
inline pow_signature_data& operator=(const pow_signature_data& from) {
CopyFrom(from);
return *this;
}
inline pow_signature_data& operator=(pow_signature_data&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const pow_signature_data& default_instance() {
return *internal_default_instance();
}
static inline const pow_signature_data* internal_default_instance() {
return reinterpret_cast<const pow_signature_data*>(
&_pow_signature_data_default_instance_);
}
static constexpr int kIndexInFileMessages =
3;
friend void swap(pow_signature_data& a, pow_signature_data& b) {
a.Swap(&b);
}
inline void Swap(pow_signature_data* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(pow_signature_data* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline pow_signature_data* New() const final {
return new pow_signature_data();
}
pow_signature_data* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<pow_signature_data>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const pow_signature_data& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const pow_signature_data& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(pow_signature_data* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "koinos.contracts.pow.pow_signature_data";
}
protected:
explicit pow_signature_data(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kNonceFieldNumber = 1,
kRecoverableSignatureFieldNumber = 2,
};
// bytes nonce = 1;
void clear_nonce();
const std::string& nonce() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_nonce(ArgT0&& arg0, ArgT... args);
std::string* mutable_nonce();
PROTOBUF_MUST_USE_RESULT std::string* release_nonce();
void set_allocated_nonce(std::string* nonce);
private:
const std::string& _internal_nonce() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_nonce(const std::string& value);
std::string* _internal_mutable_nonce();
public:
// bytes recoverable_signature = 2;
void clear_recoverable_signature();
const std::string& recoverable_signature() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_recoverable_signature(ArgT0&& arg0, ArgT... args);
std::string* mutable_recoverable_signature();
PROTOBUF_MUST_USE_RESULT std::string* release_recoverable_signature();
void set_allocated_recoverable_signature(std::string* recoverable_signature);
private:
const std::string& _internal_recoverable_signature() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_recoverable_signature(const std::string& value);
std::string* _internal_mutable_recoverable_signature();
public:
// @@protoc_insertion_point(class_scope:koinos.contracts.pow.pow_signature_data)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr nonce_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr recoverable_signature_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_koinos_2fcontracts_2fpow_2fpow_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// difficulty_metadata
// bytes target = 1;
inline void difficulty_metadata::clear_target() {
target_.ClearToEmpty();
}
inline const std::string& difficulty_metadata::target() const {
// @@protoc_insertion_point(field_get:koinos.contracts.pow.difficulty_metadata.target)
return _internal_target();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void difficulty_metadata::set_target(ArgT0&& arg0, ArgT... args) {
target_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:koinos.contracts.pow.difficulty_metadata.target)
}
inline std::string* difficulty_metadata::mutable_target() {
std::string* _s = _internal_mutable_target();
// @@protoc_insertion_point(field_mutable:koinos.contracts.pow.difficulty_metadata.target)
return _s;
}
inline const std::string& difficulty_metadata::_internal_target() const {
return target_.Get();
}
inline void difficulty_metadata::_internal_set_target(const std::string& value) {
target_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* difficulty_metadata::_internal_mutable_target() {
return target_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* difficulty_metadata::release_target() {
// @@protoc_insertion_point(field_release:koinos.contracts.pow.difficulty_metadata.target)
return target_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
}
inline void difficulty_metadata::set_allocated_target(std::string* target) {
if (target != nullptr) {
} else {
}
target_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), target,
GetArenaForAllocation());
// @@protoc_insertion_point(field_set_allocated:koinos.contracts.pow.difficulty_metadata.target)
}
// uint64 last_block_time = 2 [jstype = JS_STRING];
inline void difficulty_metadata::clear_last_block_time() {
last_block_time_ = uint64_t{0u};
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 difficulty_metadata::_internal_last_block_time() const {
return last_block_time_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 difficulty_metadata::last_block_time() const {
// @@protoc_insertion_point(field_get:koinos.contracts.pow.difficulty_metadata.last_block_time)
return _internal_last_block_time();
}
inline void difficulty_metadata::_internal_set_last_block_time(::PROTOBUF_NAMESPACE_ID::uint64 value) {
last_block_time_ = value;
}
inline void difficulty_metadata::set_last_block_time(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_set_last_block_time(value);
// @@protoc_insertion_point(field_set:koinos.contracts.pow.difficulty_metadata.last_block_time)
}
// bytes difficulty = 3;
inline void difficulty_metadata::clear_difficulty() {
difficulty_.ClearToEmpty();
}
inline const std::string& difficulty_metadata::difficulty() const {
// @@protoc_insertion_point(field_get:koinos.contracts.pow.difficulty_metadata.difficulty)
return _internal_difficulty();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void difficulty_metadata::set_difficulty(ArgT0&& arg0, ArgT... args) {
difficulty_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:koinos.contracts.pow.difficulty_metadata.difficulty)
}
inline std::string* difficulty_metadata::mutable_difficulty() {
std::string* _s = _internal_mutable_difficulty();
// @@protoc_insertion_point(field_mutable:koinos.contracts.pow.difficulty_metadata.difficulty)
return _s;
}
inline const std::string& difficulty_metadata::_internal_difficulty() const {
return difficulty_.Get();
}
inline void difficulty_metadata::_internal_set_difficulty(const std::string& value) {
difficulty_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* difficulty_metadata::_internal_mutable_difficulty() {
return difficulty_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* difficulty_metadata::release_difficulty() {
// @@protoc_insertion_point(field_release:koinos.contracts.pow.difficulty_metadata.difficulty)
return difficulty_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
}
inline void difficulty_metadata::set_allocated_difficulty(std::string* difficulty) {
if (difficulty != nullptr) {
} else {
}
difficulty_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), difficulty,
GetArenaForAllocation());
// @@protoc_insertion_point(field_set_allocated:koinos.contracts.pow.difficulty_metadata.difficulty)
}
// uint64 target_block_interval = 4 [jstype = JS_STRING];
inline void difficulty_metadata::clear_target_block_interval() {
target_block_interval_ = uint64_t{0u};
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 difficulty_metadata::_internal_target_block_interval() const {
return target_block_interval_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 difficulty_metadata::target_block_interval() const {
// @@protoc_insertion_point(field_get:koinos.contracts.pow.difficulty_metadata.target_block_interval)
return _internal_target_block_interval();
}
inline void difficulty_metadata::_internal_set_target_block_interval(::PROTOBUF_NAMESPACE_ID::uint64 value) {
target_block_interval_ = value;
}
inline void difficulty_metadata::set_target_block_interval(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_set_target_block_interval(value);
// @@protoc_insertion_point(field_set:koinos.contracts.pow.difficulty_metadata.target_block_interval)
}
// -------------------------------------------------------------------
// get_difficulty_metadata_arguments
// -------------------------------------------------------------------
// get_difficulty_metadata_result
// .koinos.contracts.pow.difficulty_metadata value = 1;
inline bool get_difficulty_metadata_result::_internal_has_value() const {
return this != internal_default_instance() && value_ != nullptr;
}
inline bool get_difficulty_metadata_result::has_value() const {
return _internal_has_value();
}
inline void get_difficulty_metadata_result::clear_value() {
if (GetArenaForAllocation() == nullptr && value_ != nullptr) {
delete value_;
}
value_ = nullptr;
}
inline const ::koinos::contracts::pow::difficulty_metadata& get_difficulty_metadata_result::_internal_value() const {
const ::koinos::contracts::pow::difficulty_metadata* p = value_;
return p != nullptr ? *p : reinterpret_cast<const ::koinos::contracts::pow::difficulty_metadata&>(
::koinos::contracts::pow::_difficulty_metadata_default_instance_);
}
inline const ::koinos::contracts::pow::difficulty_metadata& get_difficulty_metadata_result::value() const {
// @@protoc_insertion_point(field_get:koinos.contracts.pow.get_difficulty_metadata_result.value)
return _internal_value();
}
inline void get_difficulty_metadata_result::unsafe_arena_set_allocated_value(
::koinos::contracts::pow::difficulty_metadata* value) {
if (GetArenaForAllocation() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(value_);
}
value_ = value;
if (value) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:koinos.contracts.pow.get_difficulty_metadata_result.value)
}
inline ::koinos::contracts::pow::difficulty_metadata* get_difficulty_metadata_result::release_value() {
::koinos::contracts::pow::difficulty_metadata* temp = value_;
value_ = nullptr;
#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE
auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp);
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
if (GetArenaForAllocation() == nullptr) { delete old; }
#else // PROTOBUF_FORCE_COPY_IN_RELEASE
if (GetArenaForAllocation() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE
return temp;
}
inline ::koinos::contracts::pow::difficulty_metadata* get_difficulty_metadata_result::unsafe_arena_release_value() {
// @@protoc_insertion_point(field_release:koinos.contracts.pow.get_difficulty_metadata_result.value)
::koinos::contracts::pow::difficulty_metadata* temp = value_;
value_ = nullptr;
return temp;
}
inline ::koinos::contracts::pow::difficulty_metadata* get_difficulty_metadata_result::_internal_mutable_value() {
if (value_ == nullptr) {
auto* p = CreateMaybeMessage<::koinos::contracts::pow::difficulty_metadata>(GetArenaForAllocation());
value_ = p;
}
return value_;
}
inline ::koinos::contracts::pow::difficulty_metadata* get_difficulty_metadata_result::mutable_value() {
::koinos::contracts::pow::difficulty_metadata* _msg = _internal_mutable_value();
// @@protoc_insertion_point(field_mutable:koinos.contracts.pow.get_difficulty_metadata_result.value)
return _msg;
}
inline void get_difficulty_metadata_result::set_allocated_value(::koinos::contracts::pow::difficulty_metadata* value) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation();
if (message_arena == nullptr) {
delete value_;
}
if (value) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper<::koinos::contracts::pow::difficulty_metadata>::GetOwningArena(value);
if (message_arena != submessage_arena) {
value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, value, submessage_arena);
}
} else {
}
value_ = value;
// @@protoc_insertion_point(field_set_allocated:koinos.contracts.pow.get_difficulty_metadata_result.value)
}
// -------------------------------------------------------------------
// pow_signature_data
// bytes nonce = 1;
inline void pow_signature_data::clear_nonce() {
nonce_.ClearToEmpty();
}
inline const std::string& pow_signature_data::nonce() const {
// @@protoc_insertion_point(field_get:koinos.contracts.pow.pow_signature_data.nonce)
return _internal_nonce();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void pow_signature_data::set_nonce(ArgT0&& arg0, ArgT... args) {
nonce_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:koinos.contracts.pow.pow_signature_data.nonce)
}
inline std::string* pow_signature_data::mutable_nonce() {
std::string* _s = _internal_mutable_nonce();
// @@protoc_insertion_point(field_mutable:koinos.contracts.pow.pow_signature_data.nonce)
return _s;
}
inline const std::string& pow_signature_data::_internal_nonce() const {
return nonce_.Get();
}
inline void pow_signature_data::_internal_set_nonce(const std::string& value) {
nonce_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* pow_signature_data::_internal_mutable_nonce() {
return nonce_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* pow_signature_data::release_nonce() {
// @@protoc_insertion_point(field_release:koinos.contracts.pow.pow_signature_data.nonce)
return nonce_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
}
inline void pow_signature_data::set_allocated_nonce(std::string* nonce) {
if (nonce != nullptr) {
} else {
}
nonce_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), nonce,
GetArenaForAllocation());
// @@protoc_insertion_point(field_set_allocated:koinos.contracts.pow.pow_signature_data.nonce)
}
// bytes recoverable_signature = 2;
inline void pow_signature_data::clear_recoverable_signature() {
recoverable_signature_.ClearToEmpty();
}
inline const std::string& pow_signature_data::recoverable_signature() const {
// @@protoc_insertion_point(field_get:koinos.contracts.pow.pow_signature_data.recoverable_signature)
return _internal_recoverable_signature();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void pow_signature_data::set_recoverable_signature(ArgT0&& arg0, ArgT... args) {
recoverable_signature_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:koinos.contracts.pow.pow_signature_data.recoverable_signature)
}
inline std::string* pow_signature_data::mutable_recoverable_signature() {
std::string* _s = _internal_mutable_recoverable_signature();
// @@protoc_insertion_point(field_mutable:koinos.contracts.pow.pow_signature_data.recoverable_signature)
return _s;
}
inline const std::string& pow_signature_data::_internal_recoverable_signature() const {
return recoverable_signature_.Get();
}
inline void pow_signature_data::_internal_set_recoverable_signature(const std::string& value) {
recoverable_signature_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* pow_signature_data::_internal_mutable_recoverable_signature() {
return recoverable_signature_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* pow_signature_data::release_recoverable_signature() {
// @@protoc_insertion_point(field_release:koinos.contracts.pow.pow_signature_data.recoverable_signature)
return recoverable_signature_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
}
inline void pow_signature_data::set_allocated_recoverable_signature(std::string* recoverable_signature) {
if (recoverable_signature != nullptr) {
} else {
}
recoverable_signature_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), recoverable_signature,
GetArenaForAllocation());
// @@protoc_insertion_point(field_set_allocated:koinos.contracts.pow.pow_signature_data.recoverable_signature)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace pow
} // namespace contracts
} // namespace koinos
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_koinos_2fcontracts_2fpow_2fpow_2eproto
| 41.347209 | 167 | 0.749931 | [
"object"
] |
3c44c6b9cb86249499ad3293d91ffef051afa059 | 116,071 | c | C | maistra/vendor/com_github_wamr/core/iwasm/common/wasm_c_api.c | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | null | null | null | maistra/vendor/com_github_wamr/core/iwasm/common/wasm_c_api.c | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | 11 | 2019-10-15T23:03:57.000Z | 2020-06-14T16:10:12.000Z | maistra/vendor/com_github_wamr/core/iwasm/common/wasm_c_api.c | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | 7 | 2019-07-04T14:23:54.000Z | 2020-04-27T08:52:51.000Z | /*
* Copyright (C) 2019 Intel Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#include "wasm_c_api_internal.h"
#include "wasm_memory.h"
#if WASM_ENABLE_INTERP != 0
#include "wasm_runtime.h"
#endif
#if WASM_ENABLE_AOT != 0
#include "aot_runtime.h"
#endif
#define ASSERT_NOT_IMPLEMENTED() bh_assert(!"not implemented")
typedef struct wasm_module_ex_t wasm_module_ex_t;
static void
wasm_module_delete_internal(wasm_module_t *);
static void
wasm_instance_delete_internal(wasm_instance_t *);
/* temporarily put stubs here */
static wasm_store_t *
wasm_store_copy(const wasm_store_t *src)
{
(void)src;
LOG_WARNING("in the stub of %s", __FUNCTION__);
return NULL;
}
wasm_module_t *
wasm_module_copy(const wasm_module_t *src)
{
(void)src;
LOG_WARNING("in the stub of %s", __FUNCTION__);
return NULL;
}
wasm_instance_t *
wasm_instance_copy(const wasm_instance_t *src)
{
(void)src;
LOG_WARNING("in the stub of %s", __FUNCTION__);
return NULL;
}
static void *
malloc_internal(uint64 size)
{
void *mem = NULL;
if (size < UINT32_MAX && (mem = wasm_runtime_malloc((uint32)size))) {
memset(mem, 0, size);
}
return mem;
}
#define FREEIF(p) \
if (p) { \
wasm_runtime_free(p); \
}
/* clang-format off */
#define RETURN_OBJ(obj, obj_del_func) \
return obj; \
failed: \
obj_del_func(obj); \
return NULL;
#define RETURN_VOID(obj, obj_del_func) \
return; \
failed: \
obj_del_func(obj); \
return;
/* clang-format on */
/* Vectors */
#define INIT_VEC(vector_p, init_func, ...) \
do { \
if (!(vector_p = malloc_internal(sizeof(*(vector_p))))) { \
goto failed; \
} \
\
init_func(vector_p, ##__VA_ARGS__); \
if (vector_p->size && !vector_p->data) { \
LOG_DEBUG("%s failed", #init_func); \
goto failed; \
} \
} while (false)
#define DEINIT_VEC(vector_p, deinit_func) \
if ((vector_p)) { \
deinit_func(vector_p); \
wasm_runtime_free(vector_p); \
vector_p = NULL; \
}
#define WASM_DEFINE_VEC(name) \
void wasm_##name##_vec_new_empty(own wasm_##name##_vec_t *out) \
{ \
wasm_##name##_vec_new_uninitialized(out, 0); \
} \
void wasm_##name##_vec_new_uninitialized(own wasm_##name##_vec_t *out, \
size_t size) \
{ \
wasm_##name##_vec_new(out, size, NULL); \
}
/* vectors with no ownership management of elements */
#define WASM_DEFINE_VEC_PLAIN(name) \
WASM_DEFINE_VEC(name) \
void wasm_##name##_vec_new(own wasm_##name##_vec_t *out, size_t size, \
own wasm_##name##_t const data[]) \
{ \
if (!out) { \
return; \
} \
\
memset(out, 0, sizeof(wasm_##name##_vec_t)); \
\
if (!size) { \
return; \
} \
\
if (!bh_vector_init((Vector *)out, size, sizeof(wasm_##name##_t))) { \
LOG_DEBUG("bh_vector_init failed"); \
goto failed; \
} \
\
if (data) { \
unsigned int size_in_bytes = 0; \
size_in_bytes = size * sizeof(wasm_##name##_t); \
bh_memcpy_s(out->data, size_in_bytes, data, size_in_bytes); \
out->num_elems = size; \
} \
\
RETURN_VOID(out, wasm_##name##_vec_delete) \
} \
void wasm_##name##_vec_copy(wasm_##name##_vec_t *out, \
const wasm_##name##_vec_t *src) \
{ \
wasm_##name##_vec_new(out, src->size, src->data); \
} \
void wasm_##name##_vec_delete(wasm_##name##_vec_t *v) \
{ \
if (v) { \
bh_vector_destroy((Vector *)v); \
} \
}
/* vectors that own their elements */
#define WASM_DEFINE_VEC_OWN(name, elem_destroy_func) \
WASM_DEFINE_VEC(name) \
void wasm_##name##_vec_new(own wasm_##name##_vec_t *out, size_t size, \
own wasm_##name##_t *const data[]) \
{ \
if (!out) { \
return; \
} \
\
memset(out, 0, sizeof(wasm_##name##_vec_t)); \
\
if (!size) { \
return; \
} \
\
if (!bh_vector_init((Vector *)out, size, \
sizeof(wasm_##name##_t *))) { \
LOG_DEBUG("bh_vector_init failed"); \
goto failed; \
} \
\
if (data) { \
unsigned int size_in_bytes = 0; \
size_in_bytes = size * sizeof(wasm_##name##_t *); \
bh_memcpy_s(out->data, size_in_bytes, data, size_in_bytes); \
out->num_elems = size; \
} \
\
RETURN_VOID(out, wasm_##name##_vec_delete) \
} \
void wasm_##name##_vec_copy(own wasm_##name##_vec_t *out, \
const wasm_##name##_vec_t *src) \
{ \
size_t i = 0; \
memset(out, 0, sizeof(Vector)); \
\
if (!src || !src->size) { \
return; \
} \
\
if (!bh_vector_init((Vector *)out, src->size, \
sizeof(wasm_##name##_t *))) { \
LOG_DEBUG("bh_vector_init failed"); \
goto failed; \
} \
\
for (i = 0; i != src->num_elems; ++i) { \
if (!(out->data[i] = wasm_##name##_copy(src->data[i]))) { \
LOG_DEBUG("wasm_%s_copy failed", #name); \
goto failed; \
} \
} \
out->num_elems = src->num_elems; \
\
RETURN_VOID(out, wasm_##name##_vec_delete) \
} \
void wasm_##name##_vec_delete(wasm_##name##_vec_t *v) \
{ \
size_t i = 0; \
if (!v) { \
return; \
} \
for (i = 0; i != v->num_elems; ++i) { \
elem_destroy_func(*(v->data + i)); \
} \
bh_vector_destroy((Vector *)v); \
}
WASM_DEFINE_VEC_PLAIN(byte)
WASM_DEFINE_VEC_PLAIN(val)
WASM_DEFINE_VEC_OWN(valtype, wasm_valtype_delete)
WASM_DEFINE_VEC_OWN(functype, wasm_functype_delete)
WASM_DEFINE_VEC_OWN(exporttype, wasm_exporttype_delete)
WASM_DEFINE_VEC_OWN(importtype, wasm_importtype_delete)
WASM_DEFINE_VEC_OWN(store, wasm_store_delete)
WASM_DEFINE_VEC_OWN(module, wasm_module_delete_internal)
WASM_DEFINE_VEC_OWN(instance, wasm_instance_delete_internal)
WASM_DEFINE_VEC_OWN(extern, wasm_extern_delete)
WASM_DEFINE_VEC_OWN(frame, wasm_frame_delete)
static inline bool
valid_module_type(uint32 module_type)
{
bool result = false;
#if WASM_ENABLE_INTERP != 0
result = result || (module_type == Wasm_Module_Bytecode);
#endif
#if WASM_ENABLE_AOT != 0
result = result || (module_type == Wasm_Module_AoT);
#endif
if (!result) {
LOG_VERBOSE(
"current building isn't compatiable with the module, may need "
"recompile");
}
return result;
}
/* conflicting declaration between aot_export.h and aot.h */
#if WASM_ENABLE_AOT != 0 && WASM_ENABLE_JIT != 0
bool
aot_compile_wasm_file_init();
void
aot_compile_wasm_file_destroy();
uint8*
aot_compile_wasm_file(const uint8 *wasm_file_buf, uint32 wasm_file_size,
uint32 opt_level, uint32 size_level,
char *error_buf, uint32 error_buf_size,
uint32 *p_aot_file_size);
#endif
/* Runtime Environment */
static void
wasm_engine_delete_internal(wasm_engine_t *engine)
{
if (engine) {
DEINIT_VEC(engine->stores, wasm_store_vec_delete);
wasm_runtime_free(engine);
}
#if WASM_ENABLE_AOT != 0 && WASM_ENABLE_JIT != 0
aot_compile_wasm_file_destroy();
#endif
wasm_runtime_destroy();
}
static wasm_engine_t *
wasm_engine_new_internal(mem_alloc_type_t type, const MemAllocOption *opts)
{
wasm_engine_t *engine = NULL;
/* init runtime */
RuntimeInitArgs init_args = { 0 };
init_args.mem_alloc_type = type;
if (type == Alloc_With_Pool) {
if (!opts) {
return NULL;
}
init_args.mem_alloc_option.pool.heap_buf = opts->pool.heap_buf;
init_args.mem_alloc_option.pool.heap_size = opts->pool.heap_size;
}
else if (type == Alloc_With_Allocator) {
if (!opts) {
return NULL;
}
init_args.mem_alloc_option.allocator.malloc_func =
opts->allocator.malloc_func;
init_args.mem_alloc_option.allocator.free_func =
opts->allocator.free_func;
init_args.mem_alloc_option.allocator.realloc_func =
opts->allocator.realloc_func;
}
else {
init_args.mem_alloc_option.pool.heap_buf = NULL;
init_args.mem_alloc_option.pool.heap_size = 0;
}
if (!wasm_runtime_full_init(&init_args)) {
LOG_DEBUG("wasm_runtime_full_init failed");
goto failed;
}
#if BH_DEBUG != 0
bh_log_set_verbose_level(5);
#else
bh_log_set_verbose_level(3);
#endif
#if WASM_ENABLE_AOT != 0 && WASM_ENABLE_JIT != 0
if (!aot_compile_wasm_file_init()) {
goto failed;
}
#endif
/* create wasm_engine_t */
if (!(engine = malloc_internal(sizeof(wasm_engine_t)))) {
goto failed;
}
/* create wasm_store_vec_t */
INIT_VEC(engine->stores, wasm_store_vec_new_uninitialized, 1);
RETURN_OBJ(engine, wasm_engine_delete_internal)
}
/* global engine instance */
static wasm_engine_t *singleton_engine = NULL;
wasm_engine_t *
wasm_engine_new()
{
if (!singleton_engine) {
singleton_engine =
wasm_engine_new_internal(Alloc_With_System_Allocator, NULL);
}
return singleton_engine;
}
wasm_engine_t *
wasm_engine_new_with_args(mem_alloc_type_t type, const MemAllocOption *opts)
{
if (!singleton_engine) {
singleton_engine = wasm_engine_new_internal(type, opts);
}
return singleton_engine;
}
/* BE AWARE: will RESET the singleton */
void
wasm_engine_delete(wasm_engine_t *engine)
{
if (engine) {
wasm_engine_delete_internal(engine);
singleton_engine = NULL;
}
}
wasm_store_t *
wasm_store_new(wasm_engine_t *engine)
{
wasm_store_t *store = NULL;
if (!engine || singleton_engine != engine) {
return NULL;
}
if (!wasm_runtime_init_thread_env()) {
LOG_ERROR("init thread environment failed");
return NULL;
}
if (!(store = malloc_internal(sizeof(wasm_store_t)))) {
wasm_runtime_destroy_thread_env();
return NULL;
}
/* new a vector, and new its data */
INIT_VEC(store->modules, wasm_module_vec_new_uninitialized,
DEFAULT_VECTOR_INIT_LENGTH);
INIT_VEC(store->instances, wasm_instance_vec_new_uninitialized,
DEFAULT_VECTOR_INIT_LENGTH);
/* append to a store list of engine */
if (!bh_vector_append((Vector *)singleton_engine->stores, &store)) {
LOG_DEBUG("bh_vector_append failed");
goto failed;
}
return store;
failed:
wasm_store_delete(store);
return NULL;
}
void
wasm_store_delete(wasm_store_t *store)
{
size_t i, store_count;
if (!store) {
return;
}
/* remove it from the list in the engine */
store_count = bh_vector_size((Vector *)singleton_engine->stores);
for (i = 0; i != store_count; ++i) {
wasm_store_t *tmp;
if (!bh_vector_get((Vector *)singleton_engine->stores, i, &tmp)) {
break;
}
if (tmp == store) {
bh_vector_remove((Vector *)singleton_engine->stores, i, NULL);
break;
}
}
DEINIT_VEC(store->modules, wasm_module_vec_delete);
DEINIT_VEC(store->instances, wasm_instance_vec_delete);
wasm_runtime_free(store);
wasm_runtime_destroy_thread_env();
}
/* Type Representations */
static wasm_valkind_t
val_type_rt_2_valkind(uint8 val_type_rt)
{
switch (val_type_rt) {
case VALUE_TYPE_I32:
return WASM_I32;
case VALUE_TYPE_I64:
return WASM_I64;
case VALUE_TYPE_F32:
return WASM_F32;
case VALUE_TYPE_F64:
return WASM_F64;
case VALUE_TYPE_ANY:
return WASM_ANYREF;
case VALUE_TYPE_FUNCREF:
return WASM_FUNCREF;
default:
LOG_WARNING("%s meets unsupported type: %d", __FUNCTION__,
val_type_rt);
return WASM_ANYREF;
}
}
static wasm_valtype_t *
wasm_valtype_new_internal(uint8 val_type_rt)
{
return wasm_valtype_new(val_type_rt_2_valkind(val_type_rt));
}
wasm_valtype_t *
wasm_valtype_new(wasm_valkind_t kind)
{
wasm_valtype_t *val_type;
if (!(val_type = malloc_internal(sizeof(wasm_valtype_t)))) {
return NULL;
}
val_type->kind = kind;
return val_type;
}
void
wasm_valtype_delete(wasm_valtype_t *val_type)
{
FREEIF(val_type);
}
wasm_valtype_t *
wasm_valtype_copy(const wasm_valtype_t *src)
{
if (!src) {
return NULL;
}
return wasm_valtype_new(src->kind);
}
wasm_valkind_t
wasm_valtype_kind(const wasm_valtype_t *val_type)
{
if (!val_type) {
return WASM_ANYREF;
}
return val_type->kind;
}
bool
wasm_valtype_same(const wasm_valtype_t *vt1, const wasm_valtype_t *vt2)
{
if (!vt1 && !vt2) {
return true;
}
if (!vt1 || !vt2) {
return false;
}
return vt1->kind == vt2->kind;
}
static wasm_functype_t *
wasm_functype_new_internal(WASMType *type_rt)
{
wasm_functype_t *type = NULL;
wasm_valtype_t *param_type = NULL, *result_type = NULL;
uint32 i = 0;
if (!type_rt) {
return NULL;
}
if (!(type = malloc_internal(sizeof(wasm_functype_t)))) {
return NULL;
}
type->extern_kind = WASM_EXTERN_FUNC;
/* WASMType->types[0 : type_rt->param_count) -> type->params */
INIT_VEC(type->params, wasm_valtype_vec_new_uninitialized,
type_rt->param_count);
for (i = 0; i < type_rt->param_count; ++i) {
if (!(param_type = wasm_valtype_new_internal(*(type_rt->types + i)))) {
goto failed;
}
if (!bh_vector_append((Vector *)type->params, ¶m_type)) {
LOG_DEBUG("bh_vector_append failed");
goto failed;
}
}
/* WASMType->types[type_rt->param_count : type_rt->result_count) -> type->results */
INIT_VEC(type->results, wasm_valtype_vec_new_uninitialized,
type_rt->result_count);
for (i = 0; i < type_rt->result_count; ++i) {
if (!(result_type = wasm_valtype_new_internal(
*(type_rt->types + type_rt->param_count + i)))) {
goto failed;
}
if (!bh_vector_append((Vector *)type->results, &result_type)) {
LOG_DEBUG("bh_vector_append failed");
goto failed;
}
}
return type;
failed:
wasm_valtype_delete(param_type);
wasm_valtype_delete(result_type);
wasm_functype_delete(type);
return NULL;
}
wasm_functype_t *
wasm_functype_new(own wasm_valtype_vec_t *params,
own wasm_valtype_vec_t *results)
{
wasm_functype_t *type = NULL;
if (!params) {
return NULL;
}
if (!results) {
return NULL;
}
if (!(type = malloc_internal(sizeof(wasm_functype_t)))) {
goto failed;
}
type->extern_kind = WASM_EXTERN_FUNC;
/* take ownership */
if (!(type->params = malloc_internal(sizeof(wasm_valtype_vec_t)))) {
goto failed;
}
bh_memcpy_s(type->params, sizeof(wasm_valtype_vec_t), params,
sizeof(wasm_valtype_vec_t));
if (!(type->results = malloc_internal(sizeof(wasm_valtype_vec_t)))) {
goto failed;
}
bh_memcpy_s(type->results, sizeof(wasm_valtype_vec_t), results,
sizeof(wasm_valtype_vec_t));
return type;
failed:
wasm_functype_delete(type);
return NULL;
}
wasm_functype_t *
wasm_functype_copy(const wasm_functype_t *src)
{
wasm_functype_t *functype;
wasm_valtype_vec_t params = { 0 }, results = { 0 };
if (!src) {
return NULL;
}
wasm_valtype_vec_copy(¶ms, src->params);
if (src->params->size && !params.data) {
goto failed;
}
wasm_valtype_vec_copy(&results, src->results);
if (src->results->size && !results.data) {
goto failed;
}
if (!(functype = wasm_functype_new(¶ms, &results))) {
goto failed;
}
return functype;
failed:
wasm_valtype_vec_delete(¶ms);
wasm_valtype_vec_delete(&results);
return NULL;
}
void
wasm_functype_delete(wasm_functype_t *func_type)
{
if (!func_type) {
return;
}
DEINIT_VEC(func_type->params, wasm_valtype_vec_delete);
DEINIT_VEC(func_type->results, wasm_valtype_vec_delete);
wasm_runtime_free(func_type);
}
const wasm_valtype_vec_t *
wasm_functype_params(const wasm_functype_t *func_type)
{
if (!func_type) {
return NULL;
}
return func_type->params;
}
const wasm_valtype_vec_t *
wasm_functype_results(const wasm_functype_t *func_type)
{
if (!func_type) {
return NULL;
}
return func_type->results;
}
wasm_globaltype_t *
wasm_globaltype_new(own wasm_valtype_t *val_type, wasm_mutability_t mut)
{
wasm_globaltype_t *global_type = NULL;
if (!val_type) {
return NULL;
}
if (!(global_type = malloc_internal(sizeof(wasm_globaltype_t)))) {
return NULL;
}
global_type->extern_kind = WASM_EXTERN_GLOBAL;
global_type->val_type = val_type;
global_type->mutability = mut;
return global_type;
}
wasm_globaltype_t *
wasm_globaltype_new_internal(uint8 val_type_rt, bool is_mutable)
{
wasm_globaltype_t *globaltype;
wasm_valtype_t *val_type;
if (!(val_type = wasm_valtype_new(val_type_rt_2_valkind(val_type_rt)))) {
return NULL;
}
if (!(globaltype = wasm_globaltype_new(
val_type, is_mutable ? WASM_VAR : WASM_CONST))) {
wasm_valtype_delete(val_type);
}
return globaltype;
}
void
wasm_globaltype_delete(wasm_globaltype_t *global_type)
{
if (!global_type) {
return;
}
if (global_type->val_type) {
wasm_valtype_delete(global_type->val_type);
global_type->val_type = NULL;
}
wasm_runtime_free(global_type);
}
wasm_globaltype_t *
wasm_globaltype_copy(const wasm_globaltype_t *src)
{
wasm_globaltype_t *global_type;
wasm_valtype_t *val_type;
if (!src) {
return NULL;
}
if (!(val_type = wasm_valtype_copy(src->val_type))) {
return NULL;
}
if (!(global_type = wasm_globaltype_new(val_type, src->mutability))) {
wasm_valtype_delete(val_type);
}
return global_type;
}
const wasm_valtype_t *
wasm_globaltype_content(const wasm_globaltype_t *global_type)
{
if (!global_type) {
return NULL;
}
return global_type->val_type;
}
wasm_mutability_t
wasm_globaltype_mutability(const wasm_globaltype_t *global_type)
{
if (!global_type) {
return false;
}
return global_type->mutability;
}
bool
wasm_globaltype_same(const wasm_globaltype_t *gt1,
const wasm_globaltype_t *gt2)
{
if (!gt1 && !gt2) {
return true;
}
if (!gt1 || !gt2) {
return false;
}
return wasm_valtype_same(gt1->val_type, gt2->val_type)
|| gt1->mutability == gt2->mutability;
}
static wasm_tabletype_t *
wasm_tabletype_new_internal(uint8 val_type_rt,
uint32 init_size,
uint32 max_size)
{
wasm_tabletype_t *table_type;
wasm_limits_t limits = { init_size, max_size };
wasm_valtype_t *val_type;
if (!(val_type = wasm_valtype_new_internal(val_type_rt))) {
return NULL;
}
if (!(table_type = wasm_tabletype_new(val_type, &limits))) {
wasm_valtype_delete(val_type);
}
return table_type;
}
wasm_tabletype_t *
wasm_tabletype_new(own wasm_valtype_t *val_type, const wasm_limits_t *limits)
{
wasm_tabletype_t *table_type = NULL;
if (!val_type) {
return NULL;
}
if (!(table_type = malloc_internal(sizeof(wasm_tabletype_t)))) {
return NULL;
}
table_type->extern_kind = WASM_EXTERN_TABLE;
table_type->val_type = val_type;
table_type->limits.min = limits->min;
table_type->limits.max = limits->max;
return table_type;
}
wasm_tabletype_t *
wasm_tabletype_copy(const wasm_tabletype_t *src)
{
wasm_tabletype_t *table_type;
wasm_valtype_t *val_type;
if (!src) {
return NULL;
}
if (!(val_type = wasm_valtype_copy(src->val_type))) {
return NULL;
}
if (!(table_type = wasm_tabletype_new(val_type, &src->limits))) {
wasm_valtype_delete(val_type);
}
return table_type;
}
void
wasm_tabletype_delete(wasm_tabletype_t *table_type)
{
if (!table_type) {
return;
}
if (table_type->val_type) {
wasm_valtype_delete(table_type->val_type);
table_type->val_type = NULL;
}
wasm_runtime_free(table_type);
}
const wasm_valtype_t *
wasm_tabletype_element(const wasm_tabletype_t *table_type)
{
if (!table_type) {
return NULL;
}
return table_type->val_type;
}
const wasm_limits_t *
wasm_tabletype_limits(const wasm_tabletype_t *table_type)
{
if (!table_type) {
return NULL;
}
return &(table_type->limits);
}
static wasm_memorytype_t *
wasm_memorytype_new_internal(uint32 min_pages, uint32 max_pages)
{
wasm_limits_t limits = { min_pages, max_pages };
return wasm_memorytype_new(&limits);
}
wasm_memorytype_t *
wasm_memorytype_new(const wasm_limits_t *limits)
{
wasm_memorytype_t *memory_type = NULL;
if (!limits) {
return NULL;
}
if (!(memory_type = malloc_internal(sizeof(wasm_memorytype_t)))) {
return NULL;
}
memory_type->extern_kind = WASM_EXTERN_MEMORY;
memory_type->limits.min = limits->min;
memory_type->limits.max = limits->max;
return memory_type;
}
wasm_memorytype_t *
wasm_memorytype_copy(const wasm_memorytype_t *src)
{
if (!src) {
return NULL;
}
return wasm_memorytype_new(&src->limits);
}
void
wasm_memorytype_delete(wasm_memorytype_t *memory_type)
{
FREEIF(memory_type);
}
const wasm_limits_t *
wasm_memorytype_limits(const wasm_memorytype_t *memory_type)
{
if (!memory_type) {
return NULL;
}
return &(memory_type->limits);
}
wasm_externkind_t
wasm_externtype_kind(const wasm_externtype_t *extern_type)
{
if (!extern_type) {
return WASM_EXTERN_FUNC;
}
return extern_type->extern_kind;
}
#define BASIC_FOUR_TYPE_LIST(V) \
V(functype) \
V(globaltype) \
V(memorytype) \
V(tabletype)
#define WASM_EXTERNTYPE_AS_OTHERTYPE(name) \
wasm_##name##_t *wasm_externtype_as_##name( \
wasm_externtype_t *extern_type) \
{ \
return (wasm_##name##_t *)extern_type; \
}
BASIC_FOUR_TYPE_LIST(WASM_EXTERNTYPE_AS_OTHERTYPE)
#undef WASM_EXTERNTYPE_AS_OTHERTYPE
#define WASM_OTHERTYPE_AS_EXTERNTYPE(name) \
wasm_externtype_t *wasm_##name##_as_externtype(wasm_##name##_t *other) \
{ \
return (wasm_externtype_t *)other; \
}
BASIC_FOUR_TYPE_LIST(WASM_OTHERTYPE_AS_EXTERNTYPE)
#undef WASM_OTHERTYPE_AS_EXTERNTYPE
#define WASM_EXTERNTYPE_AS_OTHERTYPE_CONST(name) \
const wasm_##name##_t *wasm_externtype_as_##name##_const( \
const wasm_externtype_t *extern_type) \
{ \
return (const wasm_##name##_t *)extern_type; \
}
BASIC_FOUR_TYPE_LIST(WASM_EXTERNTYPE_AS_OTHERTYPE_CONST)
#undef WASM_EXTERNTYPE_AS_OTHERTYPE_CONST
#define WASM_OTHERTYPE_AS_EXTERNTYPE_CONST(name) \
const wasm_externtype_t *wasm_##name##_as_externtype_const( \
const wasm_##name##_t *other) \
{ \
return (const wasm_externtype_t *)other; \
}
BASIC_FOUR_TYPE_LIST(WASM_OTHERTYPE_AS_EXTERNTYPE_CONST)
#undef WASM_OTHERTYPE_AS_EXTERNTYPE_CONST
wasm_externtype_t *
wasm_externtype_copy(const wasm_externtype_t *src)
{
wasm_externtype_t *extern_type = NULL;
if (!src) {
return NULL;
}
switch (src->extern_kind) {
#define COPY_EXTERNTYPE(NAME, name) \
case WASM_EXTERN_##NAME: \
{ \
extern_type = wasm_##name##_as_externtype( \
wasm_##name##_copy(wasm_externtype_as_##name##_const(src))); \
break; \
}
COPY_EXTERNTYPE(FUNC, functype)
COPY_EXTERNTYPE(GLOBAL, globaltype)
COPY_EXTERNTYPE(MEMORY, memorytype)
COPY_EXTERNTYPE(TABLE, tabletype)
#undef COPY_EXTERNTYPE
default:
LOG_WARNING("%s meets unsupported kind", __FUNCTION__,
src->extern_kind);
break;
}
return extern_type;
}
void
wasm_externtype_delete(wasm_externtype_t *extern_type)
{
if (!extern_type) {
return;
}
switch (wasm_externtype_kind(extern_type)) {
case WASM_EXTERN_FUNC:
wasm_functype_delete(wasm_externtype_as_functype(extern_type));
break;
case WASM_EXTERN_GLOBAL:
wasm_globaltype_delete(wasm_externtype_as_globaltype(extern_type));
break;
case WASM_EXTERN_MEMORY:
wasm_memorytype_delete(wasm_externtype_as_memorytype(extern_type));
break;
case WASM_EXTERN_TABLE:
wasm_tabletype_delete(wasm_externtype_as_tabletype(extern_type));
break;
default:
LOG_WARNING("%s meets unsupported type", __FUNCTION__,
extern_type);
break;
}
}
own wasm_importtype_t *
wasm_importtype_new(own wasm_byte_vec_t *module_name,
own wasm_byte_vec_t *field_name,
own wasm_externtype_t *extern_type)
{
wasm_importtype_t *import_type = NULL;
if (!(import_type = malloc_internal(sizeof(wasm_importtype_t)))) {
return NULL;
}
/* take ownership */
if (!(import_type->module_name =
malloc_internal(sizeof(wasm_byte_vec_t)))) {
goto failed;
}
bh_memcpy_s(import_type->module_name, sizeof(wasm_byte_vec_t), module_name,
sizeof(wasm_byte_vec_t));
if (!(import_type->name = malloc_internal(sizeof(wasm_byte_vec_t)))) {
goto failed;
}
bh_memcpy_s(import_type->name, sizeof(wasm_byte_vec_t), field_name,
sizeof(wasm_byte_vec_t));
import_type->extern_type = extern_type;
return import_type;
failed:
wasm_importtype_delete(import_type);
return NULL;
}
void
wasm_importtype_delete(own wasm_importtype_t *import_type)
{
if (!import_type) {
return;
}
DEINIT_VEC(import_type->module_name, wasm_byte_vec_delete);
DEINIT_VEC(import_type->name, wasm_byte_vec_delete);
wasm_externtype_delete(import_type->extern_type);
wasm_runtime_free(import_type);
}
own wasm_importtype_t *
wasm_importtype_copy(const wasm_importtype_t *src)
{
wasm_byte_vec_t module_name = { 0 }, name = { 0 };
wasm_externtype_t *extern_type = NULL;
wasm_importtype_t *import_type = NULL;
if (!src) {
return NULL;
}
wasm_byte_vec_copy(&module_name, src->module_name);
if (src->module_name->size && !module_name.data) {
goto failed;
}
wasm_byte_vec_copy(&name, src->name);
if (src->name->size && !name.data) {
goto failed;
}
if (!(extern_type = wasm_externtype_copy(src->extern_type))) {
goto failed;
}
if (!(import_type =
wasm_importtype_new(&module_name, &name, extern_type))) {
goto failed;
}
return import_type;
failed:
wasm_byte_vec_delete(&module_name);
wasm_byte_vec_delete(&name);
wasm_externtype_delete(extern_type);
wasm_importtype_delete(import_type);
return NULL;
}
const wasm_byte_vec_t *
wasm_importtype_module(const wasm_importtype_t *import_type)
{
if (!import_type) {
return NULL;
}
return import_type->module_name;
}
const wasm_byte_vec_t *
wasm_importtype_name(const wasm_importtype_t *import_type)
{
if (!import_type) {
return NULL;
}
return import_type->name;
}
const wasm_externtype_t *
wasm_importtype_type(const wasm_importtype_t *import_type)
{
if (!import_type) {
return NULL;
}
return import_type->extern_type;
}
own wasm_exporttype_t *
wasm_exporttype_new(own wasm_byte_vec_t *name,
own wasm_externtype_t *extern_type)
{
wasm_exporttype_t *export_type = NULL;
if (!(export_type = malloc_internal(sizeof(wasm_exporttype_t)))) {
return NULL;
}
if (!(export_type->name = malloc_internal(sizeof(wasm_byte_vec_t)))) {
wasm_exporttype_delete(export_type);
return NULL;
}
bh_memcpy_s(export_type->name, sizeof(wasm_byte_vec_t), name,
sizeof(wasm_byte_vec_t));
export_type->extern_type = extern_type;
return export_type;
}
wasm_exporttype_t *
wasm_exporttype_copy(const wasm_exporttype_t *src)
{
wasm_exporttype_t *export_type;
wasm_byte_vec_t name = { 0 };
wasm_externtype_t *extern_type = NULL;
if (!src) {
return NULL;
}
wasm_byte_vec_copy(&name, src->name);
if (src->name->size && !name.data) {
goto failed;
}
if (!(extern_type = wasm_externtype_copy(src->extern_type))) {
goto failed;
}
if (!(export_type = wasm_exporttype_new(&name, extern_type))) {
goto failed;
}
return export_type;
failed:
wasm_byte_vec_delete(&name);
wasm_externtype_delete(extern_type);
return NULL;
}
void
wasm_exporttype_delete(wasm_exporttype_t *export_type)
{
if (!export_type) {
return;
}
DEINIT_VEC(export_type->name, wasm_byte_vec_delete);
wasm_externtype_delete(export_type->extern_type);
wasm_runtime_free(export_type);
}
const wasm_byte_vec_t *
wasm_exporttype_name(const wasm_exporttype_t *export_type)
{
if (!export_type) {
return NULL;
}
return export_type->name;
}
const wasm_externtype_t *
wasm_exporttype_type(const wasm_exporttype_t *export_type)
{
if (!export_type) {
return NULL;
}
return export_type->extern_type;
}
/* Runtime Objects */
void
wasm_val_delete(wasm_val_t *v)
{
FREEIF(v);
}
void
wasm_val_copy(wasm_val_t *out, const wasm_val_t *src)
{
if (!out || !src) {
return;
}
bh_memcpy_s(out, sizeof(wasm_val_t), src, sizeof(wasm_val_t));
}
bool
wasm_val_same(const wasm_val_t *v1, const wasm_val_t *v2)
{
if (!v1 && !v2) {
return true;
}
if (!v1 || !v2) {
return false;
}
if (v1->kind != v2->kind) {
return false;
}
switch (v1->kind) {
case WASM_I32:
return v1->of.i32 == v2->of.i32;
case WASM_I64:
return v1->of.i64 == v2->of.i64;
case WASM_F32:
return v1->of.f32 == v2->of.f32;
case WASM_F64:
return v1->of.f64 == v2->of.f64;
case WASM_FUNCREF:
return v1->of.ref == v2->of.ref;
default:
break;
}
return false;
}
static wasm_frame_t *
wasm_frame_new(wasm_instance_t *instance,
size_t module_offset,
uint32 func_index,
size_t func_offset)
{
wasm_frame_t *frame;
if (!(frame = malloc_internal(sizeof(wasm_frame_t)))) {
return NULL;
}
frame->instance = instance;
frame->module_offset = module_offset;
frame->func_index = func_index;
frame->func_offset = func_offset;
return frame;
}
own wasm_frame_t *
wasm_frame_copy(const wasm_frame_t *src)
{
if (!src) {
return NULL;
}
return wasm_frame_new(src->instance, src->module_offset, src->func_index,
src->func_offset);
}
void
wasm_frame_delete(own wasm_frame_t *frame)
{
if (!frame) {
return;
}
wasm_runtime_free(frame);
}
struct wasm_instance_t *
wasm_frame_instance(const wasm_frame_t *frame)
{
return frame ? frame->instance : NULL;
}
size_t
wasm_frame_module_offset(const wasm_frame_t *frame)
{
return frame ? frame->module_offset : 0;
}
uint32_t
wasm_frame_func_index(const wasm_frame_t *frame)
{
return frame ? frame->func_index : 0;
}
size_t
wasm_frame_func_offset(const wasm_frame_t *frame)
{
return frame ? frame->func_offset : 0;
}
static wasm_trap_t *
wasm_trap_new_internal(WASMModuleInstanceCommon *inst_comm_rt,
const char *default_error_info)
{
wasm_trap_t *trap;
const char *error_info = NULL;
wasm_instance_vec_t *instances;
wasm_instance_t *frame_instance = NULL;
uint32 i;
if (!singleton_engine || !singleton_engine->stores
|| !singleton_engine->stores->num_elems) {
return NULL;
}
#if WASM_ENABLE_INTERP != 0
if (inst_comm_rt->module_type == Wasm_Module_Bytecode) {
if (!(error_info =
wasm_get_exception((WASMModuleInstance *)inst_comm_rt))) {
return NULL;
}
}
#endif
#if WASM_ENABLE_AOT != 0
if (inst_comm_rt->module_type == Wasm_Module_AoT) {
if (!(error_info =
aot_get_exception((AOTModuleInstance *)inst_comm_rt))) {
return NULL;
}
}
#endif
if (!error_info && !(error_info = default_error_info)) {
return NULL;
}
if (!(trap = malloc_internal(sizeof(wasm_trap_t)))) {
return NULL;
}
if (!(trap->message = malloc_internal(sizeof(wasm_byte_vec_t)))) {
goto failed;
}
wasm_name_new_from_string_nt(trap->message, error_info);
if (strlen(error_info) && !trap->message->data) {
goto failed;
}
#if WASM_ENABLE_DUMP_CALL_STACK != 0
#if WASM_ENABLE_INTERP != 0
if (inst_comm_rt->module_type == Wasm_Module_Bytecode) {
trap->frames = ((WASMModuleInstance *)inst_comm_rt)->frames;
}
#endif
#endif /* WASM_ENABLE_DUMP_CALL_STACK != 0 */
/* allow a NULL frames list */
if (!trap->frames) {
return trap;
}
if (!(instances = singleton_engine->stores->data[0]->instances)) {
goto failed;
}
for (i = 0; i < instances->num_elems; i++) {
if (instances->data[i]->inst_comm_rt == inst_comm_rt) {
frame_instance = instances->data[i];
break;
}
}
for (i = 0; i < trap->frames->num_elems; i++) {
(((wasm_frame_t *)trap->frames->data) + i)->instance = frame_instance;
}
return trap;
failed:
wasm_trap_delete(trap);
return NULL;
}
wasm_trap_t *
wasm_trap_new(wasm_store_t *store, const wasm_message_t *message)
{
wasm_trap_t *trap;
if (!store || !message) {
return NULL;
}
if (!(trap = malloc_internal(sizeof(wasm_trap_t)))) {
return NULL;
}
INIT_VEC(trap->message, wasm_byte_vec_new, message->size, message->data);
return trap;
failed:
wasm_trap_delete(trap);
return NULL;
}
void
wasm_trap_delete(wasm_trap_t *trap)
{
if (!trap) {
return;
}
DEINIT_VEC(trap->message, wasm_byte_vec_delete);
/* reuse frames of WASMModuleInstance, do not free it here */
wasm_runtime_free(trap);
}
void
wasm_trap_message(const wasm_trap_t *trap, own wasm_message_t *out)
{
if (!trap || !out) {
return;
}
wasm_byte_vec_copy(out, trap->message);
}
own wasm_frame_t *
wasm_trap_origin(const wasm_trap_t *trap)
{
wasm_frame_t *latest_frame;
if (!trap || !trap->frames || !trap->frames->num_elems) {
return NULL;
}
/* first frame is the latest frame */
latest_frame = (wasm_frame_t *)trap->frames->data;
return wasm_frame_copy(latest_frame);
}
void
wasm_trap_trace(const wasm_trap_t *trap, own wasm_frame_vec_t *out)
{
uint32 i;
if (!trap || !out) {
return;
}
if (!trap->frames || !trap->frames->num_elems) {
wasm_frame_vec_new_empty(out);
return;
}
wasm_frame_vec_new_uninitialized(out, trap->frames->num_elems);
if (out->size && !out->data) {
return;
}
for (i = 0; i < trap->frames->num_elems; i++) {
wasm_frame_t *frame;
frame = ((wasm_frame_t *)trap->frames->data) + i;
if (!(out->data[i] =
wasm_frame_new(frame->instance, frame->module_offset,
frame->func_index, frame->func_offset))) {
goto failed;
}
out->num_elems++;
}
return;
failed:
for (i = 0; i < out->num_elems; i++) {
if (out->data[i]) {
wasm_runtime_free(out->data[i]);
}
}
if (out->data) {
wasm_runtime_free(out->data);
}
}
struct wasm_module_ex_t {
struct WASMModuleCommon *module_comm_rt;
wasm_byte_vec_t *binary;
};
static inline wasm_module_t *
module_ext_to_module(wasm_module_ex_t *module_ex)
{
return (wasm_module_t *)module_ex;
}
static inline wasm_module_ex_t *
module_to_module_ext(wasm_module_t *module)
{
return (wasm_module_ex_t *)module;
}
#if WASM_ENABLE_INTERP != 0
#define MODULE_INTERP(module) ((WASMModule *)(*module))
#endif
#if WASM_ENABLE_AOT != 0
#define MODULE_AOT(module) ((AOTModule *)(*module))
#endif
wasm_module_t *
wasm_module_new(wasm_store_t *store, const wasm_byte_vec_t *binary)
{
char error_buf[128] = { 0 };
wasm_module_ex_t *module_ex = NULL;
#if WASM_ENABLE_AOT != 0 && WASM_ENABLE_JIT != 0
uint8 *aot_file_buf = NULL;
uint32 aot_file_size;
#endif
bh_assert(singleton_engine);
if (!store || !binary || binary->size > UINT32_MAX) {
LOG_ERROR("%s failed", __FUNCTION__);
return NULL;
}
module_ex = malloc_internal(sizeof(wasm_module_ex_t));
if (!module_ex) {
goto failed;
}
INIT_VEC(module_ex->binary, wasm_byte_vec_new, binary->size, binary->data);
#if WASM_ENABLE_AOT != 0 && WASM_ENABLE_JIT != 0
if (get_package_type((uint8 *)module_ex->binary->data,
(uint32)module_ex->binary->size)
== Wasm_Module_Bytecode) {
if (!(aot_file_buf = aot_compile_wasm_file(
(uint8 *)module_ex->binary->data,
(uint32)module_ex->binary->size, 3, 3, error_buf,
(uint32)sizeof(error_buf), &aot_file_size))) {
LOG_ERROR(error_buf);
goto failed;
}
if (!(module_ex->module_comm_rt =
wasm_runtime_load(aot_file_buf, aot_file_size, error_buf,
(uint32)sizeof(error_buf)))) {
LOG_ERROR(error_buf);
goto failed;
}
}
else
#endif
{
module_ex->module_comm_rt = wasm_runtime_load(
(uint8 *)module_ex->binary->data, (uint32)module_ex->binary->size,
error_buf, (uint32)sizeof(error_buf));
if (!(module_ex->module_comm_rt)) {
LOG_ERROR(error_buf);
goto failed;
}
}
/* add it to a watching list in store */
if (!bh_vector_append((Vector *)store->modules, &module_ex)) {
goto failed;
}
return module_ext_to_module(module_ex);
failed:
LOG_ERROR("%s failed", __FUNCTION__);
wasm_module_delete_internal(module_ext_to_module(module_ex));
return NULL;
}
static void
wasm_module_delete_internal(wasm_module_t *module)
{
wasm_module_ex_t *module_ex;
if (!module) {
return;
}
module_ex = module_to_module_ext(module);
DEINIT_VEC(module_ex->binary, wasm_byte_vec_delete);
if (module_ex->module_comm_rt) {
wasm_runtime_unload(module_ex->module_comm_rt);
module_ex->module_comm_rt = NULL;
}
wasm_runtime_free(module_ex);
}
void
wasm_module_delete(wasm_module_t *module)
{
/* the module will be released when releasing the store */
}
void
wasm_module_imports(const wasm_module_t *module,
own wasm_importtype_vec_t *out)
{
uint32 i, import_func_count = 0, import_memory_count = 0,
import_global_count = 0, import_table_count = 0,
import_count = 0;
wasm_byte_vec_t module_name = { 0 }, name = { 0 };
wasm_externtype_t *extern_type = NULL;
wasm_importtype_t *import_type = NULL;
if (!module || !out || !valid_module_type((*module)->module_type)) {
return;
}
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
import_func_count = MODULE_INTERP(module)->import_function_count;
import_global_count = MODULE_INTERP(module)->import_global_count;
import_memory_count = MODULE_INTERP(module)->import_memory_count;
import_table_count = MODULE_INTERP(module)->import_table_count;
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
import_func_count = MODULE_AOT(module)->import_func_count;
import_global_count = MODULE_AOT(module)->import_global_count;
import_memory_count = MODULE_AOT(module)->import_memory_count;
import_table_count = MODULE_AOT(module)->import_table_count;
}
#endif
import_count = import_func_count + import_global_count + import_table_count
+ import_memory_count;
wasm_importtype_vec_new_uninitialized(out, import_count);
if (import_count && !out->data) {
return;
}
for (i = 0; i != import_count; ++i) {
char *module_name_rt = NULL, *field_name_rt = NULL;
if (i < import_func_count) {
wasm_functype_t *type = NULL;
WASMType *type_rt = NULL;
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
WASMImport *import =
MODULE_INTERP(module)->import_functions + i;
module_name_rt = import->u.names.module_name;
field_name_rt = import->u.names.field_name;
type_rt = import->u.function.func_type;
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
AOTImportFunc *import = MODULE_AOT(module)->import_funcs + i;
module_name_rt = import->module_name;
field_name_rt = import->func_name;
type_rt = import->func_type;
}
#endif
if (!module_name_rt || !field_name_rt || !type_rt) {
continue;
}
wasm_name_new_from_string(&module_name, module_name_rt);
if (strlen(module_name_rt) && !module_name.data) {
goto failed;
}
wasm_name_new_from_string(&name, field_name_rt);
if (strlen(field_name_rt) && !name.data) {
goto failed;
}
if (!(type = wasm_functype_new_internal(type_rt))) {
goto failed;
}
extern_type = wasm_functype_as_externtype(type);
}
else if (i < import_func_count + import_global_count) {
wasm_globaltype_t *type = NULL;
uint8 val_type_rt = 0;
bool mutability_rt = 0;
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
WASMImport *import = MODULE_INTERP(module)->import_globals
+ (i - import_func_count);
module_name_rt = import->u.names.module_name;
field_name_rt = import->u.names.field_name;
val_type_rt = import->u.global.type;
mutability_rt = import->u.global.is_mutable;
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
AOTImportGlobal *import =
MODULE_AOT(module)->import_globals + (i - import_func_count);
module_name_rt = import->module_name;
field_name_rt = import->global_name;
val_type_rt = import->type;
mutability_rt = import->is_mutable;
}
#endif
if (!module_name_rt || !field_name_rt) {
continue;
}
if (!(type = wasm_globaltype_new_internal(val_type_rt,
mutability_rt))) {
goto failed;
}
extern_type = wasm_globaltype_as_externtype(type);
}
else if (i < import_func_count + import_global_count
+ import_memory_count) {
wasm_memorytype_t *type = NULL;
uint32 min_page = 0, max_page = 0;
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
WASMImport *import =
MODULE_INTERP(module)->import_memories
+ (i - import_func_count - import_global_count);
module_name_rt = import->u.names.module_name;
field_name_rt = import->u.names.field_name;
min_page = import->u.memory.init_page_count;
max_page = import->u.memory.max_page_count;
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
AOTImportMemory *import =
MODULE_AOT(module)->import_memories
+ (i - import_func_count - import_global_count);
module_name_rt = import->module_name;
field_name_rt = import->memory_name;
min_page = import->mem_init_page_count;
max_page = import->mem_max_page_count;
}
#endif
if (!module_name_rt || !field_name_rt) {
continue;
}
wasm_name_new_from_string(&module_name, module_name_rt);
if (strlen(module_name_rt) && !module_name.data) {
goto failed;
}
wasm_name_new_from_string(&name, field_name_rt);
if (strlen(field_name_rt) && !name.data) {
goto failed;
}
if (!(type = wasm_memorytype_new_internal(min_page, max_page))) {
goto failed;
}
extern_type = wasm_memorytype_as_externtype(type);
}
else {
wasm_tabletype_t *type = NULL;
uint8 elem_type_rt = 0;
uint32 min_size = 0, max_size = 0;
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
WASMImport *import =
MODULE_INTERP(module)->import_tables
+ (i - import_func_count - import_global_count
- import_memory_count);
module_name_rt = import->u.names.module_name;
field_name_rt = import->u.names.field_name;
elem_type_rt = import->u.table.elem_type;
min_size = import->u.table.init_size;
max_size = import->u.table.max_size;
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
AOTImportTable *import =
MODULE_AOT(module)->import_tables
+ (i - import_func_count - import_global_count
- import_memory_count);
module_name_rt = import->module_name;
field_name_rt = import->table_name;
elem_type_rt = VALUE_TYPE_FUNCREF;
min_size = import->table_init_size;
max_size = import->table_max_size;
}
#endif
if (!module_name_rt || !field_name_rt) {
continue;
}
if (!(type = wasm_tabletype_new_internal(elem_type_rt, min_size,
max_size))) {
goto failed;
}
extern_type = wasm_tabletype_as_externtype(type);
}
if (!extern_type) {
continue;
}
if (!(import_type =
wasm_importtype_new(&module_name, &name, extern_type))) {
goto failed;
}
if (!bh_vector_append((Vector *)out, &import_type)) {
goto failed_importtype_new;
}
}
return;
failed:
wasm_byte_vec_delete(&module_name);
wasm_byte_vec_delete(&name);
wasm_externtype_delete(extern_type);
failed_importtype_new:
wasm_importtype_delete(import_type);
wasm_importtype_vec_delete(out);
}
void
wasm_module_exports(const wasm_module_t *module, wasm_exporttype_vec_t *out)
{
uint32 i, export_count = 0;
wasm_byte_vec_t name = { 0 };
wasm_externtype_t *extern_type = NULL;
wasm_exporttype_t *export_type = NULL;
if (!module || !out || !valid_module_type((*module)->module_type)) {
return;
}
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
export_count = MODULE_INTERP(module)->export_count;
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
export_count = MODULE_AOT(module)->export_count;
}
#endif
wasm_exporttype_vec_new_uninitialized(out, export_count);
if (export_count && !out->data) {
return;
}
for (i = 0; i != export_count; i++) {
WASMExport *export = NULL;
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
export = MODULE_INTERP(module)->exports + i;
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
export = MODULE_AOT(module)->exports + i;
}
#endif
if (!export) {
continue;
}
/* byte* -> wasm_byte_vec_t */
wasm_name_new_from_string(&name, export->name);
if (strlen(export->name) && !name.data) {
goto failed;
}
/* WASMExport -> (WASMType, (uint8, bool)) -> (wasm_functype_t, wasm_globaltype_t) -> wasm_externtype_t*/
switch (export->kind) {
case EXPORT_KIND_FUNC:
{
wasm_functype_t *type = NULL;
WASMType *type_rt;
if (!wasm_runtime_get_export_func_type(*module, export,
&type_rt)) {
goto failed;
}
if (!(type = wasm_functype_new_internal(type_rt))) {
goto failed;
}
extern_type = wasm_functype_as_externtype(type);
break;
}
case EXPORT_KIND_GLOBAL:
{
wasm_globaltype_t *type = NULL;
uint8 val_type_rt = 0;
bool mutability_rt = 0;
if (!wasm_runtime_get_export_global_type(
*module, export, &val_type_rt, &mutability_rt)) {
goto failed;
}
if (!(type = wasm_globaltype_new_internal(val_type_rt,
mutability_rt))) {
goto failed;
}
extern_type = wasm_globaltype_as_externtype(type);
break;
}
case EXPORT_KIND_MEMORY:
{
wasm_memorytype_t *type = NULL;
uint32 min_page = 0, max_page = 0;
if (!wasm_runtime_get_export_memory_type(
*module, export, &min_page, &max_page)) {
goto failed;
}
if (!(type =
wasm_memorytype_new_internal(min_page, max_page))) {
goto failed;
}
extern_type = wasm_memorytype_as_externtype(type);
break;
}
case EXPORT_KIND_TABLE:
{
wasm_tabletype_t *type = NULL;
uint8 elem_type_rt = 0;
uint32 min_size = 0, max_size = 0;
if (!wasm_runtime_get_export_table_type(
*module, export, &elem_type_rt, &min_size, &max_size)) {
goto failed;
}
if (!(type = wasm_tabletype_new_internal(
elem_type_rt, min_size, max_size))) {
goto failed;
}
extern_type = wasm_tabletype_as_externtype(type);
break;
}
default:
{
LOG_WARNING("%s meets unsupported type", __FUNCTION__,
export->kind);
break;
}
}
if (!(export_type = wasm_exporttype_new(&name, extern_type))) {
goto failed;
}
if (!(bh_vector_append((Vector *)out, &export_type))) {
goto failed_exporttype_new;
}
}
return;
failed:
wasm_byte_vec_delete(&name);
wasm_externtype_delete(extern_type);
failed_exporttype_new:
wasm_exporttype_delete(export_type);
wasm_exporttype_vec_delete(out);
}
static wasm_func_t *
wasm_func_new_basic(const wasm_functype_t *type,
wasm_func_callback_t func_callback)
{
wasm_func_t *func = NULL;
if (!(func = malloc_internal(sizeof(wasm_func_t)))) {
goto failed;
}
func->kind = WASM_EXTERN_FUNC;
func->with_env = false;
func->u.cb = func_callback;
if (!(func->type = wasm_functype_copy(type))) {
goto failed;
}
RETURN_OBJ(func, wasm_func_delete)
}
static wasm_func_t *
wasm_func_new_with_env_basic(const wasm_functype_t *type,
wasm_func_callback_with_env_t callback,
void *env,
void (*finalizer)(void *))
{
wasm_func_t *func = NULL;
if (!(func = malloc_internal(sizeof(wasm_func_t)))) {
goto failed;
}
func->kind = WASM_EXTERN_FUNC;
func->with_env = true;
func->u.cb_env.cb = callback;
func->u.cb_env.env = env;
func->u.cb_env.finalizer = finalizer;
if (!(func->type = wasm_functype_copy(type))) {
goto failed;
}
RETURN_OBJ(func, wasm_func_delete)
}
wasm_func_t *
wasm_func_new(wasm_store_t *store,
const wasm_functype_t *type,
wasm_func_callback_t callback)
{
bh_assert(singleton_engine);
return wasm_func_new_basic(type, callback);
}
wasm_func_t *
wasm_func_new_with_env(wasm_store_t *store,
const wasm_functype_t *type,
wasm_func_callback_with_env_t callback,
void *env,
void (*finalizer)(void *))
{
bh_assert(singleton_engine);
return wasm_func_new_with_env_basic(type, callback, env, finalizer);
}
static wasm_func_t *
wasm_func_new_internal(wasm_store_t *store,
uint16 func_idx_rt,
WASMModuleInstanceCommon *inst_comm_rt)
{
wasm_func_t *func = NULL;
WASMType *type_rt = NULL;
bh_assert(singleton_engine);
if (!inst_comm_rt || !valid_module_type(inst_comm_rt->module_type)) {
return NULL;
}
func = malloc_internal(sizeof(wasm_func_t));
if (!func) {
goto failed;
}
func->kind = WASM_EXTERN_FUNC;
#if WASM_ENABLE_INTERP != 0
if (inst_comm_rt->module_type == Wasm_Module_Bytecode) {
bh_assert(func_idx_rt
< ((WASMModuleInstance *)inst_comm_rt)->function_count);
WASMFunctionInstance *func_interp =
((WASMModuleInstance *)inst_comm_rt)->functions + func_idx_rt;
type_rt = func_interp->is_import_func
? func_interp->u.func_import->func_type
: func_interp->u.func->func_type;
}
#endif
#if WASM_ENABLE_AOT != 0
if (inst_comm_rt->module_type == Wasm_Module_AoT) {
/* use same index to trace the function type in AOTFuncType **func_types */
AOTModule *module_aot =
((AOTModuleInstance *)inst_comm_rt)->aot_module.ptr;
if (func_idx_rt < module_aot->import_func_count) {
type_rt = (module_aot->import_funcs + func_idx_rt)->func_type;
}
else {
type_rt =
module_aot
->func_types[module_aot->func_type_indexes
[func_idx_rt - module_aot->import_func_count]];
}
}
#endif
if (!type_rt) {
goto failed;
}
func->type = wasm_functype_new_internal(type_rt);
if (!func->type) {
goto failed;
}
/* will add name information when processing "exports" */
func->module_name = NULL;
func->name = NULL;
func->func_idx_rt = func_idx_rt;
func->inst_comm_rt = inst_comm_rt;
return func;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
wasm_func_delete(func);
return NULL;
}
void
wasm_func_delete(wasm_func_t *func)
{
if (!func) {
return;
}
if (func->type) {
wasm_functype_delete(func->type);
func->type = NULL;
}
if (func->with_env) {
if (func->u.cb_env.finalizer) {
func->u.cb_env.finalizer(func->u.cb_env.env);
func->u.cb_env.finalizer = NULL;
func->u.cb_env.env = NULL;
}
}
wasm_runtime_free(func);
}
own wasm_func_t *
wasm_func_copy(const wasm_func_t *func)
{
wasm_func_t *cloned = NULL;
if (!func) {
return NULL;
}
if (!(cloned = func->with_env
? wasm_func_new_with_env_basic(
func->type, func->u.cb_env.cb, func->u.cb_env.env,
func->u.cb_env.finalizer)
: wasm_func_new_basic(func->type, func->u.cb))) {
goto failed;
}
cloned->func_idx_rt = func->func_idx_rt;
cloned->inst_comm_rt = func->inst_comm_rt;
RETURN_OBJ(cloned, wasm_func_delete)
}
own wasm_functype_t *
wasm_func_type(const wasm_func_t *func)
{
if (!func) {
return NULL;
}
return wasm_functype_copy(func->type);
}
static uint32
params_to_argv(const wasm_val_t *params,
const wasm_valtype_vec_t *param_defs,
size_t param_arity,
uint32 *out)
{
size_t i = 0;
uint32 argc = 0;
const wasm_val_t *param = NULL;
if (!param_arity) {
return 0;
}
bh_assert(params && param_defs && out);
bh_assert(param_defs->num_elems == param_arity);
for (i = 0; out && i < param_arity; ++i) {
param = params + i;
bh_assert((*(param_defs->data + i))->kind == param->kind);
switch (param->kind) {
case WASM_I32:
*(int32 *)out = param->of.i32;
out += 1;
argc += 1;
break;
case WASM_I64:
*(int64 *)out = param->of.i64;
out += 2;
argc += 2;
break;
case WASM_F32:
*(float32 *)out = param->of.f32;
out += 1;
argc += 1;
break;
case WASM_F64:
*(float64 *)out = param->of.f64;
out += 2;
argc += 2;
break;
default:
LOG_DEBUG("unexpected parameter val type %d", param->kind);
goto failed;
}
}
return argc;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
return 0;
}
static uint32
argv_to_results(const uint32 *results,
const wasm_valtype_vec_t *result_defs,
size_t result_arity,
wasm_val_t *out)
{
size_t i = 0;
uint32 argc = 0;
const uint32 *result = results;
const wasm_valtype_t *def = NULL;
if (!result_arity) {
return 0;
}
bh_assert(results && result_defs && out);
bh_assert(result_arity == result_defs->num_elems);
for (i = 0; out && i < result_arity; i++) {
def = *(result_defs->data + i);
switch (def->kind) {
case WASM_I32:
{
out->kind = WASM_I32;
out->of.i32 = *(int32 *)result;
result += 1;
break;
}
case WASM_I64:
{
out->kind = WASM_I64;
out->of.i64 = *(int64 *)result;
result += 2;
break;
}
case WASM_F32:
{
out->kind = WASM_F32;
out->of.f32 = *(float32 *)result;
result += 1;
break;
}
case WASM_F64:
{
out->kind = WASM_F64;
out->of.f64 = *(float64 *)result;
result += 2;
break;
}
default:
LOG_WARNING("%s meets unsupported type: %d", __FUNCTION__,
def->kind);
goto failed;
}
out++;
argc++;
}
return argc;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
return 0;
}
wasm_trap_t *
wasm_func_call(const wasm_func_t *func,
const wasm_val_t params[],
wasm_val_t results[])
{
/* parameters count as if all are uint32 */
/* a int64 or float64 parameter means 2 */
uint32 argc = 0;
/* a parameter list and a return value list */
uint32 argv_buf[32], *argv = argv_buf;
WASMFunctionInstanceCommon *func_comm_rt = NULL;
WASMExecEnv *exec_env = NULL;
size_t param_count, result_count, alloc_count;
bh_assert(func && func->type && func->inst_comm_rt);
#if WASM_ENABLE_INTERP != 0
if (func->inst_comm_rt->module_type == Wasm_Module_Bytecode) {
func_comm_rt = ((WASMModuleInstance *)func->inst_comm_rt)->functions
+ func->func_idx_rt;
}
#endif
#if WASM_ENABLE_AOT != 0
if (func->inst_comm_rt->module_type == Wasm_Module_AoT) {
if (!(func_comm_rt = func->func_comm_rt)) {
AOTModuleInstance *inst_aot =
(AOTModuleInstance *)func->inst_comm_rt;
AOTModule *module_aot = (AOTModule *)inst_aot->aot_module.ptr;
uint32 export_i = 0, export_func_j = 0;
for (; export_i < module_aot->export_count; ++export_i) {
AOTExport *export = module_aot->exports + export_i;
if (export->kind == EXPORT_KIND_FUNC) {
if (export->index == func->func_idx_rt) {
func_comm_rt =
(AOTFunctionInstance *)inst_aot->export_funcs.ptr
+ export_func_j;
((wasm_func_t *)func)->func_comm_rt = func_comm_rt;
break;
}
export_func_j++;
}
}
}
}
#endif
if (!func_comm_rt) {
goto failed;
}
param_count = wasm_func_param_arity(func);
result_count = wasm_func_result_arity(func);
alloc_count = (param_count > result_count) ? param_count : result_count;
if (alloc_count > sizeof(argv_buf) / sizeof(uint64)) {
if (!(argv = malloc_internal(sizeof(uint64) * alloc_count))) {
goto failed;
}
}
/* copy parametes */
if (param_count
&& !(argc = params_to_argv(params, wasm_functype_params(func->type),
param_count, argv))) {
goto failed;
}
exec_env = wasm_runtime_get_exec_env_singleton(func->inst_comm_rt);
if (!exec_env) {
goto failed;
}
if (!wasm_runtime_call_wasm(exec_env, func_comm_rt, argc, argv)) {
if (wasm_runtime_get_exception(func->inst_comm_rt)) {
LOG_DEBUG(wasm_runtime_get_exception(func->inst_comm_rt));
goto failed;
}
}
/* copy results */
if (result_count) {
if (!(argc = argv_to_results(argv, wasm_functype_results(func->type),
result_count, results))) {
goto failed;
}
}
if (argv != argv_buf)
wasm_runtime_free(argv);
return NULL;
failed:
if (argv != argv_buf)
wasm_runtime_free(argv);
/* trap -> exception -> trap */
if (wasm_runtime_get_exception(func->inst_comm_rt)) {
return wasm_trap_new_internal(func->inst_comm_rt, NULL);
}
else {
return wasm_trap_new_internal(func->inst_comm_rt,
"wasm_func_call failed");
}
}
size_t
wasm_func_param_arity(const wasm_func_t *func)
{
if (!func || !func->type || !func->type->params) {
return 0;
}
return func->type->params->num_elems;
}
size_t
wasm_func_result_arity(const wasm_func_t *func)
{
if (!func || !func->type || !func->type->results) {
return 0;
}
return func->type->results->num_elems;
}
wasm_global_t *
wasm_global_new(wasm_store_t *store,
const wasm_globaltype_t *global_type,
const wasm_val_t *init)
{
wasm_global_t *global = NULL;
bh_assert(singleton_engine);
global = malloc_internal(sizeof(wasm_global_t));
if (!global) {
goto failed;
}
global->kind = WASM_EXTERN_GLOBAL;
global->type = wasm_globaltype_copy(global_type);
if (!global->type) {
goto failed;
}
global->init = malloc_internal(sizeof(wasm_val_t));
if (!global->init) {
goto failed;
}
wasm_val_copy(global->init, init);
/* TODO: how to check if above is failed */
return global;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
wasm_global_delete(global);
return NULL;
}
/* almost same with wasm_global_new */
wasm_global_t *
wasm_global_copy(const wasm_global_t *src)
{
wasm_global_t *global = NULL;
if (!src) {
return NULL;
}
global = malloc_internal(sizeof(wasm_global_t));
if (!global) {
goto failed;
}
global->kind = WASM_EXTERN_GLOBAL;
global->type = wasm_globaltype_copy(src->type);
if (!global->type) {
goto failed;
}
global->init = malloc_internal(sizeof(wasm_val_t));
if (!global->init) {
goto failed;
}
wasm_val_copy(global->init, src->init);
global->global_idx_rt = src->global_idx_rt;
global->inst_comm_rt = src->inst_comm_rt;
return global;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
wasm_global_delete(global);
return NULL;
}
void
wasm_global_delete(wasm_global_t *global)
{
if (!global) {
return;
}
if (global->init) {
wasm_val_delete(global->init);
global->init = NULL;
}
if (global->type) {
wasm_globaltype_delete(global->type);
global->type = NULL;
}
wasm_runtime_free(global);
}
bool
wasm_global_same(const wasm_global_t *g1, const wasm_global_t *g2)
{
if (!g1 && !g2) {
return true;
}
if (!g1 || !g2) {
return false;
}
return g1->kind == g2->kind && wasm_globaltype_same(g1->type, g2->type)
&& wasm_val_same(g1->init, g2->init);
}
#if WASM_ENABLE_INTERP != 0
static bool
interp_global_set(const WASMModuleInstance *inst_interp,
uint16 global_idx_rt,
const wasm_val_t *v)
{
const WASMGlobalInstance *global_interp =
inst_interp->globals + global_idx_rt;
uint8 val_type_rt = global_interp->type;
#if WASM_ENABLE_MULTI_MODULE != 0
uint8 *data = global_interp->import_global_inst
? global_interp->import_module_inst->global_data
+ global_interp->import_global_inst->data_offset
: inst_interp->global_data + global_interp->data_offset;
#else
uint8 *data = inst_interp->global_data + global_interp->data_offset;
#endif
bool ret = true;
switch (val_type_rt) {
case VALUE_TYPE_I32:
bh_assert(WASM_I32 == v->kind);
*((int32 *)data) = v->of.i32;
break;
case VALUE_TYPE_F32:
bh_assert(WASM_F32 == v->kind);
*((float32 *)data) = v->of.f32;
break;
case VALUE_TYPE_I64:
bh_assert(WASM_I64 == v->kind);
*((int64 *)data) = v->of.i64;
break;
case VALUE_TYPE_F64:
bh_assert(WASM_F64 == v->kind);
*((float64 *)data) = v->of.f64;
break;
default:
LOG_DEBUG("unexpected value type %d", val_type_rt);
ret = false;
break;
}
return ret;
}
static bool
interp_global_get(const WASMModuleInstance *inst_interp,
uint16 global_idx_rt,
wasm_val_t *out)
{
WASMGlobalInstance *global_interp = inst_interp->globals + global_idx_rt;
uint8 val_type_rt = global_interp->type;
#if WASM_ENABLE_MULTI_MODULE != 0
uint8 *data = global_interp->import_global_inst
? global_interp->import_module_inst->global_data
+ global_interp->import_global_inst->data_offset
: inst_interp->global_data + global_interp->data_offset;
#else
uint8 *data = inst_interp->global_data + global_interp->data_offset;
#endif
bool ret = true;
switch (val_type_rt) {
case VALUE_TYPE_I32:
out->kind = WASM_I32;
out->of.i32 = *((int32 *)data);
break;
case VALUE_TYPE_F32:
out->kind = WASM_F32;
out->of.f32 = *((float32 *)data);
break;
case VALUE_TYPE_I64:
out->kind = WASM_I64;
out->of.i64 = *((int64 *)data);
break;
case VALUE_TYPE_F64:
out->kind = WASM_F64;
out->of.f64 = *((float64 *)data);
break;
default:
LOG_DEBUG("unexpected value type %d", val_type_rt);
ret = false;
}
return ret;
}
#endif
#if WASM_ENABLE_AOT != 0
static bool
aot_global_set(const AOTModuleInstance *inst_aot,
uint16 global_idx_rt,
const wasm_val_t *v)
{
AOTModule *module_aot = inst_aot->aot_module.ptr;
uint8 val_type_rt = 0;
uint32 data_offset = 0;
void *data = NULL;
bool ret = true;
if (global_idx_rt < module_aot->import_global_count) {
data_offset = module_aot->import_globals[global_idx_rt].data_offset;
val_type_rt = module_aot->import_globals[global_idx_rt].type;
}
else {
data_offset =
module_aot->globals[global_idx_rt - module_aot->import_global_count]
.data_offset;
val_type_rt =
module_aot->globals[global_idx_rt - module_aot->import_global_count]
.type;
}
data = (void *)((uint8 *)inst_aot->global_data.ptr + data_offset);
switch (val_type_rt) {
case VALUE_TYPE_I32:
bh_assert(WASM_I32 == v->kind);
*((int32 *)data) = v->of.i32;
break;
case VALUE_TYPE_F32:
bh_assert(WASM_F32 == v->kind);
*((float32 *)data) = v->of.f32;
break;
case VALUE_TYPE_I64:
bh_assert(WASM_I64 == v->kind);
*((int64 *)data) = v->of.i64;
break;
case VALUE_TYPE_F64:
bh_assert(WASM_F64 == v->kind);
*((float64 *)data) = v->of.f64;
break;
default:
LOG_DEBUG("unexpected value type %d", val_type_rt);
ret = false;
}
return ret;
}
static bool
aot_global_get(const AOTModuleInstance *inst_aot,
uint16 global_idx_rt,
wasm_val_t *out)
{
AOTModule *module_aot = inst_aot->aot_module.ptr;
uint8 val_type_rt = 0;
uint32 data_offset = 0;
void *data = NULL;
bool ret = true;
if (global_idx_rt < module_aot->import_global_count) {
data_offset = module_aot->import_globals[global_idx_rt].data_offset;
val_type_rt = module_aot->import_globals[global_idx_rt].type;
}
else {
data_offset =
module_aot->globals[global_idx_rt - module_aot->import_global_count]
.data_offset;
val_type_rt =
module_aot->globals[global_idx_rt - module_aot->import_global_count]
.type;
}
data = (void *)((uint8 *)inst_aot->global_data.ptr + data_offset);
switch (val_type_rt) {
case VALUE_TYPE_I32:
out->kind = WASM_I32;
out->of.i32 = *((int32 *)data);
break;
case VALUE_TYPE_F32:
out->kind = WASM_F32;
out->of.f32 = *((float32 *)data);
break;
case VALUE_TYPE_I64:
out->kind = WASM_I64;
out->of.i64 = *((int64 *)data);
break;
case VALUE_TYPE_F64:
out->kind = WASM_F64;
out->of.f64 = *((float64 *)data);
break;
default:
LOG_DEBUG("unexpected value type %d", val_type_rt);
ret = false;
}
return ret;
}
#endif
void
wasm_global_set(wasm_global_t *global, const wasm_val_t *v)
{
if (!global || !v
|| !valid_module_type(global->inst_comm_rt->module_type)) {
return;
}
#if WASM_ENABLE_INTERP != 0
if (global->inst_comm_rt->module_type == Wasm_Module_Bytecode) {
(void)interp_global_set((WASMModuleInstance *)global->inst_comm_rt,
global->global_idx_rt, v);
}
#endif
#if WASM_ENABLE_AOT != 0
if (global->inst_comm_rt->module_type == Wasm_Module_AoT) {
(void)aot_global_set((AOTModuleInstance *)global->inst_comm_rt,
global->global_idx_rt, v);
}
#endif
}
void
wasm_global_get(const wasm_global_t *global, wasm_val_t *out)
{
if (!global || !out
|| !valid_module_type(global->inst_comm_rt->module_type)) {
return;
}
memset(out, 0, sizeof(wasm_val_t));
#if WASM_ENABLE_INTERP != 0
if (global->inst_comm_rt->module_type == Wasm_Module_Bytecode) {
(void)interp_global_get((WASMModuleInstance *)global->inst_comm_rt,
global->global_idx_rt, out);
}
#endif
#if WASM_ENABLE_AOT != 0
if (global->inst_comm_rt->module_type == Wasm_Module_AoT) {
(void)aot_global_get((AOTModuleInstance *)global->inst_comm_rt,
global->global_idx_rt, out);
}
#endif
bh_assert(global->init->kind == out->kind);
}
static wasm_global_t *
wasm_global_new_internal(wasm_store_t *store,
uint16 global_idx_rt,
WASMModuleInstanceCommon *inst_comm_rt)
{
wasm_global_t *global = NULL;
uint8 val_type_rt = 0;
bool is_mutable = 0;
bh_assert(singleton_engine);
if (!inst_comm_rt || !valid_module_type(inst_comm_rt->module_type)) {
return NULL;
}
global = malloc_internal(sizeof(wasm_global_t));
if (!global) {
goto failed;
}
/*
* global->module_name = NULL;
* global->name = NULL;
*/
global->kind = WASM_EXTERN_GLOBAL;
#if WASM_ENABLE_INTERP != 0
if (inst_comm_rt->module_type == Wasm_Module_Bytecode) {
WASMGlobalInstance *global_interp =
((WASMModuleInstance *)inst_comm_rt)->globals + global_idx_rt;
val_type_rt = global_interp->type;
is_mutable = global_interp->is_mutable;
}
#endif
#if WASM_ENABLE_AOT != 0
if (inst_comm_rt->module_type == Wasm_Module_AoT) {
AOTModuleInstance *inst_aot = (AOTModuleInstance *)inst_comm_rt;
AOTModule *module_aot = inst_aot->aot_module.ptr;
if (global_idx_rt < module_aot->import_global_count) {
AOTImportGlobal *global_import_aot =
module_aot->import_globals + global_idx_rt;
val_type_rt = global_import_aot->type;
is_mutable = global_import_aot->is_mutable;
}
else {
AOTGlobal *global_aot =
module_aot->globals
+ (global_idx_rt - module_aot->import_global_count);
val_type_rt = global_aot->type;
is_mutable = global_aot->is_mutable;
}
}
#endif
global->type = wasm_globaltype_new_internal(val_type_rt, is_mutable);
if (!global->type) {
goto failed;
}
global->init = malloc_internal(sizeof(wasm_val_t));
if (!global->init) {
goto failed;
}
#if WASM_ENABLE_INTERP != 0
if (inst_comm_rt->module_type == Wasm_Module_Bytecode) {
interp_global_get((WASMModuleInstance *)inst_comm_rt, global_idx_rt,
global->init);
}
#endif
#if WASM_ENABLE_AOT != 0
if (inst_comm_rt->module_type == Wasm_Module_AoT) {
aot_global_get((AOTModuleInstance *)inst_comm_rt, global_idx_rt,
global->init);
}
#endif
global->inst_comm_rt = inst_comm_rt;
global->global_idx_rt = global_idx_rt;
return global;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
wasm_global_delete(global);
return NULL;
}
wasm_globaltype_t *
wasm_global_type(const wasm_global_t *global)
{
if (!global) {
return NULL;
}
return wasm_globaltype_copy(global->type);
}
static wasm_table_t *
wasm_table_new_basic(const wasm_tabletype_t *type)
{
wasm_table_t *table = NULL;
if (!(table = malloc_internal(sizeof(wasm_table_t)))) {
goto failed;
}
table->kind = WASM_EXTERN_TABLE;
if (!(table->type = wasm_tabletype_copy(type))) {
goto failed;
}
RETURN_OBJ(table, wasm_table_delete);
}
static wasm_table_t *
wasm_table_new_internal(wasm_store_t *store,
uint16 table_idx_rt,
WASMModuleInstanceCommon *inst_comm_rt)
{
wasm_table_t *table = NULL;
uint8 val_type_rt = 0;
uint32 init_size = 0, max_size = 0;
bh_assert(singleton_engine);
if (!inst_comm_rt || !valid_module_type(inst_comm_rt->module_type)) {
return NULL;
}
if (!(table = malloc_internal(sizeof(wasm_table_t)))) {
goto failed;
}
table->kind = WASM_EXTERN_TABLE;
#if WASM_ENABLE_INTERP != 0
if (inst_comm_rt->module_type == Wasm_Module_Bytecode) {
WASMTableInstance *table_interp =
((WASMModuleInstance *)inst_comm_rt)->tables[table_idx_rt];
val_type_rt = table_interp->elem_type;
init_size = table_interp->cur_size;
max_size = table_interp->max_size;
}
#endif
#if WASM_ENABLE_AOT != 0
if (inst_comm_rt->module_type == Wasm_Module_AoT) {
AOTModuleInstance *inst_aot = (AOTModuleInstance *)inst_comm_rt;
AOTModule *module_aot = (AOTModule *)inst_aot->aot_module.ptr;
if (table_idx_rt < module_aot->import_table_count) {
AOTImportTable *table_aot =
module_aot->import_tables + table_idx_rt;
val_type_rt = VALUE_TYPE_FUNCREF;
init_size = table_aot->table_init_size;
max_size = table_aot->table_max_size;
}
else {
AOTTable *table_aot =
module_aot->tables
+ (table_idx_rt - module_aot->import_table_count);
val_type_rt = VALUE_TYPE_FUNCREF;
init_size = table_aot->table_init_size;
max_size = table_aot->table_max_size;
}
}
#endif
if (!(table->type =
wasm_tabletype_new_internal(val_type_rt, init_size, max_size))) {
goto failed;
}
table->inst_comm_rt = inst_comm_rt;
table->table_idx_rt = table_idx_rt;
RETURN_OBJ(table, wasm_table_delete);
}
wasm_table_t *
wasm_table_new(wasm_store_t *store,
const wasm_tabletype_t *table_type,
wasm_ref_t *init)
{
(void)init;
bh_assert(singleton_engine);
return wasm_table_new_basic(table_type);
}
wasm_table_t *
wasm_table_copy(const wasm_table_t *src)
{
return wasm_table_new_basic(src->type);
}
void
wasm_table_delete(wasm_table_t *table)
{
if (!table) {
return;
}
if (table->type) {
wasm_tabletype_delete(table->type);
table->type = NULL;
}
wasm_runtime_free(table);
}
wasm_tabletype_t *
wasm_table_type(const wasm_table_t *table)
{
if (!table) {
return NULL;
}
return wasm_tabletype_copy(table->type);
}
static wasm_memory_t *
wasm_memory_new_basic(const wasm_memorytype_t *type)
{
wasm_memory_t *memory = NULL;
if (!(memory = malloc_internal(sizeof(wasm_memory_t)))) {
goto failed;
}
memory->kind = WASM_EXTERN_MEMORY;
memory->type = wasm_memorytype_copy(type);
RETURN_OBJ(memory, wasm_memory_delete)
}
wasm_memory_t *
wasm_memory_new(wasm_store_t *store, const wasm_memorytype_t *type)
{
bh_assert(singleton_engine);
return wasm_memory_new_basic(type);
}
wasm_memory_t *
wasm_memory_copy(const wasm_memory_t *src)
{
wasm_memory_t *dst = NULL;
if (!src) {
return NULL;
}
if (!(dst = wasm_memory_new_basic(src->type))) {
goto failed;
}
dst->memory_idx_rt = src->memory_idx_rt;
dst->inst_comm_rt = src->inst_comm_rt;
RETURN_OBJ(dst, wasm_memory_delete)
}
static wasm_memory_t *
wasm_memory_new_internal(wasm_store_t *store,
uint16 memory_idx_rt,
WASMModuleInstanceCommon *inst_comm_rt)
{
wasm_memory_t *memory = NULL;
uint32 min_pages = 0, max_pages = 0;
bh_assert(singleton_engine);
if (!inst_comm_rt || !valid_module_type(inst_comm_rt->module_type)) {
return NULL;
}
if (!(memory = malloc_internal(sizeof(wasm_memory_t)))) {
goto failed;
}
memory->kind = WASM_EXTERN_MEMORY;
#if WASM_ENABLE_INTERP != 0
if (inst_comm_rt->module_type == Wasm_Module_Bytecode) {
WASMMemoryInstance *memory_interp =
((WASMModuleInstance *)inst_comm_rt)->memories[memory_idx_rt];
min_pages = memory_interp->cur_page_count;
max_pages = memory_interp->max_page_count;
}
#endif
#if WASM_ENABLE_AOT != 0
if (inst_comm_rt->module_type == Wasm_Module_AoT) {
AOTModuleInstance *inst_aot = (AOTModuleInstance *)inst_comm_rt;
AOTModule *module_aot = (AOTModule *)(inst_aot->aot_module.ptr);
if (memory_idx_rt < module_aot->import_memory_count) {
min_pages = module_aot->import_memories->mem_init_page_count;
max_pages = module_aot->import_memories->mem_max_page_count;
}
else {
min_pages = module_aot->memories->mem_init_page_count;
max_pages = module_aot->memories->mem_max_page_count;
}
}
#endif
if (!(memory->type = wasm_memorytype_new_internal(min_pages, max_pages))) {
goto failed;
}
memory->inst_comm_rt = inst_comm_rt;
memory->memory_idx_rt = memory_idx_rt;
RETURN_OBJ(memory, wasm_memory_delete);
}
void
wasm_memory_delete(wasm_memory_t *memory)
{
if (!memory) {
return;
}
if (memory->type) {
wasm_memorytype_delete(memory->type);
memory->type = NULL;
}
wasm_runtime_free(memory);
}
wasm_memorytype_t *
wasm_memory_type(const wasm_memory_t *memory)
{
if (!memory) {
return NULL;
}
return wasm_memorytype_copy(memory->type);
}
byte_t *
wasm_memory_data(wasm_memory_t *memory)
{
return (byte_t *)wasm_runtime_get_memory_data(memory->inst_comm_rt,
memory->memory_idx_rt);
}
size_t
wasm_memory_data_size(const wasm_memory_t *memory)
{
return wasm_runtime_get_memory_data_size(memory->inst_comm_rt,
memory->memory_idx_rt);
}
#if WASM_ENABLE_INTERP != 0
static bool
interp_link_func(const wasm_instance_t *inst,
const WASMModule *module_interp,
uint16 func_idx_rt,
wasm_func_t *import)
{
WASMImport *imported_func_interp = NULL;
wasm_func_t *cloned = NULL;
bh_assert(inst && module_interp && import);
bh_assert(func_idx_rt < module_interp->import_function_count);
bh_assert(WASM_EXTERN_FUNC == import->kind);
imported_func_interp = module_interp->import_functions + func_idx_rt;
bh_assert(imported_func_interp);
if (!(cloned = wasm_func_copy(import))) {
return false;
}
if (!bh_vector_append((Vector *)inst->imports, &cloned)) {
wasm_func_delete(cloned);
return false;
}
imported_func_interp->u.function.call_conv_wasm_c_api = true;
imported_func_interp->u.function.wasm_c_api_with_env = import->with_env;
if (import->with_env) {
imported_func_interp->u.function.func_ptr_linked = import->u.cb_env.cb;
imported_func_interp->u.function.attachment = import->u.cb_env.env;
}
else {
imported_func_interp->u.function.func_ptr_linked = import->u.cb;
imported_func_interp->u.function.attachment = NULL;
}
import->func_idx_rt = func_idx_rt;
return true;
}
static bool
interp_link_global(const WASMModule *module_interp,
uint16 global_idx_rt,
wasm_global_t *import)
{
WASMImport *imported_global_interp = NULL;
bh_assert(module_interp && import);
bh_assert(global_idx_rt < module_interp->import_global_count);
bh_assert(WASM_EXTERN_GLOBAL == import->kind);
imported_global_interp = module_interp->import_globals + global_idx_rt;
bh_assert(imported_global_interp);
/* set init value */
switch (wasm_valtype_kind(import->type->val_type)) {
case WASM_I32:
bh_assert(VALUE_TYPE_I32 == imported_global_interp->u.global.type);
imported_global_interp->u.global.global_data_linked.i32 =
import->init->of.i32;
break;
case WASM_I64:
bh_assert(VALUE_TYPE_I64 == imported_global_interp->u.global.type);
imported_global_interp->u.global.global_data_linked.i64 =
import->init->of.i64;
break;
case WASM_F32:
bh_assert(VALUE_TYPE_F32 == imported_global_interp->u.global.type);
imported_global_interp->u.global.global_data_linked.f32 =
import->init->of.f32;
break;
case WASM_F64:
bh_assert(VALUE_TYPE_F64 == imported_global_interp->u.global.type);
imported_global_interp->u.global.global_data_linked.f64 =
import->init->of.f64;
break;
default:
return false;
}
import->global_idx_rt = global_idx_rt;
imported_global_interp->u.global.is_linked = true;
return true;
}
static uint32
interp_link(const wasm_instance_t *inst,
const WASMModule *module_interp,
wasm_extern_t *imports[])
{
uint32 i = 0;
uint32 import_func_i = 0;
uint32 import_global_i = 0;
bh_assert(inst && module_interp && imports);
for (i = 0; i < module_interp->import_count; ++i) {
wasm_extern_t *import = imports[i];
WASMImport *import_rt = module_interp->imports + i;
switch (import_rt->kind) {
case IMPORT_KIND_FUNC:
{
if (!interp_link_func(inst, module_interp, import_func_i++,
wasm_extern_as_func(import))) {
goto failed;
}
break;
}
case IMPORT_KIND_GLOBAL:
{
if (!interp_link_global(module_interp, import_global_i++,
wasm_extern_as_global(import))) {
goto failed;
}
break;
}
case IMPORT_KIND_MEMORY:
case IMPORT_KIND_TABLE:
ASSERT_NOT_IMPLEMENTED();
break;
default:
LOG_WARNING("%s meets unsupported kind: %d", __FUNCTION__,
import_rt->kind);
goto failed;
}
}
return i;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
return (uint32)-1;
}
static bool
interp_process_export(wasm_store_t *store,
const WASMModuleInstance *inst_interp,
wasm_extern_vec_t *externals)
{
WASMExport *exports = NULL;
WASMExport *export = NULL;
wasm_extern_t *external = NULL;
uint32 export_cnt = 0;
uint32 i = 0;
bh_assert(store && inst_interp && inst_interp->module && externals);
exports = inst_interp->module->exports;
export_cnt = inst_interp->module->export_count;
for (i = 0; i < export_cnt; ++i) {
export = exports + i;
switch (export->kind) {
case EXPORT_KIND_FUNC:
{
wasm_func_t *func;
if (!(func = wasm_func_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_interp))) {
goto failed;
}
external = wasm_func_as_extern(func);
break;
}
case EXPORT_KIND_GLOBAL:
{
wasm_global_t *global;
if (!(global = wasm_global_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_interp))) {
goto failed;
}
external = wasm_global_as_extern(global);
break;
}
case EXPORT_KIND_TABLE:
{
wasm_table_t *table;
if (!(table = wasm_table_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_interp))) {
goto failed;
}
external = wasm_table_as_extern(table);
break;
}
case EXPORT_KIND_MEMORY:
{
wasm_memory_t *memory;
if (!(memory = wasm_memory_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_interp))) {
goto failed;
}
external = wasm_memory_as_extern(memory);
break;
}
default:
LOG_WARNING("%s meets unsupported kind: %d", __FUNCTION__,
export->kind);
goto failed;
}
if (!bh_vector_append((Vector *)externals, &external)) {
goto failed;
}
}
return true;
failed:
wasm_extern_delete(external);
return false;
}
#endif /* WASM_ENABLE_INTERP */
#if WASM_ENABLE_AOT != 0
static bool
aot_link_func(const wasm_instance_t *inst,
const AOTModule *module_aot,
uint32 import_func_idx_rt,
wasm_func_t *import)
{
AOTImportFunc *import_aot_func = NULL;
wasm_func_t *cloned = NULL;
bh_assert(inst && module_aot && import);
import_aot_func = module_aot->import_funcs + import_func_idx_rt;
bh_assert(import_aot_func);
if (!(cloned = wasm_func_copy(import))) {
return false;
}
if (!bh_vector_append((Vector *)inst->imports, &cloned)) {
wasm_func_delete(cloned);
return false;
}
import_aot_func->call_conv_wasm_c_api = true;
import_aot_func->wasm_c_api_with_env = import->with_env;
if (import->with_env) {
import_aot_func->func_ptr_linked = import->u.cb_env.cb;
import_aot_func->attachment = import->u.cb_env.env;
}
else
import_aot_func->func_ptr_linked = import->u.cb;
import->func_idx_rt = import_func_idx_rt;
return true;
}
static bool
aot_link_global(const AOTModule *module_aot,
uint16 global_idx_rt,
wasm_global_t *import)
{
AOTImportGlobal *import_aot_global = NULL;
const wasm_valtype_t *val_type = NULL;
bh_assert(module_aot && import);
import_aot_global = module_aot->import_globals + global_idx_rt;
bh_assert(import_aot_global);
//TODO: import->type ?
val_type = wasm_globaltype_content(import->type);
bh_assert(val_type);
switch (wasm_valtype_kind(val_type)) {
case WASM_I32:
bh_assert(VALUE_TYPE_I32 == import_aot_global->type);
import_aot_global->global_data_linked.i32 = import->init->of.i32;
break;
case WASM_I64:
bh_assert(VALUE_TYPE_I64 == import_aot_global->type);
import_aot_global->global_data_linked.i64 = import->init->of.i64;
break;
case WASM_F32:
bh_assert(VALUE_TYPE_F32 == import_aot_global->type);
import_aot_global->global_data_linked.f32 = import->init->of.f32;
break;
case WASM_F64:
bh_assert(VALUE_TYPE_F64 == import_aot_global->type);
import_aot_global->global_data_linked.f64 = import->init->of.f64;
break;
default:
goto failed;
}
import->global_idx_rt = global_idx_rt;
return true;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
return false;
}
static uint32
aot_link(const wasm_instance_t *inst,
const AOTModule *module_aot,
wasm_extern_t *imports[])
{
uint32 i = 0;
uint32 import_func_i = 0;
uint32 import_global_i = 0;
wasm_extern_t *import = NULL;
wasm_func_t *func = NULL;
wasm_global_t *global = NULL;
bh_assert(inst && module_aot && imports);
while (import_func_i < module_aot->import_func_count
|| import_global_i < module_aot->import_global_count) {
import = imports[i++];
bh_assert(import);
switch (wasm_extern_kind(import)) {
case WASM_EXTERN_FUNC:
bh_assert(import_func_i < module_aot->import_func_count);
func = wasm_extern_as_func((wasm_extern_t *)import);
if (!aot_link_func(inst, module_aot, import_func_i++, func)) {
goto failed;
}
break;
case WASM_EXTERN_GLOBAL:
bh_assert(import_global_i < module_aot->import_global_count);
global = wasm_extern_as_global((wasm_extern_t *)import);
if (!aot_link_global(module_aot, import_global_i++, global)) {
goto failed;
}
break;
case WASM_EXTERN_MEMORY:
case WASM_EXTERN_TABLE:
ASSERT_NOT_IMPLEMENTED();
break;
default:
goto failed;
}
}
return i;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
return (uint32)-1;
}
static bool
aot_process_export(wasm_store_t *store,
const AOTModuleInstance *inst_aot,
wasm_extern_vec_t *externals)
{
uint32 i;
wasm_extern_t *external = NULL;
AOTModule *module_aot = NULL;
bh_assert(store && inst_aot && externals);
module_aot = (AOTModule *)inst_aot->aot_module.ptr;
bh_assert(module_aot);
for (i = 0; i < module_aot->export_count; ++i) {
AOTExport *export = module_aot->exports + i;
switch (export->kind) {
case EXPORT_KIND_FUNC:
{
wasm_func_t *func = NULL;
if (!(func = wasm_func_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_aot))) {
goto failed;
}
external = wasm_func_as_extern(func);
break;
}
case EXPORT_KIND_GLOBAL:
{
wasm_global_t *global = NULL;
if (!(global = wasm_global_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_aot))) {
goto failed;
}
external = wasm_global_as_extern(global);
break;
}
case EXPORT_KIND_TABLE:
{
wasm_table_t *table;
if (!(table = wasm_table_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_aot))) {
goto failed;
}
external = wasm_table_as_extern(table);
break;
}
case EXPORT_KIND_MEMORY:
{
wasm_memory_t *memory;
if (!(memory = wasm_memory_new_internal(
store, export->index,
(WASMModuleInstanceCommon *)inst_aot))) {
goto failed;
}
external = wasm_memory_as_extern(memory);
break;
}
default:
LOG_WARNING("%s meets unsupported kind: %d", __FUNCTION__,
export->kind);
goto failed;
}
if (!(external->name = malloc_internal(sizeof(wasm_byte_vec_t)))) {
goto failed;
}
wasm_name_new_from_string(external->name, export->name);
if (strlen(export->name) && !external->name->data) {
goto failed;
}
if (!bh_vector_append((Vector *)externals, &external)) {
goto failed;
}
}
return true;
failed:
wasm_extern_delete(external);
return false;
}
#endif /* WASM_ENABLE_AOT */
wasm_instance_t *
wasm_instance_new(wasm_store_t *store,
const wasm_module_t *module,
const wasm_extern_t *const imports[],
own wasm_trap_t **traps)
{
char error_buf[128] = { 0 };
const uint32 stack_size = 32 * 1024;
const uint32 heap_size = 32 * 1024;
uint32 import_count = 0;
wasm_instance_t *instance = NULL;
uint32 i = 0;
(void)traps;
bh_assert(singleton_engine);
if (!module || !valid_module_type((*module)->module_type)) {
return NULL;
}
instance = malloc_internal(sizeof(wasm_instance_t));
if (!instance) {
goto failed;
}
/* link module and imports */
if (imports) {
#if WASM_ENABLE_INTERP != 0
if ((*module)->module_type == Wasm_Module_Bytecode) {
import_count = MODULE_INTERP(module)->import_count;
INIT_VEC(instance->imports, wasm_extern_vec_new_uninitialized,
import_count);
if (import_count) {
uint32 actual_link_import_count = interp_link(
instance, MODULE_INTERP(module), (wasm_extern_t **)imports);
/* make sure a complete import list */
if ((int32)import_count < 0
|| import_count != actual_link_import_count) {
goto failed;
}
}
}
#endif
#if WASM_ENABLE_AOT != 0
if ((*module)->module_type == Wasm_Module_AoT) {
import_count = MODULE_AOT(module)->import_func_count
+ MODULE_AOT(module)->import_global_count
+ MODULE_AOT(module)->import_memory_count
+ MODULE_AOT(module)->import_table_count;
INIT_VEC(instance->imports, wasm_extern_vec_new_uninitialized,
import_count);
if (import_count) {
import_count = aot_link(instance, MODULE_AOT(module),
(wasm_extern_t **)imports);
if ((int32)import_count < 0) {
goto failed;
}
}
}
#endif
}
instance->inst_comm_rt = wasm_runtime_instantiate(
*module, stack_size, heap_size, error_buf, sizeof(error_buf));
if (!instance->inst_comm_rt) {
LOG_ERROR(error_buf);
goto failed;
}
if (!wasm_runtime_create_exec_env_singleton(instance->inst_comm_rt)) {
goto failed;
}
/* fill with inst */
for (i = 0; imports && i < (uint32)import_count; ++i) {
wasm_extern_t *import = (wasm_extern_t *)imports[i];
switch (import->kind) {
case WASM_EXTERN_FUNC:
wasm_extern_as_func(import)->inst_comm_rt =
instance->inst_comm_rt;
break;
case WASM_EXTERN_GLOBAL:
wasm_extern_as_global(import)->inst_comm_rt =
instance->inst_comm_rt;
break;
case WASM_EXTERN_MEMORY:
wasm_extern_as_memory(import)->inst_comm_rt =
instance->inst_comm_rt;
break;
case WASM_EXTERN_TABLE:
wasm_extern_as_table(import)->inst_comm_rt =
instance->inst_comm_rt;
break;
default:
goto failed;
}
}
/* build the exports list */
#if WASM_ENABLE_INTERP != 0
if (instance->inst_comm_rt->module_type == Wasm_Module_Bytecode) {
uint32 export_cnt =
((WASMModuleInstance *)instance->inst_comm_rt)->module->export_count;
INIT_VEC(instance->exports, wasm_extern_vec_new_uninitialized,
export_cnt);
if (!interp_process_export(
store, (WASMModuleInstance *)instance->inst_comm_rt,
instance->exports)) {
goto failed;
}
}
#endif
#if WASM_ENABLE_AOT != 0
if (instance->inst_comm_rt->module_type == Wasm_Module_AoT) {
uint32 export_cnt =
((AOTModuleInstance *)instance->inst_comm_rt)->export_func_count
+ ((AOTModuleInstance *)instance->inst_comm_rt)->export_global_count
+ ((AOTModuleInstance *)instance->inst_comm_rt)->export_tab_count
+ ((AOTModuleInstance *)instance->inst_comm_rt)->export_mem_count;
INIT_VEC(instance->exports, wasm_extern_vec_new_uninitialized,
export_cnt);
if (!aot_process_export(store,
(AOTModuleInstance *)instance->inst_comm_rt,
instance->exports)) {
goto failed;
}
}
#endif
/* add it to a watching list in store */
if (!bh_vector_append((Vector *)store->instances, &instance)) {
goto failed;
}
return instance;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
wasm_instance_delete_internal(instance);
return NULL;
}
static void
wasm_instance_delete_internal(wasm_instance_t *instance)
{
if (!instance) {
return;
}
DEINIT_VEC(instance->imports, wasm_extern_vec_delete);
DEINIT_VEC(instance->exports, wasm_extern_vec_delete);
if (instance->inst_comm_rt) {
wasm_runtime_deinstantiate(instance->inst_comm_rt);
instance->inst_comm_rt = NULL;
}
wasm_runtime_free(instance);
}
void
wasm_instance_delete(wasm_instance_t *module)
{
/* will release instance when releasing the store */
}
void
wasm_instance_exports(const wasm_instance_t *instance,
own wasm_extern_vec_t *out)
{
if (!instance || !out) {
return;
}
wasm_extern_vec_copy(out, instance->exports);
}
wasm_extern_t *
wasm_extern_copy(const wasm_extern_t *src)
{
wasm_extern_t *dst = NULL;
if (!src) {
return NULL;
}
switch (wasm_extern_kind(src)) {
case WASM_EXTERN_FUNC:
dst = wasm_func_as_extern(
wasm_func_copy(wasm_extern_as_func_const(src)));
break;
case WASM_EXTERN_GLOBAL:
dst = wasm_global_as_extern(
wasm_global_copy(wasm_extern_as_global_const(src)));
break;
case WASM_EXTERN_MEMORY:
dst = wasm_memory_as_extern(
wasm_memory_copy(wasm_extern_as_memory_const(src)));
break;
case WASM_EXTERN_TABLE:
dst = wasm_table_as_extern(
wasm_table_copy(wasm_extern_as_table_const(src)));
break;
default:
LOG_WARNING("%s meets unsupported kind: %d", __FUNCTION__,
src->kind);
break;
}
if (!dst) {
goto failed;
}
return dst;
failed:
LOG_DEBUG("%s failed", __FUNCTION__);
wasm_extern_delete(dst);
return NULL;
}
void
wasm_extern_delete(wasm_extern_t *external)
{
if (!external) {
return;
}
if (external->name) {
wasm_byte_vec_delete(external->name);
wasm_runtime_free(external->name);
external->name = NULL;
}
switch (wasm_extern_kind(external)) {
case WASM_EXTERN_FUNC:
wasm_func_delete(wasm_extern_as_func(external));
break;
case WASM_EXTERN_GLOBAL:
wasm_global_delete(wasm_extern_as_global(external));
break;
case WASM_EXTERN_MEMORY:
wasm_memory_delete(wasm_extern_as_memory(external));
break;
case WASM_EXTERN_TABLE:
wasm_table_delete(wasm_extern_as_table(external));
break;
default:
LOG_WARNING("%s meets unsupported kind: %d", __FUNCTION__,
external->kind);
break;
}
}
wasm_externkind_t
wasm_extern_kind(const wasm_extern_t *external)
{
if (!external) {
return WASM_ANYREF;
}
return external->kind;
}
own wasm_externtype_t *
wasm_extern_type(const wasm_extern_t *external)
{
if (!external) {
return NULL;
}
switch (wasm_extern_kind(external)) {
case WASM_EXTERN_FUNC:
return wasm_functype_as_externtype(
wasm_func_type(wasm_extern_as_func_const(external)));
case WASM_EXTERN_GLOBAL:
return wasm_globaltype_as_externtype(
wasm_global_type(wasm_extern_as_global_const(external)));
case WASM_EXTERN_MEMORY:
return wasm_memorytype_as_externtype(
wasm_memory_type(wasm_extern_as_memory_const(external)));
case WASM_EXTERN_TABLE:
return wasm_tabletype_as_externtype(
wasm_table_type(wasm_extern_as_table_const(external)));
default:
LOG_WARNING("%s meets unsupported kind: %d", __FUNCTION__,
external->kind);
break;
}
return NULL;
}
#define BASIC_FOUR_LIST(V) \
V(func) \
V(global) \
V(memory) \
V(table)
#define WASM_EXTERN_AS_OTHER(name) \
wasm_##name##_t *wasm_extern_as_##name(wasm_extern_t *external) \
{ \
return (wasm_##name##_t *)external; \
}
BASIC_FOUR_LIST(WASM_EXTERN_AS_OTHER)
#undef WASM_EXTERN_AS_OTHER
#define WASM_OTHER_AS_EXTERN(name) \
wasm_extern_t *wasm_##name##_as_extern(wasm_##name##_t *other) \
{ \
return (wasm_extern_t *)other; \
}
BASIC_FOUR_LIST(WASM_OTHER_AS_EXTERN)
#undef WASM_OTHER_AS_EXTERN
#define WASM_EXTERN_AS_OTHER_CONST(name) \
const wasm_##name##_t *wasm_extern_as_##name##_const( \
const wasm_extern_t *external) \
{ \
return (const wasm_##name##_t *)external; \
}
BASIC_FOUR_LIST(WASM_EXTERN_AS_OTHER_CONST)
#undef WASM_EXTERN_AS_OTHER_CONST
#define WASM_OTHER_AS_EXTERN_CONST(name) \
const wasm_extern_t *wasm_##name##_as_extern_const( \
const wasm_##name##_t *other) \
{ \
return (const wasm_extern_t *)other; \
}
BASIC_FOUR_LIST(WASM_OTHER_AS_EXTERN_CONST)
#undef WASM_OTHER_AS_EXTERN_CONST
| 28.851852 | 113 | 0.550155 | [
"vector"
] |
3c4edfdcbeea856c5348be07f7c4264a37dde693 | 3,142 | h | C | Firestore/core/src/firebase/firestore/model/document_map.h | pmendesTekever/firebase-ios-sdk | edb6a9ecfcbf231dc99f811f5cd51379933bc552 | [
"Apache-2.0"
] | 6 | 2020-01-24T07:46:49.000Z | 2020-07-30T15:51:17.000Z | Firestore/core/src/firebase/firestore/model/document_map.h | pmendesTekever/firebase-ios-sdk | edb6a9ecfcbf231dc99f811f5cd51379933bc552 | [
"Apache-2.0"
] | 3 | 2021-05-09T01:54:55.000Z | 2021-09-02T13:44:47.000Z | Firestore/core/src/firebase/firestore/model/document_map.h | pmendesTekever/firebase-ios-sdk | edb6a9ecfcbf231dc99f811f5cd51379933bc552 | [
"Apache-2.0"
] | 4 | 2020-05-16T17:45:30.000Z | 2022-02-08T16:54:41.000Z | /*
* Copyright 2018 Google
*
* 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 FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_MODEL_DOCUMENT_MAP_H_
#define FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_MODEL_DOCUMENT_MAP_H_
#include <utility>
#include "Firestore/core/src/firebase/firestore/immutable/sorted_map.h"
#include "Firestore/core/src/firebase/firestore/model/document.h"
#include "Firestore/core/src/firebase/firestore/model/document_key.h"
#include "Firestore/core/src/firebase/firestore/model/maybe_document.h"
#include "absl/base/attributes.h"
#include "absl/types/optional.h"
namespace firebase {
namespace firestore {
namespace model {
/**
* Convenience type for a map of keys to MaybeDocuments, since they are so
* common.
*/
using MaybeDocumentMap = immutable::SortedMap<DocumentKey, MaybeDocument>;
using OptionalMaybeDocumentMap =
immutable::SortedMap<DocumentKey, absl::optional<MaybeDocument>>;
/**
* Convenience type for a map of keys to Documents, since they are so common.
*
* PORTING NOTE: unlike other platforms, in C++ `Foo<Derived*>` cannot be
* converted to `Foo<Base*>`; consequently, if `DocumentMap` were simply an
* alias similar to `MaybeDocumentMap`, it couldn't be passed to functions
* expecting `MaybeDocumentMap`.
*
* To work around this, in C++ `DocumentMap` is a simple wrapper over a
* `MaybeDocumentMap` that forwards all functions to the underlying map but with
* added type safety (it only accepts `Document`, not `MaybeDocument`). Use
* `DocumentMap` in functions creating and/or returning maps that only contain
* `Document`; when the `DocumentMap` needs to be passed to a function accepting
* a `MaybeDocumentMap`, use `underlying_map` function to get (read-only) access
* to the representation. Also use `underlying_map` for iterating and searching.
*/
class DocumentMap {
public:
DocumentMap() = default;
ABSL_MUST_USE_RESULT DocumentMap insert(const DocumentKey& key,
const Document& value) const;
ABSL_MUST_USE_RESULT DocumentMap erase(const DocumentKey& key) const;
bool empty() const {
return map_.empty();
}
MaybeDocumentMap::size_type size() const {
return map_.size();
}
/** Use this function to "convert" `DocumentMap` to a `MaybeDocumentMap`. */
const MaybeDocumentMap& underlying_map() const {
return map_;
}
private:
explicit DocumentMap(MaybeDocumentMap&& map) : map_{std::move(map)} {
}
MaybeDocumentMap map_;
};
} // namespace model
} // namespace firestore
} // namespace firebase
#endif // FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_MODEL_DOCUMENT_MAP_H_
| 34.527473 | 80 | 0.745385 | [
"model"
] |
2c5efa151e165825d6de5162eb0d8bc78a5dd7ab | 10,809 | h | C | google/cloud/bigtable/internal/unary_client_utils.h | nickolasrossi/google-cloud-cpp | 979c477f31308d933b7cf7a59185048201d29bae | [
"Apache-2.0"
] | null | null | null | google/cloud/bigtable/internal/unary_client_utils.h | nickolasrossi/google-cloud-cpp | 979c477f31308d933b7cf7a59185048201d29bae | [
"Apache-2.0"
] | null | null | null | google/cloud/bigtable/internal/unary_client_utils.h | nickolasrossi/google-cloud-cpp | 979c477f31308d933b7cf7a59185048201d29bae | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Google LLC
//
// 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 GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INTERNAL_UNARY_CLIENT_UTILS_H_
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INTERNAL_UNARY_CLIENT_UTILS_H_
#include "google/cloud/bigtable/internal/grpc_error_delegate.h"
#include "google/cloud/bigtable/metadata_update_policy.h"
#include "google/cloud/bigtable/rpc_backoff_policy.h"
#include "google/cloud/bigtable/rpc_retry_policy.h"
#include <thread>
namespace google {
namespace cloud {
namespace bigtable {
inline namespace BIGTABLE_CLIENT_NS {
namespace internal {
namespace noex {
/**
* Helper functions to make (unary) gRPC calls under the right policies.
*
* Many of the gRPC calls made the the Cloud Bigtable C++ client library are
* wrapped in essentially the same loop:
*
* @code
* clone the policies for the call
* do {
* make rpc call
* return if successful
* update policies
* } while(policies allow retry);
* report failure
* @endcode
*
* The loop is not hard to write, but gets tedious, `CallWithRetry` provides a
* function that implements this loop. The code is a bit difficult because the
* signature of the gRPC functions look like this:
*
* @code
* grpc::Status (StubType::*)(grpc::ClientContext*, Request const&, Response*);
* @endcode
*
* Where `Request` and `Response` are the protos in the gRPC call.
*
* @tparam ClientType the type of the client used for the gRPC call.
*/
template <typename ClientType>
struct UnaryClientUtils {
/**
* Determine if @p T is a pointer to member function with the expected
* signature for `MakeCall()`.
*
* This is the generic case, where the type does not match the expected
* signature. The class derives from `std::false_type`, so
* `CheckSignature<T>::%value` is `false`.
*
* @tparam T the type to check against the expected signature.
*/
template <typename T>
struct CheckSignature : public std::false_type {
/// Must define ResponseType because it is used in std::enable_if<>.
using ResponseType = void;
};
/**
* Determine if a type is a pointer to member function with the correct
* signature for `MakeCall()`.
*
* This is the case where the type actually matches the expected signature.
* This class derives from `std::true_type`, so `CheckSignature<T>::%value` is
* `true`. The class also extracts the request and response types used in the
* implementation of `CallWithRetry()`.
*
* @tparam Request the RPC request type.
* @tparam Response the RPC response type.
*/
template <typename Request, typename Response>
struct CheckSignature<grpc::Status (ClientType::*)(grpc::ClientContext*,
Request const&, Response*)>
: public std::true_type {
using RequestType = Request;
using ResponseType = Response;
using MemberFunctionType = grpc::Status (ClientType::*)(
grpc::ClientContext*, Request const&, Response*);
};
/**
* Call a simple unary RPC with retries.
*
* Given a pointer to member function in the grpc StubInterface class this
* generic function calls it with retries until success or until the RPC
* policies determine that this is an error.
*
* We use std::enable_if<> to stop signature errors at compile-time. The
* `CheckSignature` meta function returns `false` if given a type that is not
* a pointer to member with the right signature, that disables this function
* altogether, and the developer gets a nice-ish error message.
*
* @tparam MemberFunction the signature of the member function.
* @param client the object that holds the gRPC stub.
* @param rpc_policy the policy controlling what failures are retryable.
* @param backoff_policy the policy controlling how long to wait before
* retrying.
* @param metadata_update_policy to keep metadata like
* x-goog-request-params.
* @param function the pointer to the member function to call.
* @param request an initialized request parameter for the RPC.
* @param error_message include this message in any exception or error log.
* @return the return parameter from the RPC.
* @throw std::exception with a description of the last RPC error.
*/
template <typename MemberFunction>
static typename std::enable_if<
CheckSignature<MemberFunction>::value,
typename CheckSignature<MemberFunction>::ResponseType>::type
MakeCall(ClientType& client,
std::unique_ptr<bigtable::RPCRetryPolicy> rpc_policy,
std::unique_ptr<bigtable::RPCBackoffPolicy> backoff_policy,
bigtable::MetadataUpdatePolicy const& metadata_update_policy,
MemberFunction function,
typename CheckSignature<MemberFunction>::RequestType const& request,
char const* error_message, grpc::Status& status,
bool retry_on_failure) {
return MakeCall(client, *rpc_policy, *backoff_policy,
metadata_update_policy, function, request, error_message,
status, retry_on_failure);
}
/**
* Call a simple unary RPC with retries borrowing the RPC policies.
*
* This implements `MakeCall()`, but does not assume ownership of the RPC
* policies. Some RPCs, notably those with pagination, can reuse most of the
* code in `MakeCall()` but must reuse the same policies across several
* calls.
*
* @tparam MemberFunction the signature of the member function.
* @param client the object that holds the gRPC stub.
* @param rpc_policy the policy controlling what failures are retryable.
* @param backoff_policy the policy controlling how long to wait before
* retrying.
* @param metadata_update_policy to keep metadata like
* x-goog-request-params.
* @param function the pointer to the member function to call.
* @param request an initialized request parameter for the RPC.
* @param error_message include this message in any exception or error log.
* @return the return parameter from the RPC.
* @throw std::exception with a description of the last RPC error.
*/
template <typename MemberFunction>
static typename std::enable_if<
CheckSignature<MemberFunction>::value,
typename CheckSignature<MemberFunction>::ResponseType>::type
MakeCall(ClientType& client, bigtable::RPCRetryPolicy& rpc_policy,
bigtable::RPCBackoffPolicy& backoff_policy,
bigtable::MetadataUpdatePolicy const& metadata_update_policy,
MemberFunction function,
typename CheckSignature<MemberFunction>::RequestType const& request,
char const* error_message, grpc::Status& status,
bool retry_on_failure) {
typename CheckSignature<MemberFunction>::ResponseType response;
do {
grpc::ClientContext client_context;
rpc_policy.Setup(client_context);
backoff_policy.Setup(client_context);
metadata_update_policy.Setup(client_context);
// Call the pointer to member function.
status = (client.*function)(&client_context, request, &response);
if (status.ok()) {
break;
}
if (!rpc_policy.OnFailure(status)) {
std::string full_message = error_message;
full_message += "(" + metadata_update_policy.value() + ") ";
full_message += status.error_message();
status = grpc::Status(status.error_code(), full_message,
status.error_details());
break;
}
auto delay = backoff_policy.OnCompletion(status);
std::this_thread::sleep_for(delay);
} while (retry_on_failure);
return response;
}
/**
* Call a simple unary RPC with no retry.
*
* Given a pointer to member function in the grpc StubInterface class this
* generic function calls it with retries until success or until the RPC
* policies determine that this is an error.
*
* We use std::enable_if<> to stop signature errors at compile-time. The
* `CheckSignature` meta function returns `false` if given a type that is not
* a pointer to member with the right signature, that disables this function
* altogether, and the developer gets a nice-ish error message.
*
* @tparam MemberFunction the signature of the member function.
* @param client the object that holds the gRPC stub.
* @param rpc_policy the policy to control timeouts.
* @param metadata_update_policy to keep metadata like
* x-goog-request-params.
* @param function the pointer to the member function to call.
* @param request an initialized request parameter for the RPC.
* @param error_message include this message in any exception or error log.
* @return the return parameter from the RPC.
* @throw std::exception with a description of the last RPC error.
*/
template <typename MemberFunction>
static typename std::enable_if<
CheckSignature<MemberFunction>::value,
typename CheckSignature<MemberFunction>::ResponseType>::type
MakeNonIdemponentCall(
ClientType& client, std::unique_ptr<bigtable::RPCRetryPolicy> rpc_policy,
bigtable::MetadataUpdatePolicy const& metadata_update_policy,
MemberFunction function,
typename CheckSignature<MemberFunction>::RequestType const& request,
char const* error_message, grpc::Status& status) {
typename CheckSignature<MemberFunction>::ResponseType response;
grpc::ClientContext client_context;
// Policies can set timeouts so allowing them to update context
rpc_policy->Setup(client_context);
metadata_update_policy.Setup(client_context);
// Call the pointer to member function.
status = (client.*function)(&client_context, request, &response);
if (!status.ok()) {
std::string full_message = error_message;
full_message += "(" + metadata_update_policy.value() + ") ";
full_message += status.error_message();
status = grpc::Status(status.error_code(), full_message,
status.error_details());
}
return response;
}
};
} // namespace noex
} // namespace internal
} // namespace BIGTABLE_CLIENT_NS
} // namespace bigtable
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_BIGTABLE_INTERNAL_UNARY_CLIENT_UTILS_H_
| 41.733591 | 80 | 0.709871 | [
"object"
] |
2c6098d1ec2d184e2b4e2e30d1b51ca7c5e984b3 | 7,317 | h | C | DataFormats/EgammaReco/interface/ElectronSeed.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DataFormats/EgammaReco/interface/ElectronSeed.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DataFormats/EgammaReco/interface/ElectronSeed.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef DataFormats_EgammaReco_ElectronSeed_h
#define DataFormats_EgammaReco_ElectronSeed_h
//********************************************************************
//
// A verson of reco::ElectronSeed which can have N hits as part of the
// 2017 upgrade of E/gamma pixel matching for the phaseI pixels
//
// author: S. Harper (RAL), 2017
//
//notes:
// While it is technically named ElectronSeed, it is effectively a new class
// However to simplify things, the name ElectronSeed was kept
// (trust me it was simplier...)
//
// Noticed that h/e values never seem to used anywhere and they are a
// mild pain to propagate in the new framework so they were removed
//
// infinities are used to mark invalid unset values to maintain
// compatibilty with the orginal ElectronSeed class
//
//description:
// An ElectronSeed is a TrajectorySeed with E/gamma specific information
// A TrajectorySeed has a series of hits associated with it
// (accessed by TrajectorySeed::nHits(), TrajectorySeed::recHits())
// and ElectronSeed stores which of those hits match well to a supercluster
// together with the matching parameters (this is known as EcalDriven).
// ElectronSeeds can be TrackerDriven in which case the matching is not done.
// It used to be fixed to two matched hits, now this is an arbitary number
// Its designed with pixel matching with mind but tries to be generally
// applicable to strips as well.
// It is worth noting that due to different ways ElectronSeeds can be created
// they do not always have all parameters filled
//
//********************************************************************
#include "DataFormats/EgammaReco/interface/ElectronSeedFwd.h"
#include "DataFormats/CaloRecHit/interface/CaloClusterFwd.h"
#include "DataFormats/TrajectorySeed/interface/TrajectorySeed.h"
#include "DataFormats/TrajectoryState/interface/TrackCharge.h"
#include "DataFormats/TrackingRecHit/interface/TrackingRecHit.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
#include "DataFormats/Common/interface/RefToBase.h"
#include "DataFormats/Common/interface/Ref.h"
#include <vector>
#include <limits>
namespace reco
{
class ElectronSeed : public TrajectorySeed {
public :
struct PMVars {
float dRZPos;
float dRZNeg;
float dPhiPos;
float dPhiNeg;
int detId; //this is already stored as the hit is stored in traj seed but a useful sanity check
int layerOrDiskNr;//redundant as stored in detId but its a huge pain to hence why its saved here
PMVars();
void setDPhi(float pos,float neg);
void setDRZ(float pos,float neg);
void setDet(int iDetId,int iLayerOrDiskNr);
};
typedef edm::OwnVector<TrackingRecHit> RecHitContainer ;
typedef edm::RefToBase<CaloCluster> CaloClusterRef ;
typedef edm::Ref<TrackCollection> CtfTrackRef ;
static std::string const & name()
{
static std::string const name_("ElectronSeed") ;
return name_;
}
//! Construction of base attributes
ElectronSeed() ;
ElectronSeed( const TrajectorySeed & ) ;
ElectronSeed( PTrajectoryStateOnDet & pts, RecHitContainer & rh, PropagationDirection & dir ) ;
ElectronSeed * clone() const { return new ElectronSeed(*this) ; }
virtual ~ElectronSeed();
//! Set additional info
void setCtfTrack( const CtfTrackRef & ) ;
void setCaloCluster( const CaloClusterRef& clus){caloCluster_=clus;isEcalDriven_=true;}
void addHitInfo(const PMVars& hitVars){hitInfo_.push_back(hitVars);}
void setNrLayersAlongTraj(int val){nrLayersAlongTraj_=val;}
//! Accessors
const CtfTrackRef& ctfTrack() const { return ctfTrack_ ; }
const CaloClusterRef& caloCluster() const { return caloCluster_ ; }
//! Utility
TrackCharge getCharge() const { return startingState().parameters().charge() ; }
bool isEcalDriven() const { return isEcalDriven_ ; }
bool isTrackerDriven() const { return isTrackerDriven_ ; }
const std::vector<PMVars>& hitInfo()const{return hitInfo_;}
float dPhiNeg(size_t hitNr)const{return getVal(hitNr,&PMVars::dPhiNeg);}
float dPhiPos(size_t hitNr)const{return getVal(hitNr,&PMVars::dPhiPos);}
float dPhiBest(size_t hitNr)const{return bestVal(dPhiNeg(hitNr),dPhiPos(hitNr));}
float dRZPos(size_t hitNr)const{return getVal(hitNr,&PMVars::dRZPos);}
float dRZNeg(size_t hitNr)const{return getVal(hitNr,&PMVars::dRZNeg);}
float dRZBest(size_t hitNr)const{return bestVal(dRZNeg(hitNr),dRZPos(hitNr));}
int detId(size_t hitNr)const{return hitNr<hitInfo_.size() ? hitInfo_[hitNr].detId : 0;}
int subDet(size_t hitNr)const{return DetId(detId(hitNr)).subdetId();}
int layerOrDiskNr(size_t hitNr)const{return getVal(hitNr,&PMVars::layerOrDiskNr);}
int nrLayersAlongTraj()const{return nrLayersAlongTraj_;}
//redundant, backwards compatible function names
//to be cleaned up asap
//no new code should use them
//they were created as time is short and there is less risk having
//the functions here rather than adapting all the function call to them in other
//CMSSW code
float dPhi1()const{return dPhiNeg(0);}
float dPhi1Pos()const{return dPhiPos(0);}
float dPhi2()const{return dPhiNeg(1);}
float dPhi2Pos()const{return dPhiPos(1);}
float dRz1()const{return dRZNeg(0);}
float dRz1Pos()const{return dRZPos(0);}
float dRz2()const{return dRZNeg(1);}
float dRz2Pos()const{return dRZPos(1);}
int subDet1()const{return subDet(0);}
int subDet2()const{return subDet(1);}
unsigned int hitsMask()const;
void initTwoHitSeed(const unsigned char hitMask);
void setNegAttributes(const float dRZ2=std::numeric_limits<float>::infinity(),
const float dPhi2=std::numeric_limits<float>::infinity(),
const float dRZ1=std::numeric_limits<float>::infinity(),
const float dPhi1=std::numeric_limits<float>::infinity());
void setPosAttributes(const float dRZ2=std::numeric_limits<float>::infinity(),
const float dPhi2=std::numeric_limits<float>::infinity(),
const float dRZ1=std::numeric_limits<float>::infinity(),
const float dPhi1=std::numeric_limits<float>::infinity());
//this is a backwards compatible function designed to
//convert old format ElectronSeeds to the new format
//only public due to root io rules, not intended for any other use
//also in theory not necessary to part of this class
static std::vector<PMVars> createHitInfo(const float dPhi1Pos,const float dPhi1Neg,
const float dRZ1Pos,const float dRZ1Neg,
const float dPhi2Pos,const float dPhi2Neg,
const float dRZ2Pos,const float dRZ2Neg,
const char hitMask,const TrajectorySeed::range recHits);
private:
static float bestVal(float val1,float val2){return std::abs(val1)<std::abs(val2) ? val1 : val2;}
template<typename T>
T getVal(unsigned int hitNr,T PMVars::*val)const{
return hitNr<hitInfo_.size() ? hitInfo_[hitNr].*val : std::numeric_limits<T>::infinity();
}
static std::vector<unsigned int> hitNrsFromMask(unsigned int hitMask);
private:
CtfTrackRef ctfTrack_;
CaloClusterRef caloCluster_;
std::vector<PMVars> hitInfo_;
int nrLayersAlongTraj_;
bool isEcalDriven_;
bool isTrackerDriven_;
};
}
#endif
| 42.789474 | 102 | 0.711767 | [
"vector"
] |
2c60d7f2ed03f1efc5a873369ad8b170b90cfc9e | 7,392 | h | C | components/net/molink/api/include/mo_netconn.h | shangliyun/lu_xing_xiang_one_os | 02b3900bbc2303291ad6b16d59f50df786af4e27 | [
"Apache-2.0"
] | 1 | 2022-03-26T09:59:37.000Z | 2022-03-26T09:59:37.000Z | components/net/molink/api/include/mo_netconn.h | shangliyun/lu_xing_xiang_one_os | 02b3900bbc2303291ad6b16d59f50df786af4e27 | [
"Apache-2.0"
] | 1 | 2021-06-24T04:27:40.000Z | 2021-06-24T04:27:40.000Z | components/net/molink/api/include/mo_netconn.h | shangliyun/lu_xing_xiang_one_os | 02b3900bbc2303291ad6b16d59f50df786af4e27 | [
"Apache-2.0"
] | 2 | 2021-06-24T04:08:28.000Z | 2022-03-07T06:37:24.000Z | /**
***********************************************************************************************************************
* Copyright (c) 2020, China Mobile Communications Group 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.
*
* @file mo_netconn.h
*
* @brief module link kit netconnect api declaration
*
* @revision
* Date Author Notes
* 2020-03-25 OneOS Team First Version
***********************************************************************************************************************
*/
#ifndef __MO_NETCONN_H__
#define __MO_NETCONN_H__
#include "mo_type.h"
#include "mo_ipaddr.h"
#include "mo_object.h"
#include <extend/os_dataqueue.h>
#ifdef MOLINK_USING_NETCONN_OPS
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
***********************************************************************************************************************
* @enum mo_netconn_stat_t
*
* @brief molink module network connect state
***********************************************************************************************************************
*/
typedef enum mo_netconn_stat
{
NETCONN_STAT_NULL = 0, /* netconn has not been created */
NETCONN_STAT_INIT, /* netconn was created but not connected */
NETCONN_STAT_CONNECT, /* netconn connect OK*/
NETCONN_STAT_CLOSE, /* netconn was closed but all connect info were not deleted */
NETCONN_STAT_UNDEFINED /* netconn undefined status */
} mo_netconn_stat_t;
/**
***********************************************************************************************************************
* @enum mo_netconn_type_t
*
* @brief molink module network connect type
***********************************************************************************************************************
*/
typedef enum mo_netconn_type
{
NETCONN_TYPE_NULL = 0,
NETCONN_TYPE_TCP,
NETCONN_TYPE_UDP,
} mo_netconn_type_t;
/**
***********************************************************************************************************************
* Used to inform the callback function about changes
*
* RCVPLUS events say: Safe to perform a potentially blocking call call once more.
* They are counted in sockets - three RCVPLUS events for accept mbox means you are safe
* to call netconn_accept 3 times without being blocked.
* Same thing for receive mbox.
*
* RCVMINUS events say: Your call to to a possibly blocking function is "acknowledged".
* Socket implementation decrements the counter.
*
* For TX, there is no need to count, its merely a flag. SENDPLUS means you may send something.
* SENDPLUS occurs when enough data was delivered to peer so netconn_send() can be called again.
* A SENDMINUS event occurs when the next call to a netconn_send() would be blocking.
***********************************************************************************************************************
*/
typedef enum mo_netconn_evt
{
MO_NETCONN_EVT_RCVPLUS,
MO_NETCONN_EVT_RCVMINUS,
MO_NETCONN_EVT_SENDPLUS,
MO_NETCONN_EVT_SENDMINUS,
MO_NETCONN_EVT_ERROR
} mo_netconn_evt_t;
struct mo_netconn;
typedef void (*mo_netconn_evt_callback)(struct mo_netconn *netconn, mo_netconn_evt_t evt, os_uint16_t len);
/**
***********************************************************************************************************************
* @struct mo_netconn_t
*
* @brief molink module network connect object
***********************************************************************************************************************
*/
typedef struct mo_netconn
{
#ifdef MOLINK_USING_SOCKETS_OPS
os_int32_t socket_id;
mo_netconn_evt_callback evt_func;
#endif
os_int32_t connect_id;
mo_netconn_stat_t stat;
mo_netconn_type_t type;
ip_addr_t remote_ip;
os_uint16_t remote_port;
os_uint16_t local_port;
os_data_queue_t data_queue;
} mo_netconn_t;
/**
***********************************************************************************************************************
* @struct mo_netconn_info_t
*
* @brief struct that holds molink module netconn information
***********************************************************************************************************************
*/
typedef struct mo_netconn_info
{
os_uint32_t netconn_nums;
const mo_netconn_t *netconn_array;
} mo_netconn_info_t;
/**
***********************************************************************************************************************
* @struct mo_netconn_ops_t
*
* @brief molink module network connect ops table
***********************************************************************************************************************
*/
typedef struct mo_netconn_ops
{
mo_netconn_t *(*create)(mo_object_t *module, mo_netconn_type_t type);
os_err_t (*destroy)(mo_object_t *module, mo_netconn_t *netconn);
os_err_t (*connect)(mo_object_t *module, mo_netconn_t *netconn, ip_addr_t addr, os_uint16_t port);
os_size_t (*send)(mo_object_t *module, mo_netconn_t *netconn, const char *data, os_size_t size);
os_err_t (*gethostbyname)(mo_object_t *module, const char *domain_name, ip_addr_t *addr);
os_err_t (*get_info)(mo_object_t *module, mo_netconn_info_t *info);
} mo_netconn_ops_t;
mo_netconn_t *mo_netconn_create(mo_object_t *module, mo_netconn_type_t type);
os_err_t mo_netconn_destroy(mo_object_t *module, mo_netconn_t *netconn);
os_err_t mo_netconn_connect(mo_object_t *module, mo_netconn_t *netconn, ip_addr_t addr, os_uint16_t port);
os_size_t mo_netconn_send(mo_object_t *module, mo_netconn_t *netconn, const char *data, os_size_t size);
os_err_t mo_netconn_recv(mo_object_t *module,
mo_netconn_t *netconn,
void **data,
os_size_t *size,
os_tick_t timeout);
os_err_t mo_netconn_gethostbyname(mo_object_t *module, const char *domain_name, ip_addr_t *addr);
/**
***********************************************************************************************************************
* @note These functions are called by the molink component
***********************************************************************************************************************
*/
os_err_t mo_netconn_get_info(mo_object_t *module, mo_netconn_info_t *info);
void mo_netconn_pasv_close_notice(mo_netconn_t *netconn);
void mo_netconn_data_recv_notice(mo_netconn_t *netconn, const char *data, os_size_t size);
void mo_netconn_data_queue_deinit(os_data_queue_t *data_queue);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MOLINK_USING_NETCONN_OPS */
#endif /* __MO_NETCONN_H__ */
| 40.615385 | 120 | 0.529627 | [
"object"
] |
2c611a63c8814cd34c6a274f15cb644b1328e549 | 822 | h | C | src/map_viewer/models/corner_layer_model.h | cogsys-tuebingen/cslibs_vectormaps | bafdea3e25db51a1324634ded30c69322faa02bb | [
"BSD-3-Clause"
] | null | null | null | src/map_viewer/models/corner_layer_model.h | cogsys-tuebingen/cslibs_vectormaps | bafdea3e25db51a1324634ded30c69322faa02bb | [
"BSD-3-Clause"
] | 1 | 2021-03-31T02:12:27.000Z | 2021-03-31T02:12:27.000Z | src/map_viewer/models/corner_layer_model.h | cogsys-tuebingen/cslibs_vectormaps | bafdea3e25db51a1324634ded30c69322faa02bb | [
"BSD-3-Clause"
] | null | null | null | #ifndef CORNERLAYERMODEL_H
#define CORNERLAYERMODEL_H
#include "point_layer_model.h"
namespace cslibs_vectormaps {
class CornerLayerModel : public PointLayerModel
{
public:
typedef std::shared_ptr<CornerLayerModel> Ptr;
typedef std::shared_ptr<CornerLayerModel const> ConstPtr;
CornerLayerModel(double alpha = 0.6);
virtual ~CornerLayerModel();
QGraphicsItem* render(const QPen& pen) override;
void update(QGraphicsItem &group, const QPen& pen) override;
void setPoints(const dxf::DXFMap::Points &points) override;
void setPoints(const QPointFList &points) override;
void setCornerness(const std::vector<double> &cornerness);
void getCornerness(std::vector<double> &cornerness) const;
private:
std::vector<double> cornerness_;
};
}
#endif // CORNERLAYERMODEL_H
| 26.516129 | 64 | 0.746959 | [
"render",
"vector"
] |
2c617d9422d98813945275ef0d689b862e6c1396 | 2,636 | h | C | Modules/Core/SpatialObjects/include/itkLineSpatialObjectPoint.h | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | 3 | 2018-10-01T20:46:17.000Z | 2019-12-17T19:39:50.000Z | Modules/Core/SpatialObjects/include/itkLineSpatialObjectPoint.h | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | null | null | null | Modules/Core/SpatialObjects/include/itkLineSpatialObjectPoint.h | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | 4 | 2018-05-17T16:34:54.000Z | 2020-09-24T02:12:40.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkLineSpatialObjectPoint_h
#define itkLineSpatialObjectPoint_h
#include "itkSpatialObjectPoint.h"
#include "itkCovariantVector.h"
#include "itkFixedArray.h"
namespace itk
{
/** \class LineSpatialObjectPoint
* \brief Point used for a line definition
*
* This class contains all the functions necessary to define a point
* that can be used to build lines.
* This Class derives from SpatialObjectPoint.
* A LineSpatialObjectPoint has NDimension-1 normals.
* \ingroup ITKSpatialObjects
*
* \wiki
* \wikiexample{SpatialObjects/LineSpatialObject,Line spatial object}
* \endwiki
*/
template< unsigned int TPointDimension = 3 >
class ITK_TEMPLATE_EXPORT LineSpatialObjectPoint:
public SpatialObjectPoint< TPointDimension >
{
public:
typedef LineSpatialObjectPoint Self;
typedef SpatialObjectPoint< TPointDimension > Superclass;
typedef Point< double, TPointDimension > PointType;
typedef CovariantVector< double, TPointDimension > VectorType;
typedef FixedArray< VectorType, TPointDimension - 1 > NormalArrayType;
/** Constructor */
LineSpatialObjectPoint();
/** Destructor */
virtual ~LineSpatialObjectPoint();
/** Get Normal */
const VectorType & GetNormal(unsigned int index) const;
/** Set Normal */
void SetNormal(VectorType & normal, unsigned int index);
/** Copy one LineSpatialObjectPoint to another */
Self & operator=(const LineSpatialObjectPoint & rhs);
protected:
NormalArrayType m_NormalArray;
/** Method to print the object. */
virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;
};
} // end of namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkLineSpatialObjectPoint.hxx"
#endif
#endif // itkLineSpatialObjectPoint_h
| 32.146341 | 79 | 0.676404 | [
"object"
] |
2c665e7feb2d5199ab8c085920c3da0c28834414 | 983 | h | C | assembler/Constants.h | arturmazurek/dcpu | 0647fc521b04ba71b793eedeb62c7add3111576c | [
"MIT"
] | null | null | null | assembler/Constants.h | arturmazurek/dcpu | 0647fc521b04ba71b793eedeb62c7add3111576c | [
"MIT"
] | null | null | null | assembler/Constants.h | arturmazurek/dcpu | 0647fc521b04ba71b793eedeb62c7add3111576c | [
"MIT"
] | null | null | null | //
// Constants.h
// dcpu
//
// Created by Artur Mazurek on 16.09.2013.
// Copyright (c) 2013 Artur Mazurek. All rights reserved.
//
#ifndef dcpu_Constants_h
#define dcpu_Constants_h
#include <map>
#include <string>
#include <vector>
#include "Opcodes.h"
#include "RegisterCode.h"
namespace Constants {
extern const std::map<std::string, RegisterCode> REGISTER_NAMES;
extern const std::map<std::string, Opcode> OPCODES_NAMES;
extern const std::map<std::string, Opcode> SPECIAL_OPCODES_NAMES;
static constexpr int ADDRESSING = 0x08;
static constexpr int ADDRESSING_AND_NEXT_WORD = 0x10;
static constexpr int PUSH_POP = 0x18;
static constexpr int PEEK = 0x19;
static constexpr int PICK = 0x1a;
static constexpr int NEXT_WORD_ADDR = 0x1e; // [next word]
static constexpr int NEXT_WORD = 0x1f; // next word (literal)
static constexpr int LITERALS_MINUS_1 = 0x20; // -1
static constexpr int LITERALS_30 = 0x3f; // 30
}
#endif
| 27.305556 | 69 | 0.712106 | [
"vector"
] |
2c6af19f394b6da7e0515fb41edbccd1a1b91f09 | 3,928 | h | C | libyara/include/yara/lexer.h | akashrb8/YARA | f17c65f720dd11693906424a389bb0ec9434e325 | [
"BSD-3-Clause"
] | 7 | 2017-12-23T04:15:24.000Z | 2019-11-02T15:02:16.000Z | libyara/include/yara/lexer.h | akashrb8/YARA | f17c65f720dd11693906424a389bb0ec9434e325 | [
"BSD-3-Clause"
] | null | null | null | libyara/include/yara/lexer.h | akashrb8/YARA | f17c65f720dd11693906424a389bb0ec9434e325 | [
"BSD-3-Clause"
] | 3 | 2017-12-22T13:55:28.000Z | 2018-11-22T01:00:37.000Z | /*
Copyright (c) 2007. Victor M. Alvarez [plusvic@gmail.com].
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <yara/compiler.h>
#undef yyparse
#undef yylex
#undef yyerror
#undef yyfatal
#undef yychar
#undef yydebug
#undef yynerrs
#undef yyget_extra
#undef yyget_lineno
#undef YY_DECL
#undef YY_FATAL_ERROR
#undef YY_EXTRA_TYPE
#define yyparse yara_yyparse
#define yylex yara_yylex
#define yyerror yara_yyerror
#define yyfatal yara_yyfatal
#define yywarning yara_yywarning
#define yychar yara_yychar
#define yydebug yara_yydebug
#define yynerrs yara_yynerrs
#define yyget_extra yara_yyget_extra
#define yyget_lineno yara_yyget_lineno
#ifndef YY_TYPEDEF_YY_SCANNER_T
#define YY_TYPEDEF_YY_SCANNER_T
typedef void* yyscan_t;
#endif
#ifndef YY_TYPEDEF_EXPRESSION_T
#define YY_TYPEDEF_EXPRESSION_T
// Expression type constants are powers of two because they are used as flags.
// For example:
// CHECK_TYPE(whatever, EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT)
// The expression above is used to ensure that the type of "whatever" is either
// integer or float.
#define EXPRESSION_TYPE_BOOLEAN 1
#define EXPRESSION_TYPE_INTEGER 2
#define EXPRESSION_TYPE_STRING 4
#define EXPRESSION_TYPE_REGEXP 8
#define EXPRESSION_TYPE_OBJECT 16
#define EXPRESSION_TYPE_FLOAT 32
typedef struct _EXPRESSION
{
int type;
union {
int64_t integer;
YR_OBJECT* object;
SIZED_STRING* sized_string;
} value;
const char* identifier;
} EXPRESSION;
union YYSTYPE;
#endif
#define YY_DECL int yylex( \
union YYSTYPE* yylval_param, yyscan_t yyscanner, YR_COMPILER* compiler)
#define YY_FATAL_ERROR(msg) yara_yyfatal(yyscanner, msg)
#define YY_EXTRA_TYPE YR_COMPILER*
#define YY_USE_CONST
int yyget_lineno(yyscan_t yyscanner);
int yylex(
union YYSTYPE* yylval_param,
yyscan_t yyscanner,
YR_COMPILER* compiler);
int yyparse(
void *yyscanner,
YR_COMPILER* compiler);
void yyerror(
yyscan_t yyscanner,
YR_COMPILER* compiler,
const char *error_message);
void yywarning(
yyscan_t yyscanner,
const char *message_fmt,
...);
void yyfatal(
yyscan_t yyscanner,
const char *error_message);
YY_EXTRA_TYPE yyget_extra(
yyscan_t yyscanner);
int yr_lex_parse_rules_string(
const char* rules_string,
YR_COMPILER* compiler);
int yr_lex_parse_rules_file(
FILE* rules_file,
YR_COMPILER* compiler);
int yr_lex_parse_rules_fd(
YR_FILE_DESCRIPTOR rules_fd,
YR_COMPILER* compiler);
| 26.186667 | 80 | 0.776986 | [
"object"
] |
2c6cb6ee7f8e92e78c02c7207a868300427260a2 | 8,422 | h | C | labsound/third_party/STK/FreeVerb.h | ngokevin/LabSound | 1cd830e44befae10111675a2799dee3082e6ae1f | [
"MIT"
] | 6 | 2018-02-24T05:55:56.000Z | 2018-12-09T05:09:33.000Z | labsound/third_party/STK/FreeVerb.h | ngokevin/LabSound | 1cd830e44befae10111675a2799dee3082e6ae1f | [
"MIT"
] | 10 | 2018-06-05T09:45:19.000Z | 2019-05-24T12:53:03.000Z | labsound/third_party/STK/FreeVerb.h | ngokevin/LabSound | 1cd830e44befae10111675a2799dee3082e6ae1f | [
"MIT"
] | 3 | 2018-03-29T16:16:03.000Z | 2018-10-16T02:53:42.000Z | #ifndef STK_FREEVERB_H
#define STK_FREEVERB_H
#include "Effect.h"
#include "Delay.h"
#include "OnePole.h"
namespace stk {
/***********************************************************************/
/*! \class FreeVerb
\brief Jezar at Dreampoint's FreeVerb, implemented in STK.
Freeverb is a free and open-source Schroeder reverberator
originally implemented in C++. The parameters of the reverberation
model are exceptionally well tuned. FreeVerb uses 8
lowpass-feedback-comb-filters in parallel, followed by 4 Schroeder
allpass filters in series. The input signal can be either mono or
stereo, and the output signal is stereo. The delay lengths are
optimized for a sample rate of 44100 Hz.
Ported to STK by Gregory Burlet, 2012.
*/
/***********************************************************************/
class FreeVerb : public Effect
{
public:
//! FreeVerb Constructor
/*!
Initializes the effect with default parameters. Note that these defaults
are slightly different than those in the original implementation of
FreeVerb [Effect Mix: 0.75; Room Size: 0.75; Damping: 0.25; Width: 1.0;
Mode: freeze mode off].
*/
FreeVerb();
//! Destructor
~FreeVerb();
//! Set the effect mix [0 = mostly dry, 1 = mostly wet].
void setEffectMix( StkFloat mix );
//! Set the room size (comb filter feedback gain) parameter [0,1].
void setRoomSize( StkFloat value );
//! Get the room size (comb filter feedback gain) parameter.
StkFloat getRoomSize( void );
//! Set the damping parameter [0=low damping, 1=higher damping].
void setDamping( StkFloat value );
//! Get the damping parameter.
StkFloat getDamping( void );
//! Set the width (left-right mixing) parameter [0,1].
void setWidth( StkFloat value );
//! Get the width (left-right mixing) parameter.
StkFloat getWidth( void );
//! Set the mode [frozen = 1, unfrozen = 0].
void setMode( bool isFrozen );
//! Get the current freeze mode [frozen = 1, unfrozen = 0].
StkFloat getMode( void );
//! Clears delay lines, etc.
void clear( void );
//! Return the specified channel value of the last computed stereo frame.
/*!
Use the lastFrame() function to get both values of the last
computed stereo frame. The \c channel argument must be 0 or 1
(the first channel is specified by 0). However, range checking is
only performed if _STK_DEBUG_ is defined during compilation, in
which case an out-of-range value will trigger an StkError
exception.
*/
StkFloat lastOut( unsigned int channel = 0 );
//! Input one or two samples to the effect and return the specified \c channel value of the computed stereo frame.
/*!
Use the lastFrame() function to get both values of the computed
stereo output frame. The \c channel argument must be 0 or 1 (the
first channel is specified by 0). However, range checking is only
performed if _STK_DEBUG_ is defined during compilation, in which
case an out-of-range value will trigger an StkError exception.
*/
StkFloat tick( StkFloat inputL, StkFloat inputR = 0.0, unsigned int channel = 0 );
//! Take two channels of the StkFrames object as inputs to the effect and replace with stereo outputs.
/*!
The StkFrames argument reference is returned. The stereo
inputs are taken from (and written back to) the StkFrames argument
starting at the specified \c channel. Therefore, the \c channel
argument must be less than ( channels() - 1 ) of the StkFrames
argument (the first channel is specified by 0). However, range
checking is only performed if _STK_DEBUG_ is defined during
compilation, in which case an out-of-range value will trigger an
StkError exception.
*/
StkFrames& tick( StkFrames& frames, unsigned int channel = 0 );
//! Take one or two channels of the \c iFrames object as inputs to the effect and write stereo outputs to the \c oFrames object.
/*!
The \c iFrames object reference is returned. The \c iChannel
argument must be less than the number of channels in the \c
iFrames argument (the first channel is specified by 0). If more
than one channel of data exists in \c iFrames starting from \c
iChannel, stereo data is input to the effect. The \c oChannel
argument must be less than ( channels() - 1 ) of the \c oFrames
argument. However, range checking is only performed if
_STK_DEBUG_ is defined during compilation, in which case an
out-of-range value will trigger an StkError exception.
*/
StkFrames& tick( StkFrames& iFrames, StkFrames &oFrames, unsigned int iChannel = 0, unsigned int oChannel = 0 );
protected:
//! Update interdependent parameters.
void update( void );
// Clamp very small floats to zero, version from
// http://music.columbia.edu/pipermail/linux-audio-user/2004-July/013489.html .
// However, this is for 32-bit floats only.
//static inline StkFloat undenormalize( volatile StkFloat s ) {
// s += 9.8607615E-32f;
// return s - 9.8607615E-32f;
//}
static const int nCombs = 8;
static const int nAllpasses = 4;
static const int stereoSpread = 23;
static const StkFloat fixedGain;
static const StkFloat scaleWet;
static const StkFloat scaleDry;
static const StkFloat scaleDamp;
static const StkFloat scaleRoom;
static const StkFloat offsetRoom;
// Delay line lengths for 44100Hz sampling rate.
static int cDelayLengths[nCombs];
static int aDelayLengths[nAllpasses];
StkFloat g_; // allpass coefficient
StkFloat gain_;
StkFloat roomSizeMem_, roomSize_;
StkFloat dampMem_, damp_;
StkFloat wet1_, wet2_;
StkFloat dry_;
StkFloat width_;
bool frozenMode_;
// LBFC: Lowpass Feedback Comb Filters
Delay combDelayL_[nCombs];
Delay combDelayR_[nCombs];
OnePole combLPL_[nCombs];
OnePole combLPR_[nCombs];
// AP: Allpass Filters
Delay allPassDelayL_[nAllpasses];
Delay allPassDelayR_[nAllpasses];
};
inline StkFloat FreeVerb :: lastOut( unsigned int channel )
{
#if defined(_STK_DEBUG_)
if ( channel > 1 ) {
oStream_ << "FreeVerb::lastOut(): channel argument must be less than 2!";
handleError( StkError::FUNCTION_ARGUMENT );
}
#endif
return lastFrame_[channel];
}
inline StkFloat FreeVerb::tick( StkFloat inputL, StkFloat inputR, unsigned int channel )
{
#if defined(_STK_DEBUG_)
if ( channel > 1 ) {
oStream_ << "FreeVerb::tick(): channel argument must be less than 2!";
handleError(StkError::FUNCTION_ARGUMENT);
}
#endif
if ( !inputR ) {
inputR = inputL;
}
StkFloat fInput = (inputL + inputR) * gain_;
StkFloat outL = 0.0;
StkFloat outR = 0.0;
// Parallel LBCF filters
for ( int i = 0; i < nCombs; i++ ) {
// Left channel
//StkFloat yn = fInput + (roomSize_ * FreeVerb::undenormalize(combLPL_[i].tick(FreeVerb::undenormalize(combDelayL_[i].nextOut()))));
StkFloat yn = fInput + (roomSize_ * combLPL_[i].tick( combDelayL_[i].nextOut() ) );
combDelayL_[i].tick(yn);
outL += yn;
// Right channel
//yn = fInput + (roomSize_ * FreeVerb::undenormalize(combLPR_[i].tick(FreeVerb::undenormalize(combDelayR_[i].nextOut()))));
yn = fInput + (roomSize_ * combLPR_[i].tick( combDelayR_[i].nextOut() ) );
combDelayR_[i].tick(yn);
outR += yn;
}
// Series allpass filters
for ( int i = 0; i < nAllpasses; i++ ) {
// Left channel
//StkFloat vn_m = FreeVerb::undenormalize(allPassDelayL_[i].nextOut());
StkFloat vn_m = allPassDelayL_[i].nextOut();
StkFloat vn = outL + (g_ * vn_m);
allPassDelayL_[i].tick(vn);
// calculate output
outL = -vn + (1.0 + g_)*vn_m;
// Right channel
//vn_m = FreeVerb::undenormalize(allPassDelayR_[i].nextOut());
vn_m = allPassDelayR_[i].nextOut();
vn = outR + (g_ * vn_m);
allPassDelayR_[i].tick(vn);
// calculate output
outR = -vn + (1.0 + g_)*vn_m;
}
// Mix output
lastFrame_[0] = outL*wet1_ + outR*wet2_ + inputL*dry_;
lastFrame_[1] = outR*wet1_ + outL*wet2_ + inputR*dry_;
/*
// Hard limiter ... there's not much else we can do at this point
if ( lastFrame_[0] >= 1.0 ) {
lastFrame_[0] = 0.9999;
}
if ( lastFrame_[0] <= -1.0 ) {
lastFrame_[0] = -0.9999;
}
if ( lastFrame_[1] >= 1.0 ) {
lastFrame_[1] = 0.9999;
}
if ( lastFrame_[1] <= -1.0 ) {
lastFrame_[1] = -0.9999;
}
*/
return lastFrame_[channel];
}
}
#endif
| 32.898438 | 136 | 0.673712 | [
"object",
"model"
] |
2c6cf8e24d74d6a2b1fcb317a28c1922b32465af | 1,208 | h | C | 3rdParty/Code/3rdParty/three20/Three20UI/TTNavigator.h | jorgemhtdev/rogerthat-ios-client | 2041c605b5f3b9a3daaf748ea6cb8290debfc7c4 | [
"Apache-2.0"
] | null | null | null | 3rdParty/Code/3rdParty/three20/Three20UI/TTNavigator.h | jorgemhtdev/rogerthat-ios-client | 2041c605b5f3b9a3daaf748ea6cb8290debfc7c4 | [
"Apache-2.0"
] | 4 | 2021-06-12T12:04:15.000Z | 2022-03-12T00:58:32.000Z | 3rdParty/Code/3rdParty/three20/Three20UI/TTNavigator.h | jorgemhtdev/rogerthat-ios-client | 2041c605b5f3b9a3daaf748ea6cb8290debfc7c4 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2009-2011 Facebook
//
// 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 "TTBaseNavigator.h"
/**
* Shortcut for calling [[TTNavigator navigator] openURL:]
*/
UIViewController* TTOpenURL(NSString* URL);
/**
* Shortcut for calling [[TTBaseNavigator navigatorForView:view] openURL:]
*/
UIViewController* TTOpenURLFromView(NSString* URL, UIView* view);
/**
* A URL-based navigation system with built-in persistence.
* Add support for model-based controllers and implement the legacy global instance accessor.
*/
@interface TTNavigator : TTBaseNavigator {
}
+ (TTNavigator*)navigator;
/**
* Reloads the content in the visible view controller.
*/
- (void)reload;
@end
| 27.454545 | 93 | 0.739238 | [
"model"
] |
2c80c1c1465d7d763aa02c14cccaae8e019ea4ef | 1,675 | h | C | embeddedCNN/include/common.h | yuehniu/embeddedCNN | 1067867830300cc55b4573d633c9fa1226c64868 | [
"MIT"
] | 21 | 2018-07-10T07:47:51.000Z | 2021-12-03T05:47:30.000Z | embeddedCNN/include/common.h | honorpeter/embeddedCNN | 1067867830300cc55b4573d633c9fa1226c64868 | [
"MIT"
] | 3 | 2018-09-05T03:09:40.000Z | 2019-04-15T10:01:40.000Z | embeddedCNN/include/common.h | honorpeter/embeddedCNN | 1067867830300cc55b4573d633c9fa1226c64868 | [
"MIT"
] | 8 | 2018-06-10T02:04:09.000Z | 2021-12-03T05:47:31.000Z | /*
Desc:
This file contains several pre-define parameter for the system.
Date:
06/04/2018
Author:
Yue Niu
*/
#ifndef __COMMON_H__
#define __COMMON_H__
#include "hls_half.h"
/* Data type */
#define ATOM_NUM 1
typedef half Dtype;
typedef struct idata_struct{
Dtype d0;
} IData;
/* Network definition for VGG16 */
#define CLASS_NUM 1000
#define CONV_LAYER_NUM 13
#define FC_LAYER_NUM 5
#define IMG_W 224
#define IMG_H 224
/* Conv params */
// Input channel tile size
#define ITILE 16
#define ITILSHFT 4
// Output channel title size
#define OTILE 32
#define OTILSHFT 5
// Feature map title size(3x224)
// This set is suitable for input with 224x224,
// kernel size with 3x3
#define FTILE_W 224
#define FTILE_H 1
// Define buffer depth for weights and bias
// Note the buffer depth is closely related to kernel size,
// input and output kernel number
#define W_BUF_DEPTH 1152
#define B_BUF_DEPTH 16
// Define buffer depth for output
// Note this buffer depth is also closely related to model,
// mainly including maximum output channel number.
#define O_BUF_CHNL 512
#define O_BUF_SEC 16 // 512/32
// Define the number of rows buffered in output buffer.
// This number is closely related to kernel size and strides.
#define I_BUF_DEPTH 1000
#define I_PRE_DEPTH 1920
#define O_BUF_DEPTH (16 * 28 * 28)
/* FC params */
#define I_LENGTH (512 * 7 * 7)
#define P_LENGTH 13673960 // (25088*256+256+256*4096+4096+4096*256+256+256*4096+4096+4096*1000+1000)
#define BUFA_DEPTH 4096
#define BUFB_DEPTH 1024
/* Conv unit interface */
#define FTRANS_SIZE (3 * 224 * 224)
#define PTRANS_SIZE (512 * 512 * 3 * 3)
#endif /* __COMMON_H__ */
| 22.945205 | 100 | 0.728358 | [
"model"
] |
2c819d609f3f44a61485dee5c16701c462a4cafc | 10,128 | h | C | tools/FMM_3DSMAX_ExportPlugin/extern/maxsdk2012/include/impexp.h | FrankHB/fancy2d | 522a34c53c1c1a29ee53bbdef0771a9b0b51a980 | [
"BSD-3-Clause"
] | 42 | 2015-03-01T14:14:48.000Z | 2019-10-06T06:02:16.000Z | tools/FMM_3DSMAX_ExportPlugin/extern/maxsdk2012/include/impexp.h | FrankHB/fancy2d | 522a34c53c1c1a29ee53bbdef0771a9b0b51a980 | [
"BSD-3-Clause"
] | 9 | 2015-04-07T16:10:14.000Z | 2018-05-07T12:42:50.000Z | tools/FMM_3DSMAX_ExportPlugin/extern/maxsdk2012/include/impexp.h | FrankHB/fancy2d | 522a34c53c1c1a29ee53bbdef0771a9b0b51a980 | [
"BSD-3-Clause"
] | 28 | 2015-01-31T05:03:37.000Z | 2021-08-15T21:27:10.000Z | /**********************************************************************
*<
FILE: impexp.h
DESCRIPTION: Includes for importing and exporting geometry files
CREATED BY: Tom Hudson
HISTORY: Created 26 December 1994
*> Copyright (c) 1994, All Rights Reserved.
**********************************************************************/
#pragma once
#include <WTypes.h>
#include "maxheap.h"
#include "buildver.h"
#include "strbasic.h"
// forward declarations
class ImpInterface;
class ExpInterface;
class Interface;
// Returned by DoImport, DoExport
#define IMPEXP_FAIL 0
#define IMPEXP_SUCCESS 1
#define IMPEXP_CANCEL 2
// SceneImport::ZoomExtents return values
#define ZOOMEXT_NOT_IMPLEMENTED -1 // The default (uses Preferences value)
#define ZOOMEXT_YES TRUE // Zoom extents after import
#define ZOOMEXT_NO FALSE // No zoom extents
// The scene import/export classes. Right now, these are very similar, but this may change as things develop
/*! \sa Class ImpInterface, Class Interface.\n\n
\par Description:
This is a base class for creating file import plug-ins. The plug-in implements
methods of this class to describe the properties of the import plug-in and a
method that handles the actual import process. */
class SceneImport : public MaxHeapOperators
{
public:
/*! \remarks Constructor. */
SceneImport() {};
/*! \remarks Destructor. */
virtual ~SceneImport() {};
/*! \remarks Returns the number of file name extensions supported by the plug-in. */
virtual int ExtCount() = 0;
/*! \remarks Returns the 'i-th' file name extension (i.e. "3DS").
\par Parameters:
<b>int i</b>\n\n
The index of the file name extension to return. */
virtual const MCHAR * Ext(int n) = 0; // Extension #n (i.e. "3DS")
/*! \remarks Returns a long ASCII description of the file type being imported (i.e.
"Autodesk 3D Studio File"). */
virtual const MCHAR * LongDesc() = 0; // Long ASCII description (i.e. "Autodesk 3D Studio File")
/*! \remarks Returns a short ASCII description of the file type being imported (i.e. "3D
Studio"). */
virtual const MCHAR * ShortDesc() = 0; // Short ASCII description (i.e. "3D Studio")
/*! \remarks Returns the ASCII Author name. */
virtual const MCHAR * AuthorName() = 0; // ASCII Author name
/*! \remarks Returns the ASCII Copyright message for the plug-in. */
virtual const MCHAR * CopyrightMessage() = 0; // ASCII Copyright message
/*! \remarks Returns the first message string that is displayed. */
virtual const MCHAR * OtherMessage1() = 0; // Other message #1
/*! \remarks Returns the second message string that is displayed. */
virtual const MCHAR * OtherMessage2() = 0; // Other message #2
/*! \remarks Returns the version number of the import plug-in. The format is the version
number * 100 (i.e. v3.01 = 301). */
virtual unsigned int Version() = 0; // Version number * 100 (i.e. v3.01 = 301)
/*! \remarks This method is called to have the plug-in display its "About..." box.
\par Parameters:
<b>HWND hWnd</b>\n\n
The parent window handle for the dialog. */
virtual void ShowAbout(HWND hWnd) = 0; // Show DLL's "About..." box
/*! \remarks This method actually performs the file import.
\par Parameters:
<b>const MCHAR *name</b>\n\n
The file name chosen by the user to import.\n\n
<b>ImpInterface *ii</b>\n\n
An import interface pointer that may be used to create objects and nodes in
the scene.\n\n
<b>Interface *i</b>\n\n
Pass the 3ds Max interface pointer here.\n\n
<b>BOOL suppressPrompts=FALSE</b>\n\n
This parameter is available in release 2.0 and later only.\n\n
When TRUE, the plug-in must not display any dialogs requiring user input.
It is up to the plug-in as to how to handle error conditions or situations
requiring user input. This is an option set up for the 3ds Max API in order
for plug-in developers to create batch import plugins which operate
unattended. See <b>Interface::ImportFromFile()</b>.
\return One of the following three values should be returned\n\n
<b>#define IMPEXP_FAIL 0</b>\n\n
<b>#define IMPEXP_SUCCESS 1</b>\n\n
<b> #define IMPEXP_CANCEL 2</b> */
virtual int DoImport(const MCHAR *name,ImpInterface *ii,Interface *i, BOOL suppressPrompts=FALSE) = 0; // Import file
/*! \remarks This method is used to control the zoom extents done after the import is
accomplished. It returns a value that indicates if the plug-in should
override the user preference setting.\n\n
Also see the method <b>Interface::GetImportZoomExtents()</b> which returns
the state of the system zoom extents flag.
\return One of the following values:\n\n
<b>ZOOMEXT_NOT_IMPLEMENTED</b>\n\n
Indicates to use the preference setting.\n\n
<b>ZOOMEXT_YES</b>\n\n
Indicates to do a zoom extents after import regardless of the preference
setting.\n\n
<b>ZOOMEXT_NO</b>\n\n
Indicates to <b>not</b> do a zoom extents regardless of the preference
setting.
\par Default Implementation:
<b>{ return ZOOMEXT_NOT_IMPLEMENTED; }</b> */
virtual int ZoomExtents() { return ZOOMEXT_NOT_IMPLEMENTED; } // Override this for zoom extents control
};
// SceneExport::DoExport options flags:
#define SCENE_EXPORT_SELECTED (1<<0)
/*! \sa Class ExpInterface, Class Interface.\n\n
\par Description:
This is a base class for creating file export plug-ins. The plug-in implements
methods of this class to describe the properties of the export plug-in and a
method that handles the actual export process. */
class SceneExport : public MaxHeapOperators
{
public:
/*! \remarks Constructor. */
SceneExport() {};
/*! \remarks Destructor. */
virtual ~SceneExport() {};
/*! \remarks Returns the number of file name extensions supported by the plug-in. */
virtual int ExtCount() = 0;
/*! \remarks Returns the 'i-th' file name extension (i.e. "3DS").
\par Parameters:
<b>int i</b>\n\n
The index of the file name extension to return. */
virtual const MCHAR * Ext(int n) = 0; // Extension #n (i.e. "3DS")
/*! \remarks Returns a long ASCII description of the file type being exported (i.e.
"Autodesk 3D Studio File"). */
virtual const MCHAR * LongDesc() = 0; // Long ASCII description (i.e. "Autodesk 3D Studio File")
/*! \remarks Returns a short ASCII description of the file type being exported (i.e. "3D
Studio"). */
virtual const MCHAR * ShortDesc() = 0; // Short ASCII description (i.e. "3D Studio")
/*! \remarks Returns the ASCII Author name. */
virtual const MCHAR * AuthorName() = 0; // ASCII Author name
/*! \remarks Returns the ASCII Copyright message for the plug-in. */
virtual const MCHAR * CopyrightMessage() = 0; // ASCII Copyright message
/*! \remarks Returns the first message string that is displayed. */
virtual const MCHAR * OtherMessage1() = 0; // Other message #1
/*! \remarks Returns the second message string that is displayed. */
virtual const MCHAR * OtherMessage2() = 0; // Other message #2
/*! \remarks Returns the version number of the export plug-in. The format is the version
number * 100 (i.e. v3.01 = 301). */
virtual unsigned int Version() = 0; // Version number * 100 (i.e. v3.01 = 301)
/*! \remarks This method is called to have the plug-in display its "About..." box.
\par Parameters:
<b>HWND hWnd</b>\n\n
The parent window handle for the dialog. */
virtual void ShowAbout(HWND hWnd) = 0; // Show DLL's "About..." box
/*! \remarks This method is called for the plug-in to perform its file export.
\par Parameters:
<b>const MCHAR *name</b>\n\n
The export file name.\n\n
<b>ExpInterface *ei</b>\n\n
A pointer the plug-in may use to call methods to enumerate the scene.\n\n
<b>Interface *i</b>\n\n
An interface pointer the plug-in may use to call methods of 3ds Max.\n\n
<b>BOOL suppressPrompts=FALSE</b>\n\n
This parameter is available in release 2.0 and later only.\n\n
When TRUE, the plug-in must not display any dialogs requiring user input.
It is up to the plug-in as to how to handle error conditions or situations
requiring user input. This is an option set up for the 3ds Max API in order
for plug-in developers to create batch export plugins which operate
unattended. See <b>Interface::ExportToFile()</b>.\n\n
<b>DWORD options=0</b>\n\n
This parameter is available in release 3.0 and later only.\n\n
In order to support export of selected objects (as well as future
enhancements), this method now has this additional parameter. The only
currently defined option is:\n\n
<b>SCENE_EXPORT_SELECTED</b>\n\n
When this bit is set the export module should only export the selected
nodes.
\return One of the following three values should be returned\n\n
<b>#define IMPEXP_FAIL 0</b>\n\n
<b>#define IMPEXP_SUCCESS 1</b>\n\n
<b> #define IMPEXP_CANCEL 2</b> */
virtual int DoExport(const MCHAR *name,ExpInterface *ei,Interface *i, BOOL suppressPrompts=FALSE, DWORD options=0) = 0; // Export file
/*! \remarks This method is called by 3ds Max to determine if one or more export options
are supported by a plug-in for a given extension. It should return TRUE if
all option bits set are supported for this extension; otherwise FALSE.\n\n
Note that the method has a default implementation defined in order to
provide easy backward compatibility. It returns FALSE, indicating that no
options are supported.
\par Parameters:
<b>int ext</b>\n\n
This parameter indicates which extension the options are being queried for,
based on the number of extensions returned by the
<b>SceneExport::ExtCount()</b> method. This index is zero based.\n\n
<b>DWORD options</b>\n\n
This parameter specifies which options are being queried, and may have more
than one option specified. At present, the only export option is
<b>SCENE_EXPORT_SELECTED</b>, but this may change in the future. If more
than one option is specified in this field, the plugin should only return
TRUE if all of the options are supported. If one or more of the options are
not supported, the plugin should return FALSE.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL SupportsOptions(int ext, DWORD options) { UNUSED_PARAM(ext); UNUSED_PARAM(options); return FALSE;}
};
| 44.421053 | 138 | 0.712382 | [
"geometry",
"3d"
] |
2c8321e4cd3645b4de47265bb6685831eefec91f | 1,801 | h | C | include/ECSpp/internal/utility/Pool.h | Exepp/ECSpp | fb7ba249e538ae6cdd910cfe2b28aa1000dbcc11 | [
"MIT"
] | null | null | null | include/ECSpp/internal/utility/Pool.h | Exepp/ECSpp | fb7ba249e538ae6cdd910cfe2b28aa1000dbcc11 | [
"MIT"
] | null | null | null | include/ECSpp/internal/utility/Pool.h | Exepp/ECSpp | fb7ba249e538ae6cdd910cfe2b28aa1000dbcc11 | [
"MIT"
] | null | null | null | #ifndef EPP_POOL_H
#define EPP_POOL_H
#include <ECSpp/external/llvm/SmallVector.h>
#include <ECSpp/internal/utility/Assert.h>
#include <cmath>
#include <memory>
#include <vector>
namespace epp {
inline std::size_t SizeToFitNextN(std::size_t n, std::size_t reserved, std::size_t freeLeft)
{
return freeLeft >= n ? reserved : llvm::NextPowerOf2(reserved + (n - freeLeft) - 1);
}
/**
* A Vector that does not maintain order - the last component is always moved in the place of a removed one
*/
template <typename T>
struct Pool {
using Container_t = std::vector<T>;
/// Creates a new element with emplace_back
/**
* @param arg Arguments forwarded to the emplace_back
* @returns A reference to the created object
*/
template <typename... U>
inline T& create(U&&... arg)
{
return data.emplace_back(std::forward<U>(arg)...);
}
/// Removes the object located at a given index
/**
* Moves the last element in place of the removed one
* @param idx index of the element to be deleted
* @returns False if idx was the last element, True otherwise
*/
inline bool destroy(std::size_t idx)
{
EPP_ASSERT(idx < data.size());
bool notLast = (idx + 1) < data.size();
if (notLast) {
data[idx].~T();
new (&data[idx]) T(std::move(data.back()));
}
data.pop_back();
return notLast;
}
/// The next n create(...) calls will not require reallocation
/**
* @param n Number of elements to reserve the additional memory for
*/
void fitNextN(std::size_t n)
{
data.reserve(SizeToFitNextN(n, data.capacity(), data.capacity() - data.size()));
}
Container_t data;
};
} // namespace epp
#endif // EPP_POOL_H | 24.013333 | 107 | 0.622432 | [
"object",
"vector"
] |
2c884ceedfb9cc369558ec76502b2a0fa5581ba2 | 3,252 | h | C | Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Pass/RasterPass.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <Atom/RHI.Reflect/Handle.h>
#include <Atom/RHI.Reflect/Scissor.h>
#include <Atom/RHI.Reflect/Viewport.h>
#include <Atom/RPI.Public/Pass/PassUtils.h>
#include <Atom/RPI.Public/Pass/RenderPass.h>
#include <Atom/RPI.Public/Shader/ShaderResourceGroup.h>
namespace AZ
{
namespace RPI
{
//! A RasterPass is a leaf pass (pass with no children) that is used for rasterization.
class RasterPass
: public RenderPass
{
AZ_RPI_PASS(RasterPass);
public:
AZ_RTTI(RasterPass, "{16AF74ED-743C-4842-99F9-347D77BA7F2A}", RenderPass);
AZ_CLASS_ALLOCATOR(RasterPass, SystemAllocator, 0);
virtual ~RasterPass();
//! Creates a RasterPass
static Ptr<RasterPass> Create(const PassDescriptor& descriptor);
// Draw List & Pipeline View Tags
RHI::DrawListTag GetDrawListTag() const override;
void SetDrawListTag(Name drawListName);
void SetPipelineStateDataIndex(uint32_t index);
//! Expose shader resource group.
ShaderResourceGroup* GetShaderResourceGroup();
uint32_t GetDrawItemCount();
protected:
explicit RasterPass(const PassDescriptor& descriptor);
// Pass behavior overrides
void Validate(PassValidationResults& validationResults) override;
void FrameBeginInternal(FramePrepareParams params) override;
// Scope producer functions...
void SetupFrameGraphDependencies(RHI::FrameGraphInterface frameGraph) override;
void CompileResources(const RHI::FrameGraphCompileContext& context) override;
void BuildCommandListInternal(const RHI::FrameGraphExecuteContext& context) override;
// Retrieve draw lists from view and dynamic draw system and generate final draw list
void UpdateDrawList();
// The draw list tag used to fetch the draw list from the views
RHI::DrawListTag m_drawListTag;
// Multiple passes with the same drawListTag can have different pipeline state data (see Scene.h)
// This is the index of the pipeline state data that corresponds to this pass in the array of pipeline state data
RHI::Handle<> m_pipelineStateDataIndex;
// The reference of the draw list to be drawn
RHI::DrawListView m_drawListView;
// If there are more than one draw lists from different source: View, DynamicDrawSystem,
// we need to creates a combined draw list which combines all the draw lists to one and cache it until they are submitted.
RHI::DrawList m_combinedDrawList;
RHI::Scissor m_scissorState;
RHI::Viewport m_viewportState;
bool m_overrideScissorSate = false;
bool m_overrideViewportState = false;
uint32_t m_drawItemCount = 0;
};
} // namespace RPI
} // namespace AZ
| 38.258824 | 135 | 0.660209 | [
"3d"
] |
2c8c1fee76e267df65ce16d571ea0ea04248515c | 13,912 | h | C | ui/views/accessibility/native_view_accessibility_win.h | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-16T03:57:28.000Z | 2021-01-23T15:29:45.000Z | ui/views/accessibility/native_view_accessibility_win.h | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/views/accessibility/native_view_accessibility_win.h | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-03-15T13:21:38.000Z | 2017-03-15T13:21:38.000Z | // Copyright (c) 2012 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 UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_WIN_H_
#define UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_WIN_H_
#include <atlbase.h>
#include <atlcom.h>
#include <oleacc.h>
#include <UIAutomationCore.h>
#include <set>
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/views/accessibility/native_view_accessibility.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/view.h"
namespace ui {
enum TextBoundaryDirection;
enum TextBoundaryType;
}
namespace views {
////////////////////////////////////////////////////////////////////////////////
//
// NativeViewAccessibilityWin
//
// Class implementing the MSAA IAccessible COM interface for a generic View,
// providing accessibility to be used by screen readers and other assistive
// technology (AT).
//
////////////////////////////////////////////////////////////////////////////////
class __declspec(uuid("26f5641a-246d-457b-a96d-07f3fae6acf2"))
NativeViewAccessibilityWin
: public CComObjectRootEx<CComMultiThreadModel>,
public IDispatchImpl<IAccessible2, &IID_IAccessible2,
&LIBID_IAccessible2Lib>,
public IAccessibleText,
public IServiceProvider,
public IAccessibleEx,
public IRawElementProviderSimple,
public NativeViewAccessibility {
public:
BEGIN_COM_MAP(NativeViewAccessibilityWin)
COM_INTERFACE_ENTRY2(IDispatch, IAccessible2)
COM_INTERFACE_ENTRY2(IAccessible, IAccessible2)
COM_INTERFACE_ENTRY(IAccessible2)
COM_INTERFACE_ENTRY(IAccessibleText)
COM_INTERFACE_ENTRY(IServiceProvider)
COM_INTERFACE_ENTRY(IAccessibleEx)
COM_INTERFACE_ENTRY(IRawElementProviderSimple)
END_COM_MAP()
virtual ~NativeViewAccessibilityWin();
// NativeViewAccessibility.
virtual void NotifyAccessibilityEvent(
ui::AXEvent event_type) OVERRIDE;
virtual gfx::NativeViewAccessible GetNativeObject() OVERRIDE;
virtual void Destroy() OVERRIDE;
void set_view(views::View* view) { view_ = view; }
// Supported IAccessible methods.
// Retrieves the child element or child object at a given point on the screen.
virtual STDMETHODIMP accHitTest(LONG x_left, LONG y_top, VARIANT* child);
// Performs the object's default action.
STDMETHODIMP accDoDefaultAction(VARIANT var_id);
// Retrieves the specified object's current screen location.
STDMETHODIMP accLocation(LONG* x_left,
LONG* y_top,
LONG* width,
LONG* height,
VARIANT var_id);
// Traverses to another UI element and retrieves the object.
STDMETHODIMP accNavigate(LONG nav_dir, VARIANT start, VARIANT* end);
// Retrieves an IDispatch interface pointer for the specified child.
virtual STDMETHODIMP get_accChild(VARIANT var_child, IDispatch** disp_child);
// Retrieves the number of accessible children.
virtual STDMETHODIMP get_accChildCount(LONG* child_count);
// Retrieves a string that describes the object's default action.
STDMETHODIMP get_accDefaultAction(VARIANT var_id, BSTR* default_action);
// Retrieves the tooltip description.
STDMETHODIMP get_accDescription(VARIANT var_id, BSTR* desc);
// Retrieves the object that has the keyboard focus.
STDMETHODIMP get_accFocus(VARIANT* focus_child);
// Retrieves the specified object's shortcut.
STDMETHODIMP get_accKeyboardShortcut(VARIANT var_id, BSTR* access_key);
// Retrieves the name of the specified object.
STDMETHODIMP get_accName(VARIANT var_id, BSTR* name);
// Retrieves the IDispatch interface of the object's parent.
STDMETHODIMP get_accParent(IDispatch** disp_parent);
// Retrieves information describing the role of the specified object.
STDMETHODIMP get_accRole(VARIANT var_id, VARIANT* role);
// Retrieves the current state of the specified object.
STDMETHODIMP get_accState(VARIANT var_id, VARIANT* state);
// Retrieve or set the string value associated with the specified object.
// Setting the value is not typically used by screen readers, but it's
// used frequently by automation software.
STDMETHODIMP get_accValue(VARIANT var_id, BSTR* value);
STDMETHODIMP put_accValue(VARIANT var_id, BSTR new_value);
// Selections not applicable to views.
STDMETHODIMP get_accSelection(VARIANT* selected);
STDMETHODIMP accSelect(LONG flags_sel, VARIANT var_id);
// Help functions not supported.
STDMETHODIMP get_accHelp(VARIANT var_id, BSTR* help);
STDMETHODIMP get_accHelpTopic(BSTR* help_file,
VARIANT var_id,
LONG* topic_id);
// Deprecated functions, not implemented here.
STDMETHODIMP put_accName(VARIANT var_id, BSTR put_name);
//
// IAccessible2
//
STDMETHODIMP role(LONG* role);
STDMETHODIMP get_states(AccessibleStates* states);
STDMETHODIMP get_uniqueID(LONG* unique_id);
STDMETHODIMP get_windowHandle(HWND* window_handle);
//
// IAccessible2 methods not implemented.
//
STDMETHODIMP get_attributes(BSTR* attributes) {
return E_NOTIMPL;
}
STDMETHODIMP get_indexInParent(LONG* index_in_parent) {
return E_NOTIMPL;
}
STDMETHODIMP get_extendedRole(BSTR* extended_role) {
return E_NOTIMPL;
}
STDMETHODIMP get_nRelations(LONG* n_relations) {
return E_NOTIMPL;
}
STDMETHODIMP get_relation(LONG relation_index,
IAccessibleRelation** relation) {
return E_NOTIMPL;
}
STDMETHODIMP get_relations(LONG max_relations,
IAccessibleRelation** relations,
LONG* n_relations) {
return E_NOTIMPL;
}
STDMETHODIMP scrollTo(enum IA2ScrollType scroll_type) {
return E_NOTIMPL;
}
STDMETHODIMP scrollToPoint(
enum IA2CoordinateType coordinate_type,
LONG x,
LONG y) {
return E_NOTIMPL;
}
STDMETHODIMP get_groupPosition(LONG* group_level,
LONG* similar_items_in_group,
LONG* position_in_group) {
return E_NOTIMPL;
}
STDMETHODIMP get_localizedExtendedRole(
BSTR* localized_extended_role) {
return E_NOTIMPL;
}
STDMETHODIMP get_nExtendedStates(LONG* n_extended_states) {
return E_NOTIMPL;
}
STDMETHODIMP get_extendedStates(LONG max_extended_states,
BSTR** extended_states,
LONG* n_extended_states) {
return E_NOTIMPL;
}
STDMETHODIMP get_localizedExtendedStates(
LONG max_localized_extended_states,
BSTR** localized_extended_states,
LONG* n_localized_extended_states) {
return E_NOTIMPL;
}
STDMETHODIMP get_locale(IA2Locale* locale) {
return E_NOTIMPL;
}
//
// IAccessibleText methods.
//
STDMETHODIMP get_nCharacters(LONG* n_characters);
STDMETHODIMP get_caretOffset(LONG* offset);
STDMETHODIMP get_nSelections(LONG* n_selections);
STDMETHODIMP get_selection(LONG selection_index,
LONG* start_offset,
LONG* end_offset);
STDMETHODIMP get_text(LONG start_offset, LONG end_offset, BSTR* text);
STDMETHODIMP get_textAtOffset(LONG offset,
enum IA2TextBoundaryType boundary_type,
LONG* start_offset, LONG* end_offset,
BSTR* text);
STDMETHODIMP get_textBeforeOffset(LONG offset,
enum IA2TextBoundaryType boundary_type,
LONG* start_offset, LONG* end_offset,
BSTR* text);
STDMETHODIMP get_textAfterOffset(LONG offset,
enum IA2TextBoundaryType boundary_type,
LONG* start_offset, LONG* end_offset,
BSTR* text);
STDMETHODIMP get_offsetAtPoint(LONG x, LONG y,
enum IA2CoordinateType coord_type,
LONG* offset);
//
// IAccessibleText methods not implemented.
//
STDMETHODIMP get_newText(IA2TextSegment* new_text) {
return E_NOTIMPL;
}
STDMETHODIMP get_oldText(IA2TextSegment* old_text) {
return E_NOTIMPL;
}
STDMETHODIMP addSelection(LONG start_offset, LONG end_offset) {
return E_NOTIMPL;
}
STDMETHODIMP get_attributes(LONG offset,
LONG* start_offset,
LONG* end_offset,
BSTR* text_attributes) {
return E_NOTIMPL;
}
STDMETHODIMP get_characterExtents(LONG offset,
enum IA2CoordinateType coord_type,
LONG* x, LONG* y,
LONG* width, LONG* height) {
return E_NOTIMPL;
}
STDMETHODIMP removeSelection(LONG selection_index) {
return E_NOTIMPL;
}
STDMETHODIMP setCaretOffset(LONG offset) {
return E_NOTIMPL;
}
STDMETHODIMP setSelection(LONG selection_index,
LONG start_offset,
LONG end_offset) {
return E_NOTIMPL;
}
STDMETHODIMP scrollSubstringTo(LONG start_index,
LONG end_index,
enum IA2ScrollType scroll_type) {
return E_NOTIMPL;
}
STDMETHODIMP scrollSubstringToPoint(LONG start_index,
LONG end_index,
enum IA2CoordinateType coordinate_type,
LONG x, LONG y) {
return E_NOTIMPL;
}
//
// IServiceProvider methods.
//
STDMETHODIMP QueryService(REFGUID guidService, REFIID riid, void** object);
//
// IAccessibleEx methods not implemented.
//
STDMETHODIMP GetObjectForChild(long child_id, IAccessibleEx** ret) {
return E_NOTIMPL;
}
STDMETHODIMP GetIAccessiblePair(IAccessible** acc, long* child_id) {
return E_NOTIMPL;
}
STDMETHODIMP GetRuntimeId(SAFEARRAY** runtime_id) {
return E_NOTIMPL;
}
STDMETHODIMP ConvertReturnedElement(IRawElementProviderSimple* element,
IAccessibleEx** acc) {
return E_NOTIMPL;
}
//
// IRawElementProviderSimple methods.
//
// The GetPatternProvider/GetPropertyValue methods need to be implemented for
// the on-screen keyboard to show up in Windows 8 metro.
STDMETHODIMP GetPatternProvider(PATTERNID id, IUnknown** provider);
STDMETHODIMP GetPropertyValue(PROPERTYID id, VARIANT* ret);
//
// IRawElementProviderSimple methods not implemented.
//
STDMETHODIMP get_ProviderOptions(enum ProviderOptions* ret) {
return E_NOTIMPL;
}
STDMETHODIMP get_HostRawElementProvider(
IRawElementProviderSimple** provider) {
return E_NOTIMPL;
}
// Static methods
// Returns a conversion from the event (as defined in ax_enums.idl)
// to an MSAA event.
static int32 MSAAEvent(ui::AXEvent event);
// Returns a conversion from the Role (as defined in ax_enums.idl)
// to an MSAA role.
static int32 MSAARole(ui::AXRole role);
// Returns a conversion from the State (as defined in ax_enums.idl)
// to MSAA states set.
static int32 MSAAState(const ui::AXViewState& state);
protected:
NativeViewAccessibilityWin();
const View* view() const { return view_; }
private:
// Determines navigation direction for accNavigate, based on left, up and
// previous being mapped all to previous and right, down, next being mapped
// to next. Returns true if navigation direction is next, false otherwise.
bool IsNavDirNext(int nav_dir) const;
// Determines if the navigation target is within the allowed bounds. Returns
// true if it is, false otherwise.
bool IsValidNav(int nav_dir,
int start_id,
int lower_bound,
int upper_bound) const;
// Determines if the child id variant is valid.
bool IsValidId(const VARIANT& child) const;
// Helper function which sets applicable states of view.
void SetState(VARIANT* msaa_state, View* view);
// Return the text to use for IAccessibleText.
base::string16 TextForIAccessibleText();
// If offset is a member of IA2TextSpecialOffsets this function updates the
// value of offset and returns, otherwise offset remains unchanged.
void HandleSpecialTextOffset(const base::string16& text, LONG* offset);
// Convert from a IA2TextBoundaryType to a ui::TextBoundaryType.
ui::TextBoundaryType IA2TextBoundaryToTextBoundary(IA2TextBoundaryType type);
// Search forwards (direction == 1) or backwards (direction == -1)
// from the given offset until the given boundary is found, and
// return the offset of that boundary.
LONG FindBoundary(const base::string16& text,
IA2TextBoundaryType ia2_boundary,
LONG start_offset,
ui::TextBoundaryDirection direction);
// Populates the given vector with all widgets that are either a child
// or are owned by this view's widget, and who are not contained in a
// NativeViewHost.
void PopulateChildWidgetVector(std::vector<Widget*>* child_widgets);
// Give CComObject access to the class constructor.
template <class Base> friend class CComObject;
// Member View needed for view-specific calls.
View* view_;
// A unique id for each object, needed for IAccessible2.
long unique_id_;
// Next unique id to assign.
static long next_unique_id_;
// Circular queue size.
static const int kMaxViewStorageIds = 20;
// Circular queue of view storage ids corresponding to child ids
// used to post notifications using NotifyWinEvent.
static int view_storage_ids_[kMaxViewStorageIds];
// Next index into |view_storage_ids_| to use.
static int next_view_storage_id_index_;
DISALLOW_COPY_AND_ASSIGN(NativeViewAccessibilityWin);
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_WIN_H_
| 32.580796 | 80 | 0.693071 | [
"object",
"vector"
] |
2c8d43bfd089c64391e635d0cbebef67db42d839 | 2,442 | c | C | e2fsprogs/e2fsck/prof_err.c | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | 1 | 2020-06-28T00:49:21.000Z | 2020-06-28T00:49:21.000Z | e2fsprogs/e2fsck/prof_err.c | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | e2fsprogs/e2fsck/prof_err.c | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | 1 | 2021-03-05T16:54:52.000Z | 2021-03-05T16:54:52.000Z | /*
* prof_err.c:
* This file is automatically generated; please do not edit it.
*/
#include <stdlib.h>
#define N_(a) a
static const char * const text[] = {
N_("Profile version 0.0"),
N_("Bad magic value in profile_node"),
N_("Profile section not found"),
N_("Profile relation not found"),
N_( "Attempt to add a relation to node which is not a section"),
N_( "A profile section header has a non-zero value"),
N_("Bad linked list in profile structures"),
N_("Bad group level in profile structures"),
N_( "Bad parent pointer in profile structures"),
N_("Bad magic value in profile iterator"),
N_("Can't set value on section node"),
N_("Invalid argument passed to profile library"),
N_("Attempt to modify read-only profile"),
N_("Profile section header not at top level"),
N_("Syntax error in profile section header"),
N_("Syntax error in profile relation"),
N_("Extra closing brace in profile"),
N_("Missing open brace in profile"),
N_("Bad magic value in profile_t"),
N_("Bad magic value in profile_section_t"),
N_( "Iteration through all top level section not supported"),
N_("Invalid profile_section object"),
N_("No more sections"),
N_("Bad nameset passed to query routine"),
N_("No profile file open"),
N_("Bad magic value in profile_file_t"),
N_("Couldn't open profile file"),
N_("Section already exists"),
N_("Invalid boolean value"),
N_("Invalid integer value"),
N_("Bad magic value in profile_file_data_t"),
0
};
struct error_table {
char const * const * msgs;
long base;
int n_msgs;
};
struct et_list {
struct et_list *next;
const struct error_table * table;
};
extern struct et_list *_et_list;
const struct error_table et_prof_error_table = { text, -1429577728L, 31 };
static struct et_list link = { 0, 0 };
void initialize_prof_error_table_r(struct et_list **list);
void initialize_prof_error_table(void);
void initialize_prof_error_table(void) {
initialize_prof_error_table_r(&_et_list);
}
/* For Heimdal compatibility */
void initialize_prof_error_table_r(struct et_list **list)
{
struct et_list *et, **end;
for (end = list, et = *list; et; end = &et->next, et = et->next)
if (et->table->msgs == text)
return;
et = malloc(sizeof(struct et_list));
if (et == 0) {
if (!link.table)
et = &link;
else
return;
}
et->table = &et_prof_error_table;
et->next = 0;
*end = et;
}
| 28.395349 | 74 | 0.68018 | [
"object"
] |
2c9c825b5058fe20a115df412cace172259f9ec9 | 94,975 | c | C | dlls/quartz/vmr9.c | jakogut/wine | f614a7417c445438b49316087404dfd2418ea538 | [
"MIT"
] | null | null | null | dlls/quartz/vmr9.c | jakogut/wine | f614a7417c445438b49316087404dfd2418ea538 | [
"MIT"
] | null | null | null | dlls/quartz/vmr9.c | jakogut/wine | f614a7417c445438b49316087404dfd2418ea538 | [
"MIT"
] | null | null | null | /*
* Video Mixing Renderer for dx9
*
* Copyright 2004 Christian Costa
* Copyright 2008 Maarten Lankhorst
* Copyright 2012 Aric Stewart
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "quartz_private.h"
#include "uuids.h"
#include "vfwmsgs.h"
#include "amvideo.h"
#include "windef.h"
#include "winbase.h"
#include "dshow.h"
#include "evcode.h"
#include "strmif.h"
#include "ddraw.h"
#include "dvdmedia.h"
#include "d3d9.h"
#include "vmr9.h"
#include "wine/debug.h"
WINE_DEFAULT_DEBUG_CHANNEL(quartz);
struct quartz_vmr
{
BaseRenderer renderer;
BaseControlWindow baseControlWindow;
BaseControlVideo baseControlVideo;
IAMCertifiedOutputProtection IAMCertifiedOutputProtection_iface;
IAMFilterMiscFlags IAMFilterMiscFlags_iface;
IVMRFilterConfig IVMRFilterConfig_iface;
IVMRFilterConfig9 IVMRFilterConfig9_iface;
IVMRMonitorConfig IVMRMonitorConfig_iface;
IVMRMonitorConfig9 IVMRMonitorConfig9_iface;
IVMRSurfaceAllocatorNotify IVMRSurfaceAllocatorNotify_iface;
IVMRSurfaceAllocatorNotify9 IVMRSurfaceAllocatorNotify9_iface;
IVMRWindowlessControl IVMRWindowlessControl_iface;
IVMRWindowlessControl9 IVMRWindowlessControl9_iface;
IVMRSurfaceAllocatorEx9 *allocator;
IVMRImagePresenter9 *presenter;
BOOL allocator_is_ex;
/*
* The Video Mixing Renderer supports 3 modes, renderless, windowless and windowed
* What I do is implement windowless as a special case of renderless, and then
* windowed also as a special case of windowless. This is probably the easiest way.
*/
VMR9Mode mode;
BITMAPINFOHEADER bmiheader;
HMODULE hD3d9;
/* Presentation related members */
IDirect3DDevice9 *allocator_d3d9_dev;
HMONITOR allocator_mon;
DWORD num_surfaces;
DWORD cur_surface;
DWORD_PTR cookie;
/* for Windowless Mode */
HWND hWndClippingWindow;
RECT source_rect;
RECT target_rect;
LONG VideoWidth;
LONG VideoHeight;
};
static inline struct quartz_vmr *impl_from_BaseWindow(BaseWindow *wnd)
{
return CONTAINING_RECORD(wnd, struct quartz_vmr, baseControlWindow.baseWindow);
}
static inline struct quartz_vmr *impl_from_BaseControlVideo(BaseControlVideo *cvid)
{
return CONTAINING_RECORD(cvid, struct quartz_vmr, baseControlVideo);
}
static inline struct quartz_vmr *impl_from_IAMCertifiedOutputProtection(IAMCertifiedOutputProtection *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IAMCertifiedOutputProtection_iface);
}
static inline struct quartz_vmr *impl_from_IAMFilterMiscFlags(IAMFilterMiscFlags *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IAMFilterMiscFlags_iface);
}
static inline struct quartz_vmr *impl_from_IVMRFilterConfig(IVMRFilterConfig *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRFilterConfig_iface);
}
static inline struct quartz_vmr *impl_from_IVMRFilterConfig9(IVMRFilterConfig9 *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRFilterConfig9_iface);
}
static inline struct quartz_vmr *impl_from_IVMRMonitorConfig(IVMRMonitorConfig *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRMonitorConfig_iface);
}
static inline struct quartz_vmr *impl_from_IVMRMonitorConfig9(IVMRMonitorConfig9 *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRMonitorConfig9_iface);
}
static inline struct quartz_vmr *impl_from_IVMRSurfaceAllocatorNotify(IVMRSurfaceAllocatorNotify *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRSurfaceAllocatorNotify_iface);
}
static inline struct quartz_vmr *impl_from_IVMRSurfaceAllocatorNotify9(IVMRSurfaceAllocatorNotify9 *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRSurfaceAllocatorNotify9_iface);
}
static inline struct quartz_vmr *impl_from_IVMRWindowlessControl(IVMRWindowlessControl *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRWindowlessControl_iface);
}
static inline struct quartz_vmr *impl_from_IVMRWindowlessControl9(IVMRWindowlessControl9 *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, IVMRWindowlessControl9_iface);
}
typedef struct
{
IVMRImagePresenter9 IVMRImagePresenter9_iface;
IVMRSurfaceAllocatorEx9 IVMRSurfaceAllocatorEx9_iface;
LONG refCount;
HANDLE ack;
DWORD tid;
HANDLE hWndThread;
IDirect3DDevice9 *d3d9_dev;
IDirect3D9 *d3d9_ptr;
IDirect3DSurface9 **d3d9_surfaces;
IDirect3DVertexBuffer9 *d3d9_vertex;
HMONITOR hMon;
DWORD num_surfaces;
BOOL reset;
VMR9AllocationInfo info;
struct quartz_vmr* pVMR9;
IVMRSurfaceAllocatorNotify9 *SurfaceAllocatorNotify;
} VMR9DefaultAllocatorPresenterImpl;
static inline VMR9DefaultAllocatorPresenterImpl *impl_from_IVMRImagePresenter9( IVMRImagePresenter9 *iface)
{
return CONTAINING_RECORD(iface, VMR9DefaultAllocatorPresenterImpl, IVMRImagePresenter9_iface);
}
static inline VMR9DefaultAllocatorPresenterImpl *impl_from_IVMRSurfaceAllocatorEx9( IVMRSurfaceAllocatorEx9 *iface)
{
return CONTAINING_RECORD(iface, VMR9DefaultAllocatorPresenterImpl, IVMRSurfaceAllocatorEx9_iface);
}
static HRESULT VMR9DefaultAllocatorPresenterImpl_create(struct quartz_vmr *parent, LPVOID * ppv);
static inline struct quartz_vmr *impl_from_IBaseFilter(IBaseFilter *iface)
{
return CONTAINING_RECORD(iface, struct quartz_vmr, renderer.filter.IBaseFilter_iface);
}
static DWORD VMR9_SendSampleData(struct quartz_vmr *This, VMR9PresentationInfo *info, LPBYTE data,
DWORD size)
{
AM_MEDIA_TYPE *amt;
HRESULT hr = S_OK;
int width;
int height;
BITMAPINFOHEADER *bmiHeader;
D3DLOCKED_RECT lock;
TRACE("%p %p %d\n", This, data, size);
amt = &This->renderer.sink.pin.mtCurrent;
if (IsEqualIID(&amt->formattype, &FORMAT_VideoInfo))
{
bmiHeader = &((VIDEOINFOHEADER *)amt->pbFormat)->bmiHeader;
}
else if (IsEqualIID(&amt->formattype, &FORMAT_VideoInfo2))
{
bmiHeader = &((VIDEOINFOHEADER2 *)amt->pbFormat)->bmiHeader;
}
else
{
FIXME("Unknown type %s\n", debugstr_guid(&amt->subtype));
return VFW_E_RUNTIME_ERROR;
}
TRACE("biSize = %d\n", bmiHeader->biSize);
TRACE("biWidth = %d\n", bmiHeader->biWidth);
TRACE("biHeight = %d\n", bmiHeader->biHeight);
TRACE("biPlanes = %d\n", bmiHeader->biPlanes);
TRACE("biBitCount = %d\n", bmiHeader->biBitCount);
TRACE("biCompression = %s\n", debugstr_an((LPSTR)&(bmiHeader->biCompression), 4));
TRACE("biSizeImage = %d\n", bmiHeader->biSizeImage);
width = bmiHeader->biWidth;
height = bmiHeader->biHeight;
TRACE("Src Rect: %s\n", wine_dbgstr_rect(&This->source_rect));
TRACE("Dst Rect: %s\n", wine_dbgstr_rect(&This->target_rect));
hr = IDirect3DSurface9_LockRect(info->lpSurf, &lock, NULL, D3DLOCK_DISCARD);
if (FAILED(hr))
{
ERR("IDirect3DSurface9_LockRect failed (%x)\n",hr);
return hr;
}
if (height > 0) {
/* Bottom up image needs inverting */
lock.pBits = (char *)lock.pBits + (height * lock.Pitch);
while (height--)
{
lock.pBits = (char *)lock.pBits - lock.Pitch;
memcpy(lock.pBits, data, width * bmiHeader->biBitCount / 8);
data = data + width * bmiHeader->biBitCount / 8;
}
}
else if (lock.Pitch != width * bmiHeader->biBitCount / 8)
{
WARN("Slow path! %u/%u\n", lock.Pitch, width * bmiHeader->biBitCount/8);
while (height--)
{
memcpy(lock.pBits, data, width * bmiHeader->biBitCount / 8);
data = data + width * bmiHeader->biBitCount / 8;
lock.pBits = (char *)lock.pBits + lock.Pitch;
}
}
else memcpy(lock.pBits, data, size);
IDirect3DSurface9_UnlockRect(info->lpSurf);
hr = IVMRImagePresenter9_PresentImage(This->presenter, This->cookie, info);
return hr;
}
static HRESULT WINAPI VMR9_DoRenderSample(BaseRenderer *iface, IMediaSample * pSample)
{
struct quartz_vmr *This = impl_from_IBaseFilter(&iface->filter.IBaseFilter_iface);
LPBYTE pbSrcStream = NULL;
long cbSrcStream = 0;
REFERENCE_TIME tStart, tStop;
VMR9PresentationInfo info;
HRESULT hr;
TRACE("%p %p\n", iface, pSample);
/* It is possible that there is no device at this point */
if (!This->allocator || !This->presenter)
{
ERR("NO PRESENTER!!\n");
return S_FALSE;
}
hr = IMediaSample_GetTime(pSample, &tStart, &tStop);
if (FAILED(hr))
info.dwFlags = VMR9Sample_SrcDstRectsValid;
else
info.dwFlags = VMR9Sample_SrcDstRectsValid | VMR9Sample_TimeValid;
if (IMediaSample_IsDiscontinuity(pSample) == S_OK)
info.dwFlags |= VMR9Sample_Discontinuity;
if (IMediaSample_IsPreroll(pSample) == S_OK)
info.dwFlags |= VMR9Sample_Preroll;
if (IMediaSample_IsSyncPoint(pSample) == S_OK)
info.dwFlags |= VMR9Sample_SyncPoint;
/* If we render ourselves, and this is a preroll sample, discard it */
if (This->baseControlWindow.baseWindow.hWnd && (info.dwFlags & VMR9Sample_Preroll))
{
return S_OK;
}
hr = IMediaSample_GetPointer(pSample, &pbSrcStream);
if (FAILED(hr))
{
ERR("Cannot get pointer to sample data (%x)\n", hr);
return hr;
}
cbSrcStream = IMediaSample_GetActualDataLength(pSample);
info.rtStart = tStart;
info.rtEnd = tStop;
info.szAspectRatio.cx = This->bmiheader.biWidth;
info.szAspectRatio.cy = This->bmiheader.biHeight;
hr = IVMRSurfaceAllocatorEx9_GetSurface(This->allocator, This->cookie, (++This->cur_surface)%This->num_surfaces, 0, &info.lpSurf);
if (FAILED(hr))
return hr;
VMR9_SendSampleData(This, &info, pbSrcStream, cbSrcStream);
IDirect3DSurface9_Release(info.lpSurf);
return hr;
}
static HRESULT WINAPI VMR9_CheckMediaType(BaseRenderer *iface, const AM_MEDIA_TYPE * pmt)
{
struct quartz_vmr *This = impl_from_IBaseFilter(&iface->filter.IBaseFilter_iface);
if (!IsEqualIID(&pmt->majortype, &MEDIATYPE_Video) || !pmt->pbFormat)
return S_FALSE;
/* Ignore subtype, test for bicompression instead */
if (IsEqualIID(&pmt->formattype, &FORMAT_VideoInfo))
{
VIDEOINFOHEADER *format = (VIDEOINFOHEADER *)pmt->pbFormat;
This->bmiheader = format->bmiHeader;
TRACE("Resolution: %dx%d\n", format->bmiHeader.biWidth, format->bmiHeader.biHeight);
This->VideoWidth = format->bmiHeader.biWidth;
This->VideoHeight = format->bmiHeader.biHeight;
SetRect(&This->source_rect, 0, 0, This->VideoWidth, This->VideoHeight);
}
else if (IsEqualIID(&pmt->formattype, &FORMAT_VideoInfo2))
{
VIDEOINFOHEADER2 *format = (VIDEOINFOHEADER2 *)pmt->pbFormat;
This->bmiheader = format->bmiHeader;
TRACE("Resolution: %dx%d\n", format->bmiHeader.biWidth, format->bmiHeader.biHeight);
This->VideoWidth = format->bmiHeader.biWidth;
This->VideoHeight = format->bmiHeader.biHeight;
SetRect(&This->source_rect, 0, 0, This->VideoWidth, This->VideoHeight);
}
else
{
ERR("Format type %s not supported\n", debugstr_guid(&pmt->formattype));
return S_FALSE;
}
if (This->bmiheader.biCompression != BI_RGB)
return S_FALSE;
return S_OK;
}
static HRESULT VMR9_maybe_init(struct quartz_vmr *This, BOOL force)
{
VMR9AllocationInfo info;
DWORD buffers;
HRESULT hr;
TRACE("my mode: %u, my window: %p, my last window: %p\n", This->mode, This->baseControlWindow.baseWindow.hWnd, This->hWndClippingWindow);
if (This->baseControlWindow.baseWindow.hWnd || !This->renderer.sink.pin.peer)
return S_OK;
if (This->mode == VMR9Mode_Windowless && !This->hWndClippingWindow)
return (force ? VFW_E_RUNTIME_ERROR : S_OK);
TRACE("Initializing\n");
info.dwFlags = VMR9AllocFlag_TextureSurface;
info.dwHeight = This->source_rect.bottom;
info.dwWidth = This->source_rect.right;
info.Pool = D3DPOOL_DEFAULT;
info.MinBuffers = 2;
FIXME("Reduce ratio to least common denominator\n");
info.szAspectRatio.cx = info.dwWidth;
info.szAspectRatio.cy = info.dwHeight;
info.szNativeSize.cx = This->bmiheader.biWidth;
info.szNativeSize.cy = This->bmiheader.biHeight;
buffers = 2;
switch (This->bmiheader.biBitCount)
{
case 8: info.Format = D3DFMT_R3G3B2; break;
case 15: info.Format = D3DFMT_X1R5G5B5; break;
case 16: info.Format = D3DFMT_R5G6B5; break;
case 24: info.Format = D3DFMT_R8G8B8; break;
case 32: info.Format = D3DFMT_X8R8G8B8; break;
default:
FIXME("Unknown bpp %u\n", This->bmiheader.biBitCount);
hr = E_INVALIDARG;
}
This->cur_surface = 0;
if (This->num_surfaces)
{
ERR("num_surfaces or d3d9_surfaces not 0\n");
return E_FAIL;
}
hr = IVMRSurfaceAllocatorEx9_InitializeDevice(This->allocator, This->cookie, &info, &buffers);
if (SUCCEEDED(hr))
{
SetRect(&This->source_rect, 0, 0, This->bmiheader.biWidth, This->bmiheader.biHeight);
This->num_surfaces = buffers;
}
return hr;
}
static void vmr_start_stream(BaseRenderer *iface)
{
struct quartz_vmr *This = impl_from_IBaseFilter(&iface->filter.IBaseFilter_iface);
TRACE("(%p)\n", This);
VMR9_maybe_init(This, TRUE);
IVMRImagePresenter9_StartPresenting(This->presenter, This->cookie);
SetWindowPos(This->baseControlWindow.baseWindow.hWnd, NULL,
This->source_rect.left,
This->source_rect.top,
This->source_rect.right - This->source_rect.left,
This->source_rect.bottom - This->source_rect.top,
SWP_NOZORDER|SWP_NOMOVE|SWP_DEFERERASE);
ShowWindow(This->baseControlWindow.baseWindow.hWnd, SW_SHOW);
GetClientRect(This->baseControlWindow.baseWindow.hWnd, &This->target_rect);
}
static void vmr_stop_stream(BaseRenderer *iface)
{
struct quartz_vmr *This = impl_from_IBaseFilter(&iface->filter.IBaseFilter_iface);
TRACE("(%p)\n", This);
if (This->renderer.filter.state == State_Running)
IVMRImagePresenter9_StopPresenting(This->presenter, This->cookie);
}
static HRESULT WINAPI VMR9_ShouldDrawSampleNow(BaseRenderer *This, IMediaSample *pSample, REFERENCE_TIME *pStartTime, REFERENCE_TIME *pEndTime)
{
/* Preroll means the sample isn't shown, this is used for key frames and things like that */
if (IMediaSample_IsPreroll(pSample) == S_OK)
return E_FAIL;
return S_FALSE;
}
static HRESULT WINAPI VMR9_CompleteConnect(BaseRenderer *This, IPin *pReceivePin)
{
struct quartz_vmr *pVMR9 = impl_from_IBaseFilter(&This->filter.IBaseFilter_iface);
HRESULT hr;
TRACE("(%p)\n", This);
if (pVMR9->mode ||
SUCCEEDED(hr = IVMRFilterConfig9_SetRenderingMode(&pVMR9->IVMRFilterConfig9_iface, VMR9Mode_Windowed)))
hr = VMR9_maybe_init(pVMR9, FALSE);
return hr;
}
static HRESULT WINAPI VMR9_BreakConnect(BaseRenderer *This)
{
struct quartz_vmr *pVMR9 = impl_from_IBaseFilter(&This->filter.IBaseFilter_iface);
HRESULT hr = S_OK;
if (!pVMR9->mode)
return S_FALSE;
if (This->sink.pin.peer && pVMR9->allocator && pVMR9->presenter)
{
if (pVMR9->renderer.filter.state != State_Stopped)
{
ERR("Disconnecting while not stopped! UNTESTED!!\n");
}
if (pVMR9->renderer.filter.state == State_Running)
hr = IVMRImagePresenter9_StopPresenting(pVMR9->presenter, pVMR9->cookie);
IVMRSurfaceAllocatorEx9_TerminateDevice(pVMR9->allocator, pVMR9->cookie);
pVMR9->num_surfaces = 0;
}
return hr;
}
static void vmr_destroy(BaseRenderer *iface)
{
struct quartz_vmr *filter = impl_from_IBaseFilter(&iface->filter.IBaseFilter_iface);
BaseControlWindow_Destroy(&filter->baseControlWindow);
if (filter->allocator)
IVMRSurfaceAllocatorEx9_Release(filter->allocator);
if (filter->presenter)
IVMRImagePresenter9_Release(filter->presenter);
filter->num_surfaces = 0;
if (filter->allocator_d3d9_dev)
{
IDirect3DDevice9_Release(filter->allocator_d3d9_dev);
filter->allocator_d3d9_dev = NULL;
}
FreeLibrary(filter->hD3d9);
strmbase_renderer_cleanup(&filter->renderer);
CoTaskMemFree(filter);
}
static HRESULT vmr_query_interface(BaseRenderer *iface, REFIID iid, void **out)
{
struct quartz_vmr *filter = impl_from_IBaseFilter(&iface->filter.IBaseFilter_iface);
if (IsEqualGUID(iid, &IID_IVideoWindow))
*out = &filter->baseControlWindow.IVideoWindow_iface;
else if (IsEqualGUID(iid, &IID_IBasicVideo))
*out = &filter->baseControlVideo.IBasicVideo_iface;
else if (IsEqualGUID(iid, &IID_IAMCertifiedOutputProtection))
*out = &filter->IAMCertifiedOutputProtection_iface;
else if (IsEqualGUID(iid, &IID_IAMFilterMiscFlags))
*out = &filter->IAMFilterMiscFlags_iface;
else if (IsEqualGUID(iid, &IID_IVMRFilterConfig))
*out = &filter->IVMRFilterConfig_iface;
else if (IsEqualGUID(iid, &IID_IVMRFilterConfig9))
*out = &filter->IVMRFilterConfig9_iface;
else if (IsEqualGUID(iid, &IID_IVMRMonitorConfig))
*out = &filter->IVMRMonitorConfig_iface;
else if (IsEqualGUID(iid, &IID_IVMRMonitorConfig9))
*out = &filter->IVMRMonitorConfig9_iface;
else if (IsEqualGUID(iid, &IID_IVMRSurfaceAllocatorNotify) && filter->mode == (VMR9Mode)VMRMode_Renderless)
*out = &filter->IVMRSurfaceAllocatorNotify_iface;
else if (IsEqualGUID(iid, &IID_IVMRSurfaceAllocatorNotify9) && filter->mode == VMR9Mode_Renderless)
*out = &filter->IVMRSurfaceAllocatorNotify9_iface;
else if (IsEqualGUID(iid, &IID_IVMRWindowlessControl) && filter->mode == (VMR9Mode)VMRMode_Windowless)
*out = &filter->IVMRWindowlessControl_iface;
else if (IsEqualGUID(iid, &IID_IVMRWindowlessControl9) && filter->mode == VMR9Mode_Windowless)
*out = &filter->IVMRWindowlessControl9_iface;
else
return E_NOINTERFACE;
IUnknown_AddRef((IUnknown *)*out);
return S_OK;
}
static const BaseRendererFuncTable BaseFuncTable =
{
.pfnCheckMediaType = VMR9_CheckMediaType,
.pfnDoRenderSample = VMR9_DoRenderSample,
.renderer_start_stream = vmr_start_stream,
.renderer_stop_stream = vmr_stop_stream,
.pfnShouldDrawSampleNow = VMR9_ShouldDrawSampleNow,
.pfnCompleteConnect = VMR9_CompleteConnect,
.pfnBreakConnect = VMR9_BreakConnect,
.renderer_destroy = vmr_destroy,
.renderer_query_interface = vmr_query_interface,
};
static LPWSTR WINAPI VMR9_GetClassWindowStyles(BaseWindow *This, DWORD *pClassStyles, DWORD *pWindowStyles, DWORD *pWindowStylesEx)
{
static WCHAR classnameW[] = { 'I','V','M','R','9',' ','C','l','a','s','s', 0 };
*pClassStyles = 0;
*pWindowStyles = WS_SIZEBOX;
*pWindowStylesEx = 0;
return classnameW;
}
static RECT WINAPI VMR9_GetDefaultRect(BaseWindow *This)
{
struct quartz_vmr* pVMR9 = impl_from_BaseWindow(This);
static RECT defRect;
SetRect(&defRect, 0, 0, pVMR9->VideoWidth, pVMR9->VideoHeight);
return defRect;
}
static BOOL WINAPI VMR9_OnSize(BaseWindow *This, LONG Width, LONG Height)
{
struct quartz_vmr* pVMR9 = impl_from_BaseWindow(This);
TRACE("WM_SIZE %d %d\n", Width, Height);
GetClientRect(This->hWnd, &pVMR9->target_rect);
TRACE("WM_SIZING: DestRect=(%d,%d),(%d,%d)\n",
pVMR9->target_rect.left,
pVMR9->target_rect.top,
pVMR9->target_rect.right - pVMR9->target_rect.left,
pVMR9->target_rect.bottom - pVMR9->target_rect.top);
return BaseWindowImpl_OnSize(This, Width, Height);
}
static const BaseWindowFuncTable renderer_BaseWindowFuncTable = {
VMR9_GetClassWindowStyles,
VMR9_GetDefaultRect,
NULL,
BaseControlWindowImpl_PossiblyEatMessage,
VMR9_OnSize,
};
static HRESULT WINAPI VMR9_GetSourceRect(BaseControlVideo* This, RECT *pSourceRect)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
CopyRect(pSourceRect,&pVMR9->source_rect);
return S_OK;
}
static HRESULT WINAPI VMR9_GetStaticImage(BaseControlVideo* This, LONG *pBufferSize, LONG *pDIBImage)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
AM_MEDIA_TYPE *amt = &pVMR9->renderer.sink.pin.mtCurrent;
BITMAPINFOHEADER *bmiHeader;
LONG needed_size;
char *ptr;
FIXME("(%p/%p)->(%p, %p): partial stub\n", pVMR9, This, pBufferSize, pDIBImage);
EnterCriticalSection(&pVMR9->renderer.filter.csFilter);
if (!pVMR9->renderer.pMediaSample)
{
LeaveCriticalSection(&pVMR9->renderer.filter.csFilter);
return (pVMR9->renderer.filter.state == State_Paused ? E_UNEXPECTED : VFW_E_NOT_PAUSED);
}
if (IsEqualIID(&amt->formattype, &FORMAT_VideoInfo))
{
bmiHeader = &((VIDEOINFOHEADER *)amt->pbFormat)->bmiHeader;
}
else if (IsEqualIID(&amt->formattype, &FORMAT_VideoInfo2))
{
bmiHeader = &((VIDEOINFOHEADER2 *)amt->pbFormat)->bmiHeader;
}
else
{
FIXME("Unknown type %s\n", debugstr_guid(&amt->subtype));
LeaveCriticalSection(&pVMR9->renderer.filter.csFilter);
return VFW_E_RUNTIME_ERROR;
}
needed_size = bmiHeader->biSize;
needed_size += IMediaSample_GetActualDataLength(pVMR9->renderer.pMediaSample);
if (!pDIBImage)
{
*pBufferSize = needed_size;
LeaveCriticalSection(&pVMR9->renderer.filter.csFilter);
return S_OK;
}
if (needed_size < *pBufferSize)
{
ERR("Buffer too small %u/%u\n", needed_size, *pBufferSize);
LeaveCriticalSection(&pVMR9->renderer.filter.csFilter);
return E_FAIL;
}
*pBufferSize = needed_size;
memcpy(pDIBImage, bmiHeader, bmiHeader->biSize);
IMediaSample_GetPointer(pVMR9->renderer.pMediaSample, (BYTE **)&ptr);
memcpy((char *)pDIBImage + bmiHeader->biSize, ptr, IMediaSample_GetActualDataLength(pVMR9->renderer.pMediaSample));
LeaveCriticalSection(&pVMR9->renderer.filter.csFilter);
return S_OK;
}
static HRESULT WINAPI VMR9_GetTargetRect(BaseControlVideo* This, RECT *pTargetRect)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
CopyRect(pTargetRect,&pVMR9->target_rect);
return S_OK;
}
static VIDEOINFOHEADER* WINAPI VMR9_GetVideoFormat(BaseControlVideo* This)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
AM_MEDIA_TYPE *pmt;
TRACE("(%p/%p)\n", pVMR9, This);
pmt = &pVMR9->renderer.sink.pin.mtCurrent;
if (IsEqualIID(&pmt->formattype, &FORMAT_VideoInfo)) {
return (VIDEOINFOHEADER*)pmt->pbFormat;
} else if (IsEqualIID(&pmt->formattype, &FORMAT_VideoInfo2)) {
static VIDEOINFOHEADER vih;
VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2*)pmt->pbFormat;
memcpy(&vih,vih2,sizeof(VIDEOINFOHEADER));
memcpy(&vih.bmiHeader, &vih2->bmiHeader, sizeof(BITMAPINFOHEADER));
return &vih;
} else {
ERR("Unknown format type %s\n", qzdebugstr_guid(&pmt->formattype));
return NULL;
}
}
static HRESULT WINAPI VMR9_IsDefaultSourceRect(BaseControlVideo* This)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
FIXME("(%p/%p)->(): stub !!!\n", pVMR9, This);
return S_OK;
}
static HRESULT WINAPI VMR9_IsDefaultTargetRect(BaseControlVideo* This)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
FIXME("(%p/%p)->(): stub !!!\n", pVMR9, This);
return S_OK;
}
static HRESULT WINAPI VMR9_SetDefaultSourceRect(BaseControlVideo* This)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
SetRect(&pVMR9->source_rect, 0, 0, pVMR9->VideoWidth, pVMR9->VideoHeight);
return S_OK;
}
static HRESULT WINAPI VMR9_SetDefaultTargetRect(BaseControlVideo* This)
{
RECT rect;
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
if (!GetClientRect(pVMR9->baseControlWindow.baseWindow.hWnd, &rect))
return E_FAIL;
SetRect(&pVMR9->target_rect, 0, 0, rect.right, rect.bottom);
return S_OK;
}
static HRESULT WINAPI VMR9_SetSourceRect(BaseControlVideo* This, RECT *pSourceRect)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
CopyRect(&pVMR9->source_rect,pSourceRect);
return S_OK;
}
static HRESULT WINAPI VMR9_SetTargetRect(BaseControlVideo* This, RECT *pTargetRect)
{
struct quartz_vmr* pVMR9 = impl_from_BaseControlVideo(This);
CopyRect(&pVMR9->target_rect,pTargetRect);
return S_OK;
}
static const BaseControlVideoFuncTable renderer_BaseControlVideoFuncTable = {
VMR9_GetSourceRect,
VMR9_GetStaticImage,
VMR9_GetTargetRect,
VMR9_GetVideoFormat,
VMR9_IsDefaultSourceRect,
VMR9_IsDefaultTargetRect,
VMR9_SetDefaultSourceRect,
VMR9_SetDefaultTargetRect,
VMR9_SetSourceRect,
VMR9_SetTargetRect
};
static const IBaseFilterVtbl VMR_Vtbl =
{
BaseFilterImpl_QueryInterface,
BaseFilterImpl_AddRef,
BaseFilterImpl_Release,
BaseFilterImpl_GetClassID,
BaseRendererImpl_Stop,
BaseRendererImpl_Pause,
BaseRendererImpl_Run,
BaseRendererImpl_GetState,
BaseRendererImpl_SetSyncSource,
BaseFilterImpl_GetSyncSource,
BaseFilterImpl_EnumPins,
BaseFilterImpl_FindPin,
BaseFilterImpl_QueryFilterInfo,
BaseFilterImpl_JoinFilterGraph,
BaseFilterImpl_QueryVendorInfo
};
static const IVideoWindowVtbl IVideoWindow_VTable =
{
BaseControlWindowImpl_QueryInterface,
BaseControlWindowImpl_AddRef,
BaseControlWindowImpl_Release,
BaseControlWindowImpl_GetTypeInfoCount,
BaseControlWindowImpl_GetTypeInfo,
BaseControlWindowImpl_GetIDsOfNames,
BaseControlWindowImpl_Invoke,
BaseControlWindowImpl_put_Caption,
BaseControlWindowImpl_get_Caption,
BaseControlWindowImpl_put_WindowStyle,
BaseControlWindowImpl_get_WindowStyle,
BaseControlWindowImpl_put_WindowStyleEx,
BaseControlWindowImpl_get_WindowStyleEx,
BaseControlWindowImpl_put_AutoShow,
BaseControlWindowImpl_get_AutoShow,
BaseControlWindowImpl_put_WindowState,
BaseControlWindowImpl_get_WindowState,
BaseControlWindowImpl_put_BackgroundPalette,
BaseControlWindowImpl_get_BackgroundPalette,
BaseControlWindowImpl_put_Visible,
BaseControlWindowImpl_get_Visible,
BaseControlWindowImpl_put_Left,
BaseControlWindowImpl_get_Left,
BaseControlWindowImpl_put_Width,
BaseControlWindowImpl_get_Width,
BaseControlWindowImpl_put_Top,
BaseControlWindowImpl_get_Top,
BaseControlWindowImpl_put_Height,
BaseControlWindowImpl_get_Height,
BaseControlWindowImpl_put_Owner,
BaseControlWindowImpl_get_Owner,
BaseControlWindowImpl_put_MessageDrain,
BaseControlWindowImpl_get_MessageDrain,
BaseControlWindowImpl_get_BorderColor,
BaseControlWindowImpl_put_BorderColor,
BaseControlWindowImpl_get_FullScreenMode,
BaseControlWindowImpl_put_FullScreenMode,
BaseControlWindowImpl_SetWindowForeground,
BaseControlWindowImpl_NotifyOwnerMessage,
BaseControlWindowImpl_SetWindowPosition,
BaseControlWindowImpl_GetWindowPosition,
BaseControlWindowImpl_GetMinIdealImageSize,
BaseControlWindowImpl_GetMaxIdealImageSize,
BaseControlWindowImpl_GetRestorePosition,
BaseControlWindowImpl_HideCursor,
BaseControlWindowImpl_IsCursorHidden
};
static HRESULT WINAPI AMCertifiedOutputProtection_QueryInterface(IAMCertifiedOutputProtection *iface,
REFIID riid, void **ppv)
{
struct quartz_vmr *This = impl_from_IAMCertifiedOutputProtection(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI AMCertifiedOutputProtection_AddRef(IAMCertifiedOutputProtection *iface)
{
struct quartz_vmr *This = impl_from_IAMCertifiedOutputProtection(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI AMCertifiedOutputProtection_Release(IAMCertifiedOutputProtection *iface)
{
struct quartz_vmr *This = impl_from_IAMCertifiedOutputProtection(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI AMCertifiedOutputProtection_KeyExchange(IAMCertifiedOutputProtection *iface,
GUID* pRandom, BYTE** VarLenCertGH,
DWORD* pdwLengthCertGH)
{
struct quartz_vmr *This = impl_from_IAMCertifiedOutputProtection(iface);
FIXME("(%p/%p)->(%p, %p, %p) stub\n", iface, This, pRandom, VarLenCertGH, pdwLengthCertGH);
return VFW_E_NO_COPP_HW;
}
static HRESULT WINAPI AMCertifiedOutputProtection_SessionSequenceStart(IAMCertifiedOutputProtection *iface,
AMCOPPSignature* pSig)
{
struct quartz_vmr *This = impl_from_IAMCertifiedOutputProtection(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, pSig);
return VFW_E_NO_COPP_HW;
}
static HRESULT WINAPI AMCertifiedOutputProtection_ProtectionCommand(IAMCertifiedOutputProtection *iface,
const AMCOPPCommand* cmd)
{
struct quartz_vmr *This = impl_from_IAMCertifiedOutputProtection(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, cmd);
return VFW_E_NO_COPP_HW;
}
static HRESULT WINAPI AMCertifiedOutputProtection_ProtectionStatus(IAMCertifiedOutputProtection *iface,
const AMCOPPStatusInput* pStatusInput,
AMCOPPStatusOutput* pStatusOutput)
{
struct quartz_vmr *This = impl_from_IAMCertifiedOutputProtection(iface);
FIXME("(%p/%p)->(%p, %p) stub\n", iface, This, pStatusInput, pStatusOutput);
return VFW_E_NO_COPP_HW;
}
static const IAMCertifiedOutputProtectionVtbl IAMCertifiedOutputProtection_Vtbl =
{
AMCertifiedOutputProtection_QueryInterface,
AMCertifiedOutputProtection_AddRef,
AMCertifiedOutputProtection_Release,
AMCertifiedOutputProtection_KeyExchange,
AMCertifiedOutputProtection_SessionSequenceStart,
AMCertifiedOutputProtection_ProtectionCommand,
AMCertifiedOutputProtection_ProtectionStatus
};
static HRESULT WINAPI AMFilterMiscFlags_QueryInterface(IAMFilterMiscFlags *iface, REFIID riid, void **ppv) {
struct quartz_vmr *This = impl_from_IAMFilterMiscFlags(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI AMFilterMiscFlags_AddRef(IAMFilterMiscFlags *iface) {
struct quartz_vmr *This = impl_from_IAMFilterMiscFlags(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI AMFilterMiscFlags_Release(IAMFilterMiscFlags *iface) {
struct quartz_vmr *This = impl_from_IAMFilterMiscFlags(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static ULONG WINAPI AMFilterMiscFlags_GetMiscFlags(IAMFilterMiscFlags *iface) {
return AM_FILTER_MISC_FLAGS_IS_RENDERER;
}
static const IAMFilterMiscFlagsVtbl IAMFilterMiscFlags_Vtbl = {
AMFilterMiscFlags_QueryInterface,
AMFilterMiscFlags_AddRef,
AMFilterMiscFlags_Release,
AMFilterMiscFlags_GetMiscFlags
};
static HRESULT WINAPI VMR7FilterConfig_QueryInterface(IVMRFilterConfig *iface, REFIID riid,
void** ppv)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR7FilterConfig_AddRef(IVMRFilterConfig *iface)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR7FilterConfig_Release(IVMRFilterConfig *iface)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR7FilterConfig_SetImageCompositor(IVMRFilterConfig *iface,
IVMRImageCompositor *compositor)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, compositor);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7FilterConfig_SetNumberOfStreams(IVMRFilterConfig *iface, DWORD max)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
FIXME("(%p/%p)->(%u) stub\n", iface, This, max);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7FilterConfig_GetNumberOfStreams(IVMRFilterConfig *iface, DWORD *max)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, max);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7FilterConfig_SetRenderingPrefs(IVMRFilterConfig *iface, DWORD renderflags)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
FIXME("(%p/%p)->(%u) stub\n", iface, This, renderflags);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7FilterConfig_GetRenderingPrefs(IVMRFilterConfig *iface, DWORD *renderflags)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, renderflags);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7FilterConfig_SetRenderingMode(IVMRFilterConfig *iface, DWORD mode)
{
struct quartz_vmr *filter = impl_from_IVMRFilterConfig(iface);
TRACE("iface %p, mode %#x.\n", iface, mode);
return IVMRFilterConfig9_SetRenderingMode(&filter->IVMRFilterConfig9_iface, mode);
}
static HRESULT WINAPI VMR7FilterConfig_GetRenderingMode(IVMRFilterConfig *iface, DWORD *mode)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig(iface);
TRACE("(%p/%p)->(%p)\n", iface, This, mode);
if (!mode) return E_POINTER;
if (This->mode)
*mode = This->mode;
else
*mode = VMRMode_Windowed;
return S_OK;
}
static const IVMRFilterConfigVtbl VMR7_FilterConfig_Vtbl =
{
VMR7FilterConfig_QueryInterface,
VMR7FilterConfig_AddRef,
VMR7FilterConfig_Release,
VMR7FilterConfig_SetImageCompositor,
VMR7FilterConfig_SetNumberOfStreams,
VMR7FilterConfig_GetNumberOfStreams,
VMR7FilterConfig_SetRenderingPrefs,
VMR7FilterConfig_GetRenderingPrefs,
VMR7FilterConfig_SetRenderingMode,
VMR7FilterConfig_GetRenderingMode
};
struct get_available_monitors_args
{
VMRMONITORINFO *info7;
VMR9MonitorInfo *info9;
DWORD arraysize;
DWORD numdev;
};
static BOOL CALLBACK get_available_monitors_proc(HMONITOR hmon, HDC hdc, LPRECT lprc, LPARAM lparam)
{
struct get_available_monitors_args *args = (struct get_available_monitors_args *)lparam;
MONITORINFOEXW mi;
if (args->info7 || args->info9)
{
if (!args->arraysize)
return FALSE;
mi.cbSize = sizeof(mi);
if (!GetMonitorInfoW(hmon, (MONITORINFO*)&mi))
return TRUE;
/* fill VMRMONITORINFO struct */
if (args->info7)
{
VMRMONITORINFO *info = args->info7++;
memset(info, 0, sizeof(*info));
if (args->numdev > 0)
{
info->guid.pGUID = &info->guid.GUID;
info->guid.GUID.Data4[7] = args->numdev;
}
else
info->guid.pGUID = NULL;
info->rcMonitor = mi.rcMonitor;
info->hMon = hmon;
info->dwFlags = mi.dwFlags;
lstrcpynW(info->szDevice, mi.szDevice, ARRAY_SIZE(info->szDevice));
/* FIXME: how to get these values? */
info->szDescription[0] = 0;
}
/* fill VMR9MonitorInfo struct */
if (args->info9)
{
VMR9MonitorInfo *info = args->info9++;
memset(info, 0, sizeof(*info));
info->uDevID = 0; /* FIXME */
info->rcMonitor = mi.rcMonitor;
info->hMon = hmon;
info->dwFlags = mi.dwFlags;
lstrcpynW(info->szDevice, mi.szDevice, ARRAY_SIZE(info->szDevice));
/* FIXME: how to get these values? */
info->szDescription[0] = 0;
info->dwVendorId = 0;
info->dwDeviceId = 0;
info->dwSubSysId = 0;
info->dwRevision = 0;
}
args->arraysize--;
}
args->numdev++;
return TRUE;
}
static HRESULT WINAPI VMR7MonitorConfig_QueryInterface(IVMRMonitorConfig *iface, REFIID riid,
LPVOID * ppv)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR7MonitorConfig_AddRef(IVMRMonitorConfig *iface)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR7MonitorConfig_Release(IVMRMonitorConfig *iface)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR7MonitorConfig_SetMonitor(IVMRMonitorConfig *iface, const VMRGUID *pGUID)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, pGUID);
if (!pGUID)
return E_POINTER;
return S_OK;
}
static HRESULT WINAPI VMR7MonitorConfig_GetMonitor(IVMRMonitorConfig *iface, VMRGUID *pGUID)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, pGUID);
if (!pGUID)
return E_POINTER;
pGUID->pGUID = NULL; /* default DirectDraw device */
return S_OK;
}
static HRESULT WINAPI VMR7MonitorConfig_SetDefaultMonitor(IVMRMonitorConfig *iface,
const VMRGUID *pGUID)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, pGUID);
if (!pGUID)
return E_POINTER;
return S_OK;
}
static HRESULT WINAPI VMR7MonitorConfig_GetDefaultMonitor(IVMRMonitorConfig *iface, VMRGUID *pGUID)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, pGUID);
if (!pGUID)
return E_POINTER;
pGUID->pGUID = NULL; /* default DirectDraw device */
return S_OK;
}
static HRESULT WINAPI VMR7MonitorConfig_GetAvailableMonitors(IVMRMonitorConfig *iface,
VMRMONITORINFO *info, DWORD arraysize,
DWORD *numdev)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig(iface);
struct get_available_monitors_args args;
FIXME("(%p/%p)->(%p, %u, %p) semi-stub\n", iface, This, info, arraysize, numdev);
if (!numdev)
return E_POINTER;
if (info && arraysize == 0)
return E_INVALIDARG;
args.info7 = info;
args.info9 = NULL;
args.arraysize = arraysize;
args.numdev = 0;
EnumDisplayMonitors(NULL, NULL, get_available_monitors_proc, (LPARAM)&args);
*numdev = args.numdev;
return S_OK;
}
static const IVMRMonitorConfigVtbl VMR7_MonitorConfig_Vtbl =
{
VMR7MonitorConfig_QueryInterface,
VMR7MonitorConfig_AddRef,
VMR7MonitorConfig_Release,
VMR7MonitorConfig_SetMonitor,
VMR7MonitorConfig_GetMonitor,
VMR7MonitorConfig_SetDefaultMonitor,
VMR7MonitorConfig_GetDefaultMonitor,
VMR7MonitorConfig_GetAvailableMonitors
};
static HRESULT WINAPI VMR9MonitorConfig_QueryInterface(IVMRMonitorConfig9 *iface, REFIID riid,
LPVOID * ppv)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR9MonitorConfig_AddRef(IVMRMonitorConfig9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR9MonitorConfig_Release(IVMRMonitorConfig9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR9MonitorConfig_SetMonitor(IVMRMonitorConfig9 *iface, UINT uDev)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
FIXME("(%p/%p)->(%u) stub\n", iface, This, uDev);
return S_OK;
}
static HRESULT WINAPI VMR9MonitorConfig_GetMonitor(IVMRMonitorConfig9 *iface, UINT *uDev)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, uDev);
if (!uDev)
return E_POINTER;
*uDev = 0;
return S_OK;
}
static HRESULT WINAPI VMR9MonitorConfig_SetDefaultMonitor(IVMRMonitorConfig9 *iface, UINT uDev)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
FIXME("(%p/%p)->(%u) stub\n", iface, This, uDev);
return S_OK;
}
static HRESULT WINAPI VMR9MonitorConfig_GetDefaultMonitor(IVMRMonitorConfig9 *iface, UINT *uDev)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, uDev);
if (!uDev)
return E_POINTER;
*uDev = 0;
return S_OK;
}
static HRESULT WINAPI VMR9MonitorConfig_GetAvailableMonitors(IVMRMonitorConfig9 *iface,
VMR9MonitorInfo *info, DWORD arraysize,
DWORD *numdev)
{
struct quartz_vmr *This = impl_from_IVMRMonitorConfig9(iface);
struct get_available_monitors_args args;
FIXME("(%p/%p)->(%p, %u, %p) semi-stub\n", iface, This, info, arraysize, numdev);
if (!numdev)
return E_POINTER;
if (info && arraysize == 0)
return E_INVALIDARG;
args.info7 = NULL;
args.info9 = info;
args.arraysize = arraysize;
args.numdev = 0;
EnumDisplayMonitors(NULL, NULL, get_available_monitors_proc, (LPARAM)&args);
*numdev = args.numdev;
return S_OK;
}
static const IVMRMonitorConfig9Vtbl VMR9_MonitorConfig_Vtbl =
{
VMR9MonitorConfig_QueryInterface,
VMR9MonitorConfig_AddRef,
VMR9MonitorConfig_Release,
VMR9MonitorConfig_SetMonitor,
VMR9MonitorConfig_GetMonitor,
VMR9MonitorConfig_SetDefaultMonitor,
VMR9MonitorConfig_GetDefaultMonitor,
VMR9MonitorConfig_GetAvailableMonitors
};
static HRESULT WINAPI VMR9FilterConfig_QueryInterface(IVMRFilterConfig9 *iface, REFIID riid, LPVOID * ppv)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR9FilterConfig_AddRef(IVMRFilterConfig9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR9FilterConfig_Release(IVMRFilterConfig9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR9FilterConfig_SetImageCompositor(IVMRFilterConfig9 *iface, IVMRImageCompositor9 *compositor)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, compositor);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9FilterConfig_SetNumberOfStreams(IVMRFilterConfig9 *iface, DWORD count)
{
FIXME("iface %p, count %u, stub!\n", iface, count);
if (count == 1)
return S_OK;
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9FilterConfig_GetNumberOfStreams(IVMRFilterConfig9 *iface, DWORD *max)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, max);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9FilterConfig_SetRenderingPrefs(IVMRFilterConfig9 *iface, DWORD renderflags)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
FIXME("(%p/%p)->(%u) stub\n", iface, This, renderflags);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9FilterConfig_GetRenderingPrefs(IVMRFilterConfig9 *iface, DWORD *renderflags)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
FIXME("(%p/%p)->(%p) stub\n", iface, This, renderflags);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9FilterConfig_SetRenderingMode(IVMRFilterConfig9 *iface, DWORD mode)
{
HRESULT hr = S_OK;
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
TRACE("(%p/%p)->(%u)\n", iface, This, mode);
EnterCriticalSection(&This->renderer.filter.csFilter);
if (This->mode)
{
LeaveCriticalSection(&This->renderer.filter.csFilter);
return VFW_E_WRONG_STATE;
}
if (This->allocator)
IVMRSurfaceAllocatorEx9_Release(This->allocator);
if (This->presenter)
IVMRImagePresenter9_Release(This->presenter);
This->allocator = NULL;
This->presenter = NULL;
switch (mode)
{
case VMR9Mode_Windowed:
case VMR9Mode_Windowless:
This->allocator_is_ex = 0;
This->cookie = ~0;
hr = VMR9DefaultAllocatorPresenterImpl_create(This, (LPVOID*)&This->presenter);
if (SUCCEEDED(hr))
hr = IVMRImagePresenter9_QueryInterface(This->presenter, &IID_IVMRSurfaceAllocatorEx9, (LPVOID*)&This->allocator);
if (FAILED(hr))
{
ERR("Unable to find Presenter interface\n");
IVMRImagePresenter9_Release(This->presenter);
This->allocator = NULL;
This->presenter = NULL;
}
else
hr = IVMRSurfaceAllocatorEx9_AdviseNotify(This->allocator, &This->IVMRSurfaceAllocatorNotify9_iface);
break;
case VMR9Mode_Renderless:
break;
default:
LeaveCriticalSection(&This->renderer.filter.csFilter);
return E_INVALIDARG;
}
This->mode = mode;
LeaveCriticalSection(&This->renderer.filter.csFilter);
return hr;
}
static HRESULT WINAPI VMR9FilterConfig_GetRenderingMode(IVMRFilterConfig9 *iface, DWORD *mode)
{
struct quartz_vmr *This = impl_from_IVMRFilterConfig9(iface);
TRACE("(%p/%p)->(%p)\n", iface, This, mode);
if (!mode)
return E_POINTER;
if (This->mode)
*mode = This->mode;
else
*mode = VMR9Mode_Windowed;
return S_OK;
}
static const IVMRFilterConfig9Vtbl VMR9_FilterConfig_Vtbl =
{
VMR9FilterConfig_QueryInterface,
VMR9FilterConfig_AddRef,
VMR9FilterConfig_Release,
VMR9FilterConfig_SetImageCompositor,
VMR9FilterConfig_SetNumberOfStreams,
VMR9FilterConfig_GetNumberOfStreams,
VMR9FilterConfig_SetRenderingPrefs,
VMR9FilterConfig_GetRenderingPrefs,
VMR9FilterConfig_SetRenderingMode,
VMR9FilterConfig_GetRenderingMode
};
static HRESULT WINAPI VMR7WindowlessControl_QueryInterface(IVMRWindowlessControl *iface, REFIID riid,
LPVOID * ppv)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR7WindowlessControl_AddRef(IVMRWindowlessControl *iface)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR7WindowlessControl_Release(IVMRWindowlessControl *iface)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR7WindowlessControl_GetNativeVideoSize(IVMRWindowlessControl *iface,
LONG *width, LONG *height,
LONG *arwidth, LONG *arheight)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
TRACE("(%p/%p)->(%p, %p, %p, %p)\n", iface, This, width, height, arwidth, arheight);
if (!width || !height || !arwidth || !arheight)
{
ERR("Got no pointer\n");
return E_POINTER;
}
*width = This->bmiheader.biWidth;
*height = This->bmiheader.biHeight;
*arwidth = This->bmiheader.biWidth;
*arheight = This->bmiheader.biHeight;
return S_OK;
}
static HRESULT WINAPI VMR7WindowlessControl_GetMinIdealVideoSize(IVMRWindowlessControl *iface,
LONG *width, LONG *height)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_GetMaxIdealVideoSize(IVMRWindowlessControl *iface,
LONG *width, LONG *height)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_SetVideoPosition(IVMRWindowlessControl *iface,
const RECT *source, const RECT *dest)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
TRACE("(%p/%p)->(%p, %p)\n", iface, This, source, dest);
EnterCriticalSection(&This->renderer.filter.csFilter);
if (source)
This->source_rect = *source;
if (dest)
{
This->target_rect = *dest;
if (This->baseControlWindow.baseWindow.hWnd)
{
FIXME("Output rectangle: %s\n", wine_dbgstr_rect(dest));
SetWindowPos(This->baseControlWindow.baseWindow.hWnd, NULL,
dest->left, dest->top, dest->right - dest->left, dest->bottom-dest->top,
SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOOWNERZORDER|SWP_NOREDRAW);
}
}
LeaveCriticalSection(&This->renderer.filter.csFilter);
return S_OK;
}
static HRESULT WINAPI VMR7WindowlessControl_GetVideoPosition(IVMRWindowlessControl *iface,
RECT *source, RECT *dest)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
if (source)
*source = This->source_rect;
if (dest)
*dest = This->target_rect;
FIXME("(%p/%p)->(%p/%p) stub\n", iface, This, source, dest);
return S_OK;
}
static HRESULT WINAPI VMR7WindowlessControl_GetAspectRatioMode(IVMRWindowlessControl *iface,
DWORD *mode)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_SetAspectRatioMode(IVMRWindowlessControl *iface,
DWORD mode)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_SetVideoClippingWindow(IVMRWindowlessControl *iface, HWND window)
{
struct quartz_vmr *filter = impl_from_IVMRWindowlessControl(iface);
TRACE("iface %p, window %p.\n", iface, window);
return IVMRWindowlessControl9_SetVideoClippingWindow(&filter->IVMRWindowlessControl9_iface, window);
}
static HRESULT WINAPI VMR7WindowlessControl_RepaintVideo(IVMRWindowlessControl *iface,
HWND hwnd, HDC hdc)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_DisplayModeChanged(IVMRWindowlessControl *iface)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_GetCurrentImage(IVMRWindowlessControl *iface,
BYTE **dib)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_SetBorderColor(IVMRWindowlessControl *iface,
COLORREF color)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_GetBorderColor(IVMRWindowlessControl *iface,
COLORREF *color)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_SetColorKey(IVMRWindowlessControl *iface, COLORREF color)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7WindowlessControl_GetColorKey(IVMRWindowlessControl *iface, COLORREF *color)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static const IVMRWindowlessControlVtbl VMR7_WindowlessControl_Vtbl =
{
VMR7WindowlessControl_QueryInterface,
VMR7WindowlessControl_AddRef,
VMR7WindowlessControl_Release,
VMR7WindowlessControl_GetNativeVideoSize,
VMR7WindowlessControl_GetMinIdealVideoSize,
VMR7WindowlessControl_GetMaxIdealVideoSize,
VMR7WindowlessControl_SetVideoPosition,
VMR7WindowlessControl_GetVideoPosition,
VMR7WindowlessControl_GetAspectRatioMode,
VMR7WindowlessControl_SetAspectRatioMode,
VMR7WindowlessControl_SetVideoClippingWindow,
VMR7WindowlessControl_RepaintVideo,
VMR7WindowlessControl_DisplayModeChanged,
VMR7WindowlessControl_GetCurrentImage,
VMR7WindowlessControl_SetBorderColor,
VMR7WindowlessControl_GetBorderColor,
VMR7WindowlessControl_SetColorKey,
VMR7WindowlessControl_GetColorKey
};
static HRESULT WINAPI VMR9WindowlessControl_QueryInterface(IVMRWindowlessControl9 *iface, REFIID riid, LPVOID * ppv)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR9WindowlessControl_AddRef(IVMRWindowlessControl9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR9WindowlessControl_Release(IVMRWindowlessControl9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR9WindowlessControl_GetNativeVideoSize(IVMRWindowlessControl9 *iface, LONG *width, LONG *height, LONG *arwidth, LONG *arheight)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
TRACE("(%p/%p)->(%p, %p, %p, %p)\n", iface, This, width, height, arwidth, arheight);
if (!width || !height || !arwidth || !arheight)
{
ERR("Got no pointer\n");
return E_POINTER;
}
*width = This->bmiheader.biWidth;
*height = This->bmiheader.biHeight;
*arwidth = This->bmiheader.biWidth;
*arheight = This->bmiheader.biHeight;
return S_OK;
}
static HRESULT WINAPI VMR9WindowlessControl_GetMinIdealVideoSize(IVMRWindowlessControl9 *iface, LONG *width, LONG *height)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9WindowlessControl_GetMaxIdealVideoSize(IVMRWindowlessControl9 *iface, LONG *width, LONG *height)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9WindowlessControl_SetVideoPosition(IVMRWindowlessControl9 *iface, const RECT *source, const RECT *dest)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
TRACE("(%p/%p)->(%p, %p)\n", iface, This, source, dest);
EnterCriticalSection(&This->renderer.filter.csFilter);
if (source)
This->source_rect = *source;
if (dest)
{
This->target_rect = *dest;
if (This->baseControlWindow.baseWindow.hWnd)
{
FIXME("Output rectangle: %s\n", wine_dbgstr_rect(dest));
SetWindowPos(This->baseControlWindow.baseWindow.hWnd, NULL, dest->left, dest->top, dest->right - dest->left,
dest->bottom-dest->top, SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOOWNERZORDER|SWP_NOREDRAW);
}
}
LeaveCriticalSection(&This->renderer.filter.csFilter);
return S_OK;
}
static HRESULT WINAPI VMR9WindowlessControl_GetVideoPosition(IVMRWindowlessControl9 *iface, RECT *source, RECT *dest)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
if (source)
*source = This->source_rect;
if (dest)
*dest = This->target_rect;
FIXME("(%p/%p)->(%p/%p) stub\n", iface, This, source, dest);
return S_OK;
}
static HRESULT WINAPI VMR9WindowlessControl_GetAspectRatioMode(IVMRWindowlessControl9 *iface, DWORD *mode)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9WindowlessControl_SetAspectRatioMode(IVMRWindowlessControl9 *iface, DWORD mode)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9WindowlessControl_SetVideoClippingWindow(IVMRWindowlessControl9 *iface, HWND hwnd)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
TRACE("(%p/%p)->(%p)\n", iface, This, hwnd);
EnterCriticalSection(&This->renderer.filter.csFilter);
This->hWndClippingWindow = hwnd;
VMR9_maybe_init(This, FALSE);
if (!hwnd)
IVMRSurfaceAllocatorEx9_TerminateDevice(This->allocator, This->cookie);
LeaveCriticalSection(&This->renderer.filter.csFilter);
return S_OK;
}
static HRESULT WINAPI VMR9WindowlessControl_RepaintVideo(IVMRWindowlessControl9 *iface, HWND hwnd, HDC hdc)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
HRESULT hr;
FIXME("(%p/%p)->(...) semi-stub\n", iface, This);
EnterCriticalSection(&This->renderer.filter.csFilter);
if (hwnd != This->hWndClippingWindow && hwnd != This->baseControlWindow.baseWindow.hWnd)
{
ERR("Not handling changing windows yet!!!\n");
LeaveCriticalSection(&This->renderer.filter.csFilter);
return S_OK;
}
if (!This->allocator_d3d9_dev)
{
ERR("No d3d9 device!\n");
LeaveCriticalSection(&This->renderer.filter.csFilter);
return VFW_E_WRONG_STATE;
}
/* Windowless extension */
hr = IDirect3DDevice9_Present(This->allocator_d3d9_dev, NULL, NULL, This->baseControlWindow.baseWindow.hWnd, NULL);
LeaveCriticalSection(&This->renderer.filter.csFilter);
return hr;
}
static HRESULT WINAPI VMR9WindowlessControl_DisplayModeChanged(IVMRWindowlessControl9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9WindowlessControl_GetCurrentImage(IVMRWindowlessControl9 *iface, BYTE **dib)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9WindowlessControl_SetBorderColor(IVMRWindowlessControl9 *iface, COLORREF color)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR9WindowlessControl_GetBorderColor(IVMRWindowlessControl9 *iface, COLORREF *color)
{
struct quartz_vmr *This = impl_from_IVMRWindowlessControl9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static const IVMRWindowlessControl9Vtbl VMR9_WindowlessControl_Vtbl =
{
VMR9WindowlessControl_QueryInterface,
VMR9WindowlessControl_AddRef,
VMR9WindowlessControl_Release,
VMR9WindowlessControl_GetNativeVideoSize,
VMR9WindowlessControl_GetMinIdealVideoSize,
VMR9WindowlessControl_GetMaxIdealVideoSize,
VMR9WindowlessControl_SetVideoPosition,
VMR9WindowlessControl_GetVideoPosition,
VMR9WindowlessControl_GetAspectRatioMode,
VMR9WindowlessControl_SetAspectRatioMode,
VMR9WindowlessControl_SetVideoClippingWindow,
VMR9WindowlessControl_RepaintVideo,
VMR9WindowlessControl_DisplayModeChanged,
VMR9WindowlessControl_GetCurrentImage,
VMR9WindowlessControl_SetBorderColor,
VMR9WindowlessControl_GetBorderColor
};
static HRESULT WINAPI VMR7SurfaceAllocatorNotify_QueryInterface(IVMRSurfaceAllocatorNotify *iface,
REFIID riid, LPVOID * ppv)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR7SurfaceAllocatorNotify_AddRef(IVMRSurfaceAllocatorNotify *iface)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR7SurfaceAllocatorNotify_Release(IVMRSurfaceAllocatorNotify *iface)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR7SurfaceAllocatorNotify_AdviseSurfaceAllocator(IVMRSurfaceAllocatorNotify *iface,
DWORD_PTR id,
IVMRSurfaceAllocator *alloc)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7SurfaceAllocatorNotify_SetDDrawDevice(IVMRSurfaceAllocatorNotify *iface,
IDirectDraw7 *device, HMONITOR monitor)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7SurfaceAllocatorNotify_ChangeDDrawDevice(IVMRSurfaceAllocatorNotify *iface,
IDirectDraw7 *device, HMONITOR monitor)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7SurfaceAllocatorNotify_RestoreDDrawSurfaces(IVMRSurfaceAllocatorNotify *iface)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7SurfaceAllocatorNotify_NotifyEvent(IVMRSurfaceAllocatorNotify *iface, LONG code,
LONG_PTR param1, LONG_PTR param2)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static HRESULT WINAPI VMR7SurfaceAllocatorNotify_SetBorderColor(IVMRSurfaceAllocatorNotify *iface,
COLORREF clrBorder)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static const IVMRSurfaceAllocatorNotifyVtbl VMR7_SurfaceAllocatorNotify_Vtbl =
{
VMR7SurfaceAllocatorNotify_QueryInterface,
VMR7SurfaceAllocatorNotify_AddRef,
VMR7SurfaceAllocatorNotify_Release,
VMR7SurfaceAllocatorNotify_AdviseSurfaceAllocator,
VMR7SurfaceAllocatorNotify_SetDDrawDevice,
VMR7SurfaceAllocatorNotify_ChangeDDrawDevice,
VMR7SurfaceAllocatorNotify_RestoreDDrawSurfaces,
VMR7SurfaceAllocatorNotify_NotifyEvent,
VMR7SurfaceAllocatorNotify_SetBorderColor
};
static HRESULT WINAPI VMR9SurfaceAllocatorNotify_QueryInterface(IVMRSurfaceAllocatorNotify9 *iface, REFIID riid, LPVOID * ppv)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
return IUnknown_QueryInterface(This->renderer.filter.outer_unk, riid, ppv);
}
static ULONG WINAPI VMR9SurfaceAllocatorNotify_AddRef(IVMRSurfaceAllocatorNotify9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
return IUnknown_AddRef(This->renderer.filter.outer_unk);
}
static ULONG WINAPI VMR9SurfaceAllocatorNotify_Release(IVMRSurfaceAllocatorNotify9 *iface)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
return IUnknown_Release(This->renderer.filter.outer_unk);
}
static HRESULT WINAPI VMR9SurfaceAllocatorNotify_AdviseSurfaceAllocator(IVMRSurfaceAllocatorNotify9 *iface, DWORD_PTR id, IVMRSurfaceAllocator9 *alloc)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
/* FIXME: This code is not tested!!! */
FIXME("(%p/%p)->(...) stub\n", iface, This);
This->cookie = id;
if (This->presenter)
return VFW_E_WRONG_STATE;
if (FAILED(IVMRSurfaceAllocator9_QueryInterface(alloc, &IID_IVMRImagePresenter9, (void **)&This->presenter)))
return E_NOINTERFACE;
if (SUCCEEDED(IVMRSurfaceAllocator9_QueryInterface(alloc, &IID_IVMRSurfaceAllocatorEx9, (void **)&This->allocator)))
This->allocator_is_ex = 1;
else
{
This->allocator = (IVMRSurfaceAllocatorEx9 *)alloc;
IVMRSurfaceAllocator9_AddRef(alloc);
This->allocator_is_ex = 0;
}
return S_OK;
}
static HRESULT WINAPI VMR9SurfaceAllocatorNotify_SetD3DDevice(IVMRSurfaceAllocatorNotify9 *iface, IDirect3DDevice9 *device, HMONITOR monitor)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
FIXME("(%p/%p)->(...) semi-stub\n", iface, This);
if (This->allocator_d3d9_dev)
IDirect3DDevice9_Release(This->allocator_d3d9_dev);
This->allocator_d3d9_dev = device;
IDirect3DDevice9_AddRef(This->allocator_d3d9_dev);
This->allocator_mon = monitor;
return S_OK;
}
static HRESULT WINAPI VMR9SurfaceAllocatorNotify_ChangeD3DDevice(IVMRSurfaceAllocatorNotify9 *iface, IDirect3DDevice9 *device, HMONITOR monitor)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
FIXME("(%p/%p)->(...) semi-stub\n", iface, This);
if (This->allocator_d3d9_dev)
IDirect3DDevice9_Release(This->allocator_d3d9_dev);
This->allocator_d3d9_dev = device;
IDirect3DDevice9_AddRef(This->allocator_d3d9_dev);
This->allocator_mon = monitor;
return S_OK;
}
static HRESULT WINAPI VMR9SurfaceAllocatorNotify_AllocateSurfaceHelper(IVMRSurfaceAllocatorNotify9 *iface, VMR9AllocationInfo *allocinfo, DWORD *numbuffers, IDirect3DSurface9 **surface)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
DWORD i;
HRESULT hr = S_OK;
FIXME("(%p/%p)->(%p, %p => %u, %p) semi-stub\n", iface, This, allocinfo, numbuffers, (numbuffers ? *numbuffers : 0), surface);
if (!allocinfo || !numbuffers || !surface)
return E_POINTER;
if (!*numbuffers || *numbuffers < allocinfo->MinBuffers)
{
ERR("Invalid number of buffers?\n");
return E_INVALIDARG;
}
if (!This->allocator_d3d9_dev)
{
ERR("No direct3d device when requested to allocate a surface!\n");
return VFW_E_WRONG_STATE;
}
if (allocinfo->dwFlags & VMR9AllocFlag_OffscreenSurface)
{
ERR("Creating offscreen surface\n");
for (i = 0; i < *numbuffers; ++i)
{
hr = IDirect3DDevice9_CreateOffscreenPlainSurface(This->allocator_d3d9_dev, allocinfo->dwWidth, allocinfo->dwHeight,
allocinfo->Format, allocinfo->Pool, &surface[i], NULL);
if (FAILED(hr))
break;
}
}
else if (allocinfo->dwFlags & VMR9AllocFlag_TextureSurface)
{
TRACE("Creating texture surface\n");
for (i = 0; i < *numbuffers; ++i)
{
IDirect3DTexture9 *texture;
hr = IDirect3DDevice9_CreateTexture(This->allocator_d3d9_dev, allocinfo->dwWidth, allocinfo->dwHeight, 1, 0,
allocinfo->Format, allocinfo->Pool, &texture, NULL);
if (FAILED(hr))
break;
IDirect3DTexture9_GetSurfaceLevel(texture, 0, &surface[i]);
IDirect3DTexture9_Release(texture);
}
}
else
{
FIXME("Could not allocate for type %08x\n", allocinfo->dwFlags);
return E_NOTIMPL;
}
if (i >= allocinfo->MinBuffers)
{
hr = S_OK;
*numbuffers = i;
}
else
{
for ( ; i > 0; --i) IDirect3DSurface9_Release(surface[i - 1]);
*numbuffers = 0;
}
return hr;
}
static HRESULT WINAPI VMR9SurfaceAllocatorNotify_NotifyEvent(IVMRSurfaceAllocatorNotify9 *iface, LONG code, LONG_PTR param1, LONG_PTR param2)
{
struct quartz_vmr *This = impl_from_IVMRSurfaceAllocatorNotify9(iface);
FIXME("(%p/%p)->(...) stub\n", iface, This);
return E_NOTIMPL;
}
static const IVMRSurfaceAllocatorNotify9Vtbl VMR9_SurfaceAllocatorNotify_Vtbl =
{
VMR9SurfaceAllocatorNotify_QueryInterface,
VMR9SurfaceAllocatorNotify_AddRef,
VMR9SurfaceAllocatorNotify_Release,
VMR9SurfaceAllocatorNotify_AdviseSurfaceAllocator,
VMR9SurfaceAllocatorNotify_SetD3DDevice,
VMR9SurfaceAllocatorNotify_ChangeD3DDevice,
VMR9SurfaceAllocatorNotify_AllocateSurfaceHelper,
VMR9SurfaceAllocatorNotify_NotifyEvent
};
static HRESULT vmr_create(IUnknown *outer, void **out, const CLSID *clsid)
{
static const WCHAR sink_name[] = {'V','M','R',' ','I','n','p','u','t','0',0};
HRESULT hr;
struct quartz_vmr* pVMR;
*out = NULL;
pVMR = CoTaskMemAlloc(sizeof(struct quartz_vmr));
pVMR->hD3d9 = LoadLibraryA("d3d9.dll");
if (!pVMR->hD3d9 )
{
WARN("Could not load d3d9.dll\n");
CoTaskMemFree(pVMR);
return VFW_E_DDRAW_CAPS_NOT_SUITABLE;
}
pVMR->IAMCertifiedOutputProtection_iface.lpVtbl = &IAMCertifiedOutputProtection_Vtbl;
pVMR->IAMFilterMiscFlags_iface.lpVtbl = &IAMFilterMiscFlags_Vtbl;
pVMR->mode = 0;
pVMR->allocator_d3d9_dev = NULL;
pVMR->allocator_mon= NULL;
pVMR->num_surfaces = pVMR->cur_surface = 0;
pVMR->allocator = NULL;
pVMR->presenter = NULL;
pVMR->hWndClippingWindow = NULL;
pVMR->IVMRFilterConfig_iface.lpVtbl = &VMR7_FilterConfig_Vtbl;
pVMR->IVMRFilterConfig9_iface.lpVtbl = &VMR9_FilterConfig_Vtbl;
pVMR->IVMRMonitorConfig_iface.lpVtbl = &VMR7_MonitorConfig_Vtbl;
pVMR->IVMRMonitorConfig9_iface.lpVtbl = &VMR9_MonitorConfig_Vtbl;
pVMR->IVMRSurfaceAllocatorNotify_iface.lpVtbl = &VMR7_SurfaceAllocatorNotify_Vtbl;
pVMR->IVMRSurfaceAllocatorNotify9_iface.lpVtbl = &VMR9_SurfaceAllocatorNotify_Vtbl;
pVMR->IVMRWindowlessControl_iface.lpVtbl = &VMR7_WindowlessControl_Vtbl;
pVMR->IVMRWindowlessControl9_iface.lpVtbl = &VMR9_WindowlessControl_Vtbl;
hr = strmbase_renderer_init(&pVMR->renderer, &VMR_Vtbl, outer, clsid, sink_name, &BaseFuncTable);
if (FAILED(hr))
goto fail;
hr = BaseControlWindow_Init(&pVMR->baseControlWindow, &IVideoWindow_VTable,
&pVMR->renderer.filter, &pVMR->renderer.filter.csFilter,
&pVMR->renderer.sink.pin, &renderer_BaseWindowFuncTable);
if (FAILED(hr))
goto fail;
hr = strmbase_video_init(&pVMR->baseControlVideo, &pVMR->renderer.filter,
&pVMR->renderer.filter.csFilter, &pVMR->renderer.sink.pin,
&renderer_BaseControlVideoFuncTable);
if (FAILED(hr))
goto fail;
*out = &pVMR->renderer.filter.IUnknown_inner;
ZeroMemory(&pVMR->source_rect, sizeof(RECT));
ZeroMemory(&pVMR->target_rect, sizeof(RECT));
TRACE("Created at %p\n", pVMR);
return hr;
fail:
strmbase_renderer_cleanup(&pVMR->renderer);
FreeLibrary(pVMR->hD3d9);
CoTaskMemFree(pVMR);
return hr;
}
HRESULT VMR7Impl_create(IUnknown *outer_unk, LPVOID *ppv)
{
return vmr_create(outer_unk, ppv, &CLSID_VideoMixingRenderer);
}
HRESULT VMR9Impl_create(IUnknown *outer_unk, LPVOID *ppv)
{
return vmr_create(outer_unk, ppv, &CLSID_VideoMixingRenderer9);
}
static HRESULT WINAPI VMR9_ImagePresenter_QueryInterface(IVMRImagePresenter9 *iface, REFIID riid, void **ppv)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRImagePresenter9(iface);
TRACE("(%p/%p)->(%s, %p)\n", This, iface, qzdebugstr_guid(riid), ppv);
*ppv = NULL;
if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IVMRImagePresenter9))
*ppv = &This->IVMRImagePresenter9_iface;
else if (IsEqualIID(riid, &IID_IVMRSurfaceAllocatorEx9))
*ppv = &This->IVMRSurfaceAllocatorEx9_iface;
if (*ppv)
{
IUnknown_AddRef((IUnknown *)(*ppv));
return S_OK;
}
FIXME("No interface for %s\n", debugstr_guid(riid));
return E_NOINTERFACE;
}
static ULONG WINAPI VMR9_ImagePresenter_AddRef(IVMRImagePresenter9 *iface)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRImagePresenter9(iface);
ULONG refCount = InterlockedIncrement(&This->refCount);
TRACE("(%p)->() AddRef from %d\n", iface, refCount - 1);
return refCount;
}
static ULONG WINAPI VMR9_ImagePresenter_Release(IVMRImagePresenter9 *iface)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRImagePresenter9(iface);
ULONG refCount = InterlockedDecrement(&This->refCount);
TRACE("(%p)->() Release from %d\n", iface, refCount + 1);
if (!refCount)
{
DWORD i;
TRACE("Destroying\n");
CloseHandle(This->ack);
IDirect3D9_Release(This->d3d9_ptr);
TRACE("Number of surfaces: %u\n", This->num_surfaces);
for (i = 0; i < This->num_surfaces; ++i)
{
IDirect3DSurface9 *surface = This->d3d9_surfaces[i];
TRACE("Releasing surface %p\n", surface);
if (surface)
IDirect3DSurface9_Release(surface);
}
CoTaskMemFree(This->d3d9_surfaces);
This->d3d9_surfaces = NULL;
This->num_surfaces = 0;
if (This->d3d9_vertex)
{
IDirect3DVertexBuffer9_Release(This->d3d9_vertex);
This->d3d9_vertex = NULL;
}
CoTaskMemFree(This);
return 0;
}
return refCount;
}
static HRESULT WINAPI VMR9_ImagePresenter_StartPresenting(IVMRImagePresenter9 *iface, DWORD_PTR id)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRImagePresenter9(iface);
TRACE("(%p/%p/%p)->(...) stub\n", iface, This,This->pVMR9);
return S_OK;
}
static HRESULT WINAPI VMR9_ImagePresenter_StopPresenting(IVMRImagePresenter9 *iface, DWORD_PTR id)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRImagePresenter9(iface);
TRACE("(%p/%p/%p)->(...) stub\n", iface, This,This->pVMR9);
return S_OK;
}
#define USED_FVF (D3DFVF_XYZRHW | D3DFVF_TEX1)
struct VERTEX { float x, y, z, rhw, u, v; };
static HRESULT VMR9_ImagePresenter_PresentTexture(VMR9DefaultAllocatorPresenterImpl *This, IDirect3DSurface9 *surface)
{
IDirect3DTexture9 *texture = NULL;
HRESULT hr;
hr = IDirect3DDevice9_SetFVF(This->d3d9_dev, USED_FVF);
if (FAILED(hr))
{
FIXME("SetFVF: %08x\n", hr);
return hr;
}
hr = IDirect3DDevice9_SetStreamSource(This->d3d9_dev, 0, This->d3d9_vertex, 0, sizeof(struct VERTEX));
if (FAILED(hr))
{
FIXME("SetStreamSource: %08x\n", hr);
return hr;
}
hr = IDirect3DSurface9_GetContainer(surface, &IID_IDirect3DTexture9, (void **) &texture);
if (FAILED(hr))
{
FIXME("IDirect3DSurface9_GetContainer failed\n");
return hr;
}
hr = IDirect3DDevice9_SetTexture(This->d3d9_dev, 0, (IDirect3DBaseTexture9 *)texture);
IDirect3DTexture9_Release(texture);
if (FAILED(hr))
{
FIXME("SetTexture: %08x\n", hr);
return hr;
}
hr = IDirect3DDevice9_DrawPrimitive(This->d3d9_dev, D3DPT_TRIANGLESTRIP, 0, 2);
if (FAILED(hr))
{
FIXME("DrawPrimitive: %08x\n", hr);
return hr;
}
return S_OK;
}
static HRESULT VMR9_ImagePresenter_PresentOffscreenSurface(VMR9DefaultAllocatorPresenterImpl *This, IDirect3DSurface9 *surface)
{
HRESULT hr;
IDirect3DSurface9 *target = NULL;
RECT target_rect;
hr = IDirect3DDevice9_GetBackBuffer(This->d3d9_dev, 0, 0, D3DBACKBUFFER_TYPE_MONO, &target);
if (FAILED(hr))
{
ERR("IDirect3DDevice9_GetBackBuffer -- %08x\n", hr);
return hr;
}
/* Move rect to origin and flip it */
SetRect(&target_rect, 0, This->pVMR9->target_rect.bottom - This->pVMR9->target_rect.top,
This->pVMR9->target_rect.right - This->pVMR9->target_rect.left, 0);
hr = IDirect3DDevice9_StretchRect(This->d3d9_dev, surface, &This->pVMR9->source_rect, target, &target_rect, D3DTEXF_LINEAR);
if (FAILED(hr))
ERR("IDirect3DDevice9_StretchRect -- %08x\n", hr);
IDirect3DSurface9_Release(target);
return hr;
}
static HRESULT WINAPI VMR9_ImagePresenter_PresentImage(IVMRImagePresenter9 *iface, DWORD_PTR id, VMR9PresentationInfo *info)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRImagePresenter9(iface);
HRESULT hr;
RECT output;
BOOL render = FALSE;
TRACE("(%p/%p/%p)->(...) stub\n", iface, This, This->pVMR9);
GetWindowRect(This->pVMR9->baseControlWindow.baseWindow.hWnd, &output);
TRACE("Output rectangle: %s\n", wine_dbgstr_rect(&output));
/* This might happen if we don't have active focus (eg on a different virtual desktop) */
if (!This->d3d9_dev)
return S_OK;
/* Display image here */
hr = IDirect3DDevice9_Clear(This->d3d9_dev, 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
if (FAILED(hr))
FIXME("hr: %08x\n", hr);
hr = IDirect3DDevice9_BeginScene(This->d3d9_dev);
if (SUCCEEDED(hr))
{
if (This->d3d9_vertex)
hr = VMR9_ImagePresenter_PresentTexture(This, info->lpSurf);
else
hr = VMR9_ImagePresenter_PresentOffscreenSurface(This, info->lpSurf);
render = SUCCEEDED(hr);
}
else
FIXME("BeginScene: %08x\n", hr);
hr = IDirect3DDevice9_EndScene(This->d3d9_dev);
if (render && SUCCEEDED(hr))
{
hr = IDirect3DDevice9_Present(This->d3d9_dev, NULL, NULL, This->pVMR9->baseControlWindow.baseWindow.hWnd, NULL);
if (FAILED(hr))
FIXME("Presenting image: %08x\n", hr);
}
return S_OK;
}
static const IVMRImagePresenter9Vtbl VMR9_ImagePresenter =
{
VMR9_ImagePresenter_QueryInterface,
VMR9_ImagePresenter_AddRef,
VMR9_ImagePresenter_Release,
VMR9_ImagePresenter_StartPresenting,
VMR9_ImagePresenter_StopPresenting,
VMR9_ImagePresenter_PresentImage
};
static HRESULT WINAPI VMR9_SurfaceAllocator_QueryInterface(IVMRSurfaceAllocatorEx9 *iface, REFIID riid, LPVOID * ppv)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRSurfaceAllocatorEx9(iface);
return VMR9_ImagePresenter_QueryInterface(&This->IVMRImagePresenter9_iface, riid, ppv);
}
static ULONG WINAPI VMR9_SurfaceAllocator_AddRef(IVMRSurfaceAllocatorEx9 *iface)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRSurfaceAllocatorEx9(iface);
return VMR9_ImagePresenter_AddRef(&This->IVMRImagePresenter9_iface);
}
static ULONG WINAPI VMR9_SurfaceAllocator_Release(IVMRSurfaceAllocatorEx9 *iface)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRSurfaceAllocatorEx9(iface);
return VMR9_ImagePresenter_Release(&This->IVMRImagePresenter9_iface);
}
static HRESULT VMR9_SurfaceAllocator_SetAllocationSettings(VMR9DefaultAllocatorPresenterImpl *This, VMR9AllocationInfo *allocinfo)
{
D3DCAPS9 caps;
UINT width, height;
HRESULT hr;
if (!(allocinfo->dwFlags & VMR9AllocFlag_TextureSurface))
/* Only needed for texture surfaces */
return S_OK;
hr = IDirect3DDevice9_GetDeviceCaps(This->d3d9_dev, &caps);
if (FAILED(hr))
return hr;
if (!(caps.TextureCaps & D3DPTEXTURECAPS_POW2) || (caps.TextureCaps & D3DPTEXTURECAPS_SQUAREONLY))
{
width = allocinfo->dwWidth;
height = allocinfo->dwHeight;
}
else
{
width = height = 1;
while (width < allocinfo->dwWidth)
width *= 2;
while (height < allocinfo->dwHeight)
height *= 2;
FIXME("NPOW2 support missing, not using proper surfaces!\n");
}
if (caps.TextureCaps & D3DPTEXTURECAPS_SQUAREONLY)
{
if (height > width)
width = height;
else
height = width;
FIXME("Square texture support required..\n");
}
hr = IDirect3DDevice9_CreateVertexBuffer(This->d3d9_dev, 4 * sizeof(struct VERTEX), D3DUSAGE_WRITEONLY, USED_FVF, allocinfo->Pool, &This->d3d9_vertex, NULL);
if (FAILED(hr))
{
ERR("Couldn't create vertex buffer: %08x\n", hr);
return hr;
}
This->reset = TRUE;
allocinfo->dwHeight = height;
allocinfo->dwWidth = width;
return hr;
}
static DWORD WINAPI MessageLoop(LPVOID lpParameter)
{
MSG msg;
BOOL fGotMessage;
VMR9DefaultAllocatorPresenterImpl *This = lpParameter;
TRACE("Starting message loop\n");
if (FAILED(BaseWindowImpl_PrepareWindow(&This->pVMR9->baseControlWindow.baseWindow)))
{
FIXME("Failed to prepare window\n");
return FALSE;
}
SetEvent(This->ack);
while ((fGotMessage = GetMessageW(&msg, NULL, 0, 0)) != 0 && fGotMessage != -1)
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
TRACE("End of message loop\n");
return 0;
}
static UINT d3d9_adapter_from_hwnd(IDirect3D9 *d3d9, HWND hwnd, HMONITOR *mon_out)
{
UINT d3d9_adapter;
HMONITOR mon;
mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL);
if (!mon)
d3d9_adapter = 0;
else
{
for (d3d9_adapter = 0; d3d9_adapter < IDirect3D9_GetAdapterCount(d3d9); ++d3d9_adapter)
{
if (mon == IDirect3D9_GetAdapterMonitor(d3d9, d3d9_adapter))
break;
}
if (d3d9_adapter >= IDirect3D9_GetAdapterCount(d3d9))
d3d9_adapter = 0;
}
if (mon_out)
*mon_out = mon;
return d3d9_adapter;
}
static BOOL CreateRenderingWindow(VMR9DefaultAllocatorPresenterImpl *This, VMR9AllocationInfo *info, DWORD *numbuffers)
{
D3DPRESENT_PARAMETERS d3dpp;
DWORD d3d9_adapter;
HRESULT hr;
TRACE("(%p)->()\n", This);
This->hWndThread = CreateThread(NULL, 0, MessageLoop, This, 0, &This->tid);
if (!This->hWndThread)
return FALSE;
WaitForSingleObject(This->ack, INFINITE);
if (!This->pVMR9->baseControlWindow.baseWindow.hWnd) return FALSE;
/* Obtain a monitor and d3d9 device */
d3d9_adapter = d3d9_adapter_from_hwnd(This->d3d9_ptr, This->pVMR9->baseControlWindow.baseWindow.hWnd, &This->hMon);
/* Now try to create the d3d9 device */
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.hDeviceWindow = This->pVMR9->baseControlWindow.baseWindow.hWnd;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferHeight = This->pVMR9->target_rect.bottom - This->pVMR9->target_rect.top;
d3dpp.BackBufferWidth = This->pVMR9->target_rect.right - This->pVMR9->target_rect.left;
hr = IDirect3D9_CreateDevice(This->d3d9_ptr, d3d9_adapter, D3DDEVTYPE_HAL, NULL, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp, &This->d3d9_dev);
if (FAILED(hr))
{
ERR("Could not create device: %08x\n", hr);
BaseWindowImpl_DoneWithWindow(&This->pVMR9->baseControlWindow.baseWindow);
return FALSE;
}
IVMRSurfaceAllocatorNotify9_SetD3DDevice(This->SurfaceAllocatorNotify, This->d3d9_dev, This->hMon);
This->d3d9_surfaces = CoTaskMemAlloc(*numbuffers * sizeof(IDirect3DSurface9 *));
ZeroMemory(This->d3d9_surfaces, *numbuffers * sizeof(IDirect3DSurface9 *));
hr = VMR9_SurfaceAllocator_SetAllocationSettings(This, info);
if (FAILED(hr))
ERR("Setting allocation settings failed: %08x\n", hr);
if (SUCCEEDED(hr))
{
hr = IVMRSurfaceAllocatorNotify9_AllocateSurfaceHelper(This->SurfaceAllocatorNotify, info, numbuffers, This->d3d9_surfaces);
if (FAILED(hr))
ERR("Allocating surfaces failed: %08x\n", hr);
}
if (FAILED(hr))
{
IVMRSurfaceAllocatorEx9_TerminateDevice(This->pVMR9->allocator, This->pVMR9->cookie);
BaseWindowImpl_DoneWithWindow(&This->pVMR9->baseControlWindow.baseWindow);
return FALSE;
}
This->num_surfaces = *numbuffers;
return TRUE;
}
static HRESULT WINAPI VMR9_SurfaceAllocator_InitializeDevice(IVMRSurfaceAllocatorEx9 *iface, DWORD_PTR id, VMR9AllocationInfo *allocinfo, DWORD *numbuffers)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRSurfaceAllocatorEx9(iface);
if (This->pVMR9->mode != VMR9Mode_Windowed && !This->pVMR9->hWndClippingWindow)
{
ERR("No window set\n");
return VFW_E_WRONG_STATE;
}
This->info = *allocinfo;
if (!CreateRenderingWindow(This, allocinfo, numbuffers))
{
ERR("Failed to create rendering window, expect no output!\n");
return VFW_E_WRONG_STATE;
}
return S_OK;
}
static HRESULT WINAPI VMR9_SurfaceAllocator_TerminateDevice(IVMRSurfaceAllocatorEx9 *iface, DWORD_PTR id)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRSurfaceAllocatorEx9(iface);
if (!This->pVMR9->baseControlWindow.baseWindow.hWnd)
{
return S_OK;
}
SendMessageW(This->pVMR9->baseControlWindow.baseWindow.hWnd, WM_CLOSE, 0, 0);
PostThreadMessageW(This->tid, WM_QUIT, 0, 0);
WaitForSingleObject(This->hWndThread, INFINITE);
This->hWndThread = NULL;
BaseWindowImpl_DoneWithWindow(&This->pVMR9->baseControlWindow.baseWindow);
return S_OK;
}
/* Recreate all surfaces (If allocated as D3DPOOL_DEFAULT) and survive! */
static HRESULT VMR9_SurfaceAllocator_UpdateDeviceReset(VMR9DefaultAllocatorPresenterImpl *This)
{
struct VERTEX t_vert[4];
UINT width, height;
unsigned int i;
void *bits = NULL;
D3DPRESENT_PARAMETERS d3dpp;
HRESULT hr;
if (!This->pVMR9->baseControlWindow.baseWindow.hWnd)
{
ERR("No window\n");
return E_FAIL;
}
if (!This->d3d9_surfaces || !This->reset)
return S_OK;
This->reset = FALSE;
TRACE("RESETTING\n");
if (This->d3d9_vertex)
{
IDirect3DVertexBuffer9_Release(This->d3d9_vertex);
This->d3d9_vertex = NULL;
}
for (i = 0; i < This->num_surfaces; ++i)
{
IDirect3DSurface9 *surface = This->d3d9_surfaces[i];
TRACE("Releasing surface %p\n", surface);
if (surface)
IDirect3DSurface9_Release(surface);
}
ZeroMemory(This->d3d9_surfaces, sizeof(IDirect3DSurface9 *) * This->num_surfaces);
/* Now try to create the d3d9 device */
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.hDeviceWindow = This->pVMR9->baseControlWindow.baseWindow.hWnd;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
if (This->d3d9_dev)
IDirect3DDevice9_Release(This->d3d9_dev);
This->d3d9_dev = NULL;
hr = IDirect3D9_CreateDevice(This->d3d9_ptr, d3d9_adapter_from_hwnd(This->d3d9_ptr, This->pVMR9->baseControlWindow.baseWindow.hWnd, &This->hMon), D3DDEVTYPE_HAL, NULL, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &This->d3d9_dev);
if (FAILED(hr))
{
hr = IDirect3D9_CreateDevice(This->d3d9_ptr, d3d9_adapter_from_hwnd(This->d3d9_ptr, This->pVMR9->baseControlWindow.baseWindow.hWnd, &This->hMon), D3DDEVTYPE_HAL, NULL, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp, &This->d3d9_dev);
if (FAILED(hr))
{
ERR("--> Creating device: %08x\n", hr);
return S_OK;
}
}
IVMRSurfaceAllocatorNotify9_ChangeD3DDevice(This->SurfaceAllocatorNotify, This->d3d9_dev, This->hMon);
IVMRSurfaceAllocatorNotify9_AllocateSurfaceHelper(This->SurfaceAllocatorNotify, &This->info, &This->num_surfaces, This->d3d9_surfaces);
This->reset = FALSE;
if (!(This->info.dwFlags & VMR9AllocFlag_TextureSurface))
return S_OK;
hr = IDirect3DDevice9_CreateVertexBuffer(This->d3d9_dev, 4 * sizeof(struct VERTEX), D3DUSAGE_WRITEONLY, USED_FVF,
This->info.Pool, &This->d3d9_vertex, NULL);
width = This->info.dwWidth;
height = This->info.dwHeight;
for (i = 0; i < ARRAY_SIZE(t_vert); ++i)
{
if (i % 2)
{
t_vert[i].x = (float)This->pVMR9->target_rect.right - (float)This->pVMR9->target_rect.left - 0.5f;
t_vert[i].u = (float)This->pVMR9->source_rect.right / (float)width;
}
else
{
t_vert[i].x = -0.5f;
t_vert[i].u = (float)This->pVMR9->source_rect.left / (float)width;
}
if (i % 4 < 2)
{
t_vert[i].y = -0.5f;
t_vert[i].v = (float)This->pVMR9->source_rect.bottom / (float)height;
}
else
{
t_vert[i].y = (float)This->pVMR9->target_rect.bottom - (float)This->pVMR9->target_rect.top - 0.5f;
t_vert[i].v = (float)This->pVMR9->source_rect.top / (float)height;
}
t_vert[i].z = 0.0f;
t_vert[i].rhw = 1.0f;
}
FIXME("Vertex rectangle:\n");
FIXME("X, Y: %f, %f\n", t_vert[0].x, t_vert[0].y);
FIXME("X, Y: %f, %f\n", t_vert[3].x, t_vert[3].y);
FIXME("TOP, LEFT: %f, %f\n", t_vert[0].u, t_vert[0].v);
FIXME("DOWN, BOTTOM: %f, %f\n", t_vert[3].u, t_vert[3].v);
IDirect3DVertexBuffer9_Lock(This->d3d9_vertex, 0, sizeof(t_vert), &bits, 0);
memcpy(bits, t_vert, sizeof(t_vert));
IDirect3DVertexBuffer9_Unlock(This->d3d9_vertex);
return S_OK;
}
static HRESULT WINAPI VMR9_SurfaceAllocator_GetSurface(IVMRSurfaceAllocatorEx9 *iface, DWORD_PTR id, DWORD surfaceindex, DWORD flags, IDirect3DSurface9 **surface)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRSurfaceAllocatorEx9(iface);
/* Update everything first, this is needed because the surface might be destroyed in the reset */
if (!This->d3d9_dev)
{
TRACE("Device has left me!\n");
return E_FAIL;
}
VMR9_SurfaceAllocator_UpdateDeviceReset(This);
if (surfaceindex >= This->num_surfaces)
{
ERR("surfaceindex is greater than num_surfaces\n");
return E_FAIL;
}
*surface = This->d3d9_surfaces[surfaceindex];
IDirect3DSurface9_AddRef(*surface);
return S_OK;
}
static HRESULT WINAPI VMR9_SurfaceAllocator_AdviseNotify(IVMRSurfaceAllocatorEx9 *iface, IVMRSurfaceAllocatorNotify9 *allocnotify)
{
VMR9DefaultAllocatorPresenterImpl *This = impl_from_IVMRSurfaceAllocatorEx9(iface);
TRACE("(%p/%p)->(...)\n", iface, This);
/* No AddRef taken here or the base VMR9 filter would never be destroyed */
This->SurfaceAllocatorNotify = allocnotify;
return S_OK;
}
static const IVMRSurfaceAllocatorEx9Vtbl VMR9_SurfaceAllocator =
{
VMR9_SurfaceAllocator_QueryInterface,
VMR9_SurfaceAllocator_AddRef,
VMR9_SurfaceAllocator_Release,
VMR9_SurfaceAllocator_InitializeDevice,
VMR9_SurfaceAllocator_TerminateDevice,
VMR9_SurfaceAllocator_GetSurface,
VMR9_SurfaceAllocator_AdviseNotify,
NULL /* This isn't the SurfaceAllocatorEx type yet, working on it */
};
static IDirect3D9 *init_d3d9(HMODULE d3d9_handle)
{
IDirect3D9 * (__stdcall * d3d9_create)(UINT SDKVersion);
d3d9_create = (void *)GetProcAddress(d3d9_handle, "Direct3DCreate9");
if (!d3d9_create) return NULL;
return d3d9_create(D3D_SDK_VERSION);
}
static HRESULT VMR9DefaultAllocatorPresenterImpl_create(struct quartz_vmr *parent, LPVOID * ppv)
{
HRESULT hr = S_OK;
int i;
VMR9DefaultAllocatorPresenterImpl* This;
This = CoTaskMemAlloc(sizeof(VMR9DefaultAllocatorPresenterImpl));
if (!This)
return E_OUTOFMEMORY;
This->d3d9_ptr = init_d3d9(parent->hD3d9);
if (!This->d3d9_ptr)
{
WARN("Could not initialize d3d9.dll\n");
CoTaskMemFree(This);
return VFW_E_DDRAW_CAPS_NOT_SUITABLE;
}
i = 0;
do
{
D3DDISPLAYMODE mode;
hr = IDirect3D9_EnumAdapterModes(This->d3d9_ptr, i++, D3DFMT_X8R8G8B8, 0, &mode);
if (hr == D3DERR_INVALIDCALL) break; /* out of adapters */
} while (FAILED(hr));
if (FAILED(hr))
ERR("HR: %08x\n", hr);
if (hr == D3DERR_NOTAVAILABLE)
{
ERR("Format not supported\n");
IDirect3D9_Release(This->d3d9_ptr);
CoTaskMemFree(This);
return VFW_E_DDRAW_CAPS_NOT_SUITABLE;
}
This->IVMRImagePresenter9_iface.lpVtbl = &VMR9_ImagePresenter;
This->IVMRSurfaceAllocatorEx9_iface.lpVtbl = &VMR9_SurfaceAllocator;
This->refCount = 1;
This->pVMR9 = parent;
This->d3d9_surfaces = NULL;
This->d3d9_dev = NULL;
This->hMon = 0;
This->d3d9_vertex = NULL;
This->num_surfaces = 0;
This->hWndThread = NULL;
This->ack = CreateEventW(NULL, 0, 0, NULL);
This->SurfaceAllocatorNotify = NULL;
This->reset = FALSE;
*ppv = &This->IVMRImagePresenter9_iface;
return S_OK;
}
| 33.324561 | 235 | 0.69732 | [
"render"
] |
2c9f2926a9d274e8baa22c81eb01a90ea1450f65 | 1,548 | c | C | source/matrix/jit.alphablend/max.jit.alphablend.c | maevagrondin/max_externals | 9083d877c0091077f823aa42665209050f4ebfde | [
"MIT"
] | 16 | 2017-12-20T08:25:15.000Z | 2021-12-22T22:31:49.000Z | source/matrix/jit.alphablend/max.jit.alphablend.c | maevagrondin/max_externals | 9083d877c0091077f823aa42665209050f4ebfde | [
"MIT"
] | 13 | 2018-01-02T20:02:16.000Z | 2021-07-27T20:08:05.000Z | source/matrix/jit.alphablend/max.jit.alphablend.c | maevagrondin/max_externals | 9083d877c0091077f823aa42665209050f4ebfde | [
"MIT"
] | 9 | 2018-02-14T05:42:09.000Z | 2022-02-08T11:12:32.000Z | /*
Copyright 2001-2005 - Cycling '74
Joshua Kit Clayton jkc@cycling74.com
*/
#include "jit.common.h"
#include "max.jit.mop.h"
typedef struct _max_jit_alphablend
{
t_object ob;
void *obex;
} t_max_jit_alphablend;
t_jit_err jit_alphablend_init(void);
void *max_jit_alphablend_new(t_symbol *s, long argc, t_atom *argv);
void max_jit_alphablend_free(t_max_jit_alphablend *x);
void *max_jit_alphablend_class;
void ext_main(void *r)
{
void *p,*q;
jit_alphablend_init();
setup((t_messlist **)&max_jit_alphablend_class, (method)max_jit_alphablend_new, (method)max_jit_alphablend_free, (short)sizeof(t_max_jit_alphablend),
0L, A_GIMME, 0);
p = max_jit_classex_setup(calcoffset(t_max_jit_alphablend,obex));
q = jit_class_findbyname(gensym("jit_alphablend"));
max_jit_classex_mop_wrap(p,q,0);
max_jit_classex_standard_wrap(p,q,0);
addmess((method)max_jit_mop_assist, "assist", A_CANT,0);
}
void max_jit_alphablend_free(t_max_jit_alphablend *x)
{
max_jit_mop_free(x);
jit_object_free(max_jit_obex_jitob_get(x));
max_jit_obex_free(x);
}
void *max_jit_alphablend_new(t_symbol *s, long argc, t_atom *argv)
{
t_max_jit_alphablend *x;
void *o;
if (x=(t_max_jit_alphablend *)max_jit_obex_new(max_jit_alphablend_class,gensym("jit_alphablend"))) {
if (o=jit_object_new(gensym("jit_alphablend"))) {
max_jit_mop_setup_simple(x,o,argc,argv);
max_jit_attr_args(x,argc,argv);
} else {
jit_object_error((t_object *)x,"jit.alphablend: could not allocate object");
freeobject((t_object *)x);
x=NULL;
}
}
return (x);
}
| 25.8 | 150 | 0.75969 | [
"object"
] |
2ca128de3752b687515d28b7e6770dec1974a397 | 5,021 | h | C | Graphs and Searching/Project - Graph Applications (Searching, Dijkstra, Prim)/trabalho.h | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | Graphs and Searching/Project - Graph Applications (Searching, Dijkstra, Prim)/trabalho.h | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | Graphs and Searching/Project - Graph Applications (Searching, Dijkstra, Prim)/trabalho.h | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<time.h>
#include<unistd.h>
#include <float.h>
#define INFINITY 999999
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct _node { // Estruturas Do Grafo
int vertex;
struct _edge* head;
struct _edge* tail;
struct _node* up;
struct _node* bellow;
int size;
}node;
typedef struct _edge{
int vertex;
int peso;
struct _edge* prev;
struct _edge* next;
}edge;
typedef struct{
node* head;
node* tail;
int size;
}grafo;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
grafo* new_grafo(); //Aloca memoria para um grafo OK
void free_grafo(grafo *g);//desaloca memoria e apaga o grafo OK
void insert_vertex(grafo* g,int value); //funçoes de insersao de elementos OK
void insert_edge(grafo* g,int v,int a,int p); // OK
void new_edge(node* n,int v,int p);// OK
void new_vertex(grafo* g,int value);// OK
void remove_vertex(grafo*g,int v); //funçoes de remoçao de elementos OK
void remove_edge(grafo* g,int v,int a);// OK
void r_edge(node* n,edge* e);// OK
void r_vertex(grafo* g,node* n);// OK
bool exist_vertex(grafo* g,int v); //funçoes de verificaçao OK
bool exist_edge(node* v,int e); // OK
edge* search_edge(node* v,int e); //funçoes de busca OK
node* search_vertex(grafo* g,int v);// OK
int degree(grafo* g,int v); // função que retorna o grau de um vértice OK
void print_grafo(grafo* g); //imprimir o grafo OK
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Estruturas Do vector Utilizado como auxiliar
typedef struct _elem { // Cada nó possui armazena um valor e um ponteiro para o próximo.
int v;
int p;
int d;
int f;
int c;
node* end;
struct _elem* next;
struct _elem* prev;
}elem;
typedef struct { // aponta para o primeiro nó na lista
elem* head;
elem* tail;
int size;
}vector;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Alocação e desalocação de memória
vector* new_vector(); //OK
void free_vector(vector* v); //OK
//funçoes de inserçao no vector
void vector_push_front(vector* v,node* end,int vert,int p,int d,int f,int c); //OK
void vector_push_back(vector* v,node* end,int vert,int p,int d,int f,int c); //OK
// Funções de remoção de elementos
void vector_pop_back(vector* v); //OK
void vector_pop_front(vector* v); //OK
//funçao para verificar se o vector esta vazio
bool vector_empty(vector* v); //OK
//função para procurar o vertice no vetor
elem* vector_search(vector* v,int vert); //OK
//função que retorna o inicio ou o fim do vector
elem* vector_head(vector* v); //OK
elem* vector_tail(vector* v);
// busca um elemento marcado em branco no vetor auxiliar
int vector_white_search(vector* v); //OK
// Impressão do valores no vetor
void vector_print_dfs(vector* v); //OK
void vector_print_bfs(vector* v); //OK
void vector_print_prim(vector* v); //OK
void vector_print_d(vector* v); //OK
// funçao que extrai o minimo //OK
elem* extract_min(vector* v); //OK
// funçao para verificar se o vertice existe no vetor
bool exist_vector(vector* v,int i); //OK
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Função de busca em largura
void breadth_first_search(grafo* g, int v); //OK
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//funçao para busca em profundidade
void depth_first_search(grafo *g); //OK
void dfs(vector* aux,int*f,int v); //OK
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//funçao para imprimir matriz de adjacencias
int busca_indice(grafo* g,int vert); //OK
void matriz(grafo* g); //OK
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//funçao que verifica se o grafo é conexo
bool grafo_connected(grafo* g); //OK
//funçao que construi a arvore geradora minima
void prim(grafo* g, int v); //OK
// constroi a arvore de caminho minimo de dijkstra
void dijkstra(grafo* g,int v); //OK
| 36.384058 | 140 | 0.488349 | [
"vector"
] |
2ca50412526b5e6b1c9bac1ffb5a70c1d678e977 | 724 | h | C | knearest.h | hatstand/symmetrical-octo-fiesta | 8a1ed099f2598e330c60d3e85448431f4bb2c117 | [
"MIT"
] | 5 | 2017-08-26T23:59:04.000Z | 2020-06-08T19:28:10.000Z | knearest.h | hatstand/symmetrical-octo-fiesta | 8a1ed099f2598e330c60d3e85448431f4bb2c117 | [
"MIT"
] | 1 | 2017-05-16T11:22:22.000Z | 2017-06-14T12:39:32.000Z | knearest.h | hatstand/symmetrical-octo-fiesta | 8a1ed099f2598e330c60d3e85448431f4bb2c117 | [
"MIT"
] | 1 | 2019-12-30T14:00:33.000Z | 2019-12-30T14:00:33.000Z | #ifndef KNEAREST_H
#define KNEAREST_H
#include <functional>
#include <memory>
#include "opencv2/ml/ml.hpp"
class KNearest {
public:
KNearest(std::function<char(const cv::Mat&)> recognise_callback = nullptr);
void Learn(const cv::Mat& image, char c);
void Train();
// Returns the closest match to an actual tile.
char Recognise(const cv::Mat& image) const;
void Save(const std::string& path);
bool Load(const std::string& path);
bool LoadFromString(const std::string& model);
private:
cv::Mat PrepareSample(const cv::Mat& image) const;
cv::Mat samples_;
cv::Mat responses_;
cv::Ptr<cv::ml::KNearest> model_;
std::function<char(const cv::Mat&)> recognise_callback_;
};
#endif // KNEAREST_H
| 23.354839 | 77 | 0.705801 | [
"model"
] |
2ca53574f3752a926fdd62949a2ba6da1e8400d7 | 2,031 | h | C | cplusplus/level3_multi_model/2_official/scenetextrecognition/src/AscendBase/src/Base/CommandParser/CommandParser.h | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | null | null | null | cplusplus/level3_multi_model/2_official/scenetextrecognition/src/AscendBase/src/Base/CommandParser/CommandParser.h | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | null | null | null | cplusplus/level3_multi_model/2_official/scenetextrecognition/src/AscendBase/src/Base/CommandParser/CommandParser.h | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020.Huawei Technologies Co., Ltd. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMMAND_PARSER_H
#define COMMAND_PARSER_H
#include <string>
#include <map>
#include <vector>
// Command parser class
class CommandParser {
public:
CommandParser();
// Construct a new Command Parser object according to the argument
CommandParser(int &argc, const char **argv);
~CommandParser() {};
// Add options into the map
void add_option(const std::string &option, const std::string &defaults = "", const std::string &message = "");
// Parse the input arguments
void ParseArgs(int &argc, const char **argv);
// Get the option string value from parser
const std::string &GetStringOption(const std::string &option);
// Get the int value by option
const int GetIntOption(const std::string &option);
const uint32_t GetUint32Option(const std::string &option);
// Get the int value by option
const float GetFloatOption(const std::string &option);
// Get the double option
const double GetDoubleOption(const std::string &option);
// Get the bool option
const bool GetBoolOption(const std::string &option);
private:
std::map<std::string, std::pair<std::string, std::string>> commands_;
// Show the usage of app, then exit
void ShowUsage();
bool IsInteger(std::string &str);
bool IsDecimal(std::string &str);
};
#endif /* COMMANDPARSER_H */
| 37.611111 | 115 | 0.689808 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.