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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e2ae034d2f4b395ffe30a67b4ed2b201b8e8a62c | 857 | h | C | sel4-camkes-proj/kernel/include/arch/riscv/arch/kernel/thread.h | mssabr01/Dissertation-Work | 355366ed658c6d18f83d6751bf66a7f83786e22d | [
"Apache-2.0"
] | null | null | null | sel4-camkes-proj/kernel/include/arch/riscv/arch/kernel/thread.h | mssabr01/Dissertation-Work | 355366ed658c6d18f83d6751bf66a7f83786e22d | [
"Apache-2.0"
] | null | null | null | sel4-camkes-proj/kernel/include/arch/riscv/arch/kernel/thread.h | mssabr01/Dissertation-Work | 355366ed658c6d18f83d6751bf66a7f83786e22d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(DATA61_GPL)
*/
/*
*
* Copyright 2016, 2017 Hesham Almatary, Data61/CSIRO <hesham.almatary@data61.csiro.au>
* Copyright 2015, 2016 Hesham Almatary <heshamelmatary@gmail.com>
*/
#ifndef __ARCH_KERNEL_THREAD_H
#define __ARCH_KERNEL_THREAD_H
#include <object.h>
void Arch_switchToThread(tcb_t *tcb);
void Arch_switchToIdleThread(void);
void Arch_configureIdleThread(tcb_t *tcb);
void Arch_activateIdleThread(tcb_t *tcb);
static inline bool_t CONST
Arch_getSanitiseRegisterInfo(tcb_t *thread)
{
return 0;
}
#endif
| 23.805556 | 87 | 0.765461 | [
"object"
] |
e2aff980a1848d321c2344bd118fb8dcec4692c2 | 17,685 | c | C | zircon/system/dev/board/x86/acpi-dev/dev-ec.c | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | zircon/system/dev/board/x86/acpi-dev/dev-ec.c | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | zircon/system/dev/board/x86/acpi-dev/dev-ec.c | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "dev.h"
#include <hw/inout.h>
#include <ddk/debug.h>
#include <ddk/driver.h>
#include <zircon/syscalls.h>
#include <zircon/types.h>
#include <threads.h>
#include "errors.h"
#define xprintf(fmt...) zxlogf(SPEW, fmt)
/* EC commands */
#define EC_CMD_READ 0x80
#define EC_CMD_WRITE 0x81
#define EC_CMD_QUERY 0x84
/* EC status register bits */
#define EC_SC_SCI_EVT (1 << 5)
#define EC_SC_IBF (1 << 1)
#define EC_SC_OBF (1 << 0)
/* Thread signals */
#define IRQ_RECEIVED ZX_EVENT_SIGNALED
#define EC_THREAD_SHUTDOWN ZX_USER_SIGNAL_0
#define EC_THREAD_SHUTDOWN_DONE ZX_USER_SIGNAL_1
typedef struct acpi_ec_device {
zx_device_t* zxdev;
ACPI_HANDLE acpi_handle;
// PIO addresses for EC device
uint16_t cmd_port;
uint16_t data_port;
// GPE for EC events
ACPI_HANDLE gpe_block;
UINT32 gpe;
// thread for processing events from the EC
thrd_t evt_thread;
zx_handle_t interrupt_event;
bool gpe_setup : 1;
bool thread_setup : 1;
bool ec_space_setup : 1;
} acpi_ec_device_t;
static ACPI_STATUS get_ec_handle(ACPI_HANDLE, UINT32, void*, void**);
static ACPI_STATUS get_ec_gpe_info(ACPI_HANDLE, ACPI_HANDLE*, UINT32*);
static ACPI_STATUS get_ec_ports(ACPI_HANDLE, uint16_t*, uint16_t*);
static ACPI_STATUS ec_space_setup_handler(ACPI_HANDLE Region, UINT32 Function,
void* HandlerContext, void** ReturnContext);
static ACPI_STATUS ec_space_request_handler(UINT32 Function, ACPI_PHYSICAL_ADDRESS Address,
UINT32 BitWidth, UINT64* Value,
void* HandlerContext, void* RegionContext);
static zx_status_t wait_for_interrupt(acpi_ec_device_t* dev);
static zx_status_t execute_read_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t* val);
static zx_status_t execute_write_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t val);
static zx_status_t execute_query_op(acpi_ec_device_t* dev, uint8_t* val);
// Execute the EC_CMD_READ operation. Requires the ACPI global lock be held.
static zx_status_t execute_read_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t* val) {
// Issue EC command
outp(dev->cmd_port, EC_CMD_READ);
// Wait for EC to read the command so we can write the address
while (inp(dev->cmd_port) & EC_SC_IBF) {
zx_status_t status = wait_for_interrupt(dev);
if (status != ZX_OK) {
return status;
}
}
// Specify the address
outp(dev->data_port, addr);
// Wait for EC to read the address and write a response
while ((inp(dev->cmd_port) & (EC_SC_OBF | EC_SC_IBF)) != EC_SC_OBF) {
zx_status_t status = wait_for_interrupt(dev);
if (status != ZX_OK) {
return status;
}
}
// Read the response
*val = inp(dev->data_port);
return ZX_OK;
}
// Execute the EC_CMD_WRITE operation. Requires the ACPI global lock be held.
static zx_status_t execute_write_op(acpi_ec_device_t* dev, uint8_t addr, uint8_t val) {
// Issue EC command
outp(dev->cmd_port, EC_CMD_WRITE);
// Wait for EC to read the command so we can write the address
while (inp(dev->cmd_port) & EC_SC_IBF) {
zx_status_t status = wait_for_interrupt(dev);
if (status != ZX_OK) {
return status;
}
}
// Specify the address
outp(dev->data_port, addr);
// Wait for EC to read the address
while (inp(dev->cmd_port) & EC_SC_IBF) {
zx_status_t status = wait_for_interrupt(dev);
if (status != ZX_OK) {
return status;
}
}
// Write the data
outp(dev->data_port, val);
// Wait for EC to read the data
while (inp(dev->cmd_port) & EC_SC_IBF) {
zx_status_t status = wait_for_interrupt(dev);
if (status != ZX_OK) {
return status;
}
}
return ZX_OK;
}
// Execute the EC_CMD_QUERY operation. Requires the ACPI global lock be held.
static zx_status_t execute_query_op(acpi_ec_device_t* dev, uint8_t* event) {
// Query EC command
outp(dev->cmd_port, EC_CMD_QUERY);
// Wait for EC to respond
while ((inp(dev->cmd_port) & (EC_SC_OBF | EC_SC_IBF)) != EC_SC_OBF) {
zx_status_t status = wait_for_interrupt(dev);
if (status != ZX_OK) {
return status;
}
}
*event = inp(dev->data_port);
return ZX_OK;
}
static ACPI_STATUS ec_space_setup_handler(ACPI_HANDLE Region, UINT32 Function,
void* HandlerContext, void** ReturnContext) {
acpi_ec_device_t* dev = HandlerContext;
*ReturnContext = dev;
if (Function == ACPI_REGION_ACTIVATE) {
xprintf("acpi-ec: Setting up EC region\n");
return AE_OK;
} else if (Function == ACPI_REGION_DEACTIVATE) {
xprintf("acpi-ec: Tearing down EC region\n");
return AE_OK;
} else {
return AE_SUPPORT;
}
}
static ACPI_STATUS ec_space_request_handler(UINT32 Function, ACPI_PHYSICAL_ADDRESS Address,
UINT32 BitWidth, UINT64* Value,
void* HandlerContext, void* RegionContext) {
acpi_ec_device_t* dev = HandlerContext;
if (BitWidth != 8 && BitWidth != 16 && BitWidth != 32 && BitWidth != 64) {
return AE_BAD_PARAMETER;
}
if (Address > UINT8_MAX || Address - 1 + BitWidth / 8 > UINT8_MAX) {
return AE_BAD_PARAMETER;
}
UINT32 global_lock;
while (AcpiAcquireGlobalLock(0xFFFF, &global_lock) != AE_OK)
;
// NB: The processing of the read/write ops below will generate interrupts,
// which will unfortunately cause spurious wakeups on the event thread. One
// design that would avoid this is to have that thread responsible for
// processing these EC address space requests, but an attempt at an
// implementation failed due to apparent deadlocks against the Global Lock.
const size_t bytes = BitWidth / 8;
ACPI_STATUS status = AE_OK;
uint8_t* value_bytes = (uint8_t*)Value;
if (Function == ACPI_WRITE) {
for (size_t i = 0; i < bytes; ++i) {
zx_status_t zx_status = execute_write_op(dev, Address + i, value_bytes[i]);
if (zx_status != ZX_OK) {
status = AE_ERROR;
goto finish;
}
}
} else {
*Value = 0;
for (size_t i = 0; i < bytes; ++i) {
zx_status_t zx_status = execute_read_op(dev, Address + i, value_bytes + i);
if (zx_status != ZX_OK) {
status = AE_ERROR;
goto finish;
}
}
}
finish:
AcpiReleaseGlobalLock(global_lock);
return status;
}
static zx_status_t wait_for_interrupt(acpi_ec_device_t* dev) {
uint32_t pending;
zx_status_t status = zx_object_wait_one(dev->interrupt_event,
IRQ_RECEIVED | EC_THREAD_SHUTDOWN,
ZX_TIME_INFINITE,
&pending);
if (status != ZX_OK) {
printf("acpi-ec: thread wait failed: %d\n", status);
zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN_DONE);
return status;
}
if (pending & EC_THREAD_SHUTDOWN) {
zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN_DONE);
return ZX_ERR_STOP;
}
/* Clear interrupt */
zx_object_signal(dev->interrupt_event, IRQ_RECEIVED, 0);
return ZX_OK;
}
static int acpi_ec_thread(void* arg) {
acpi_ec_device_t* dev = arg;
UINT32 global_lock;
while (1) {
zx_status_t zx_status = wait_for_interrupt(dev);
if (zx_status != ZX_OK) {
goto exiting_without_lock;
}
while (AcpiAcquireGlobalLock(0xFFFF, &global_lock) != AE_OK)
;
uint8_t status;
bool processed_evt = false;
while ((status = inp(dev->cmd_port)) & EC_SC_SCI_EVT) {
uint8_t event_code;
zx_status_t zx_status = execute_query_op(dev, &event_code);
if (zx_status != ZX_OK) {
goto exiting_with_lock;
}
if (event_code != 0) {
char method[5] = {0};
snprintf(method, sizeof(method), "_Q%02x", event_code);
xprintf("acpi-ec: Invoking method %s\n", method);
AcpiEvaluateObject(dev->acpi_handle, method, NULL, NULL);
xprintf("acpi-ec: Invoked method %s\n", method);
} else {
xprintf("acpi-ec: Spurious event?\n");
}
processed_evt = true;
/* Clear interrupt before we check EVT again, to prevent a spurious
* interrupt later. There could be two sources of that spurious
* wakeup: Either we handled two events back-to-back, or we didn't
* wait for the OBF interrupt above. */
zx_object_signal(dev->interrupt_event, IRQ_RECEIVED, 0);
}
if (!processed_evt) {
xprintf("acpi-ec: Spurious wakeup, no evt: %#x\n", status);
}
AcpiReleaseGlobalLock(global_lock);
}
exiting_with_lock:
AcpiReleaseGlobalLock(global_lock);
exiting_without_lock:
xprintf("acpi-ec: thread terminated\n");
return 0;
}
static uint32_t raw_ec_event_gpe_handler(ACPI_HANDLE gpe_dev, uint32_t gpe_num, void* ctx) {
acpi_ec_device_t* dev = ctx;
zx_object_signal(dev->interrupt_event, 0, IRQ_RECEIVED);
return ACPI_REENABLE_GPE;
}
static ACPI_STATUS get_ec_handle(
ACPI_HANDLE object,
UINT32 nesting_level,
void* context,
void** ret) {
*(ACPI_HANDLE*)context = object;
return AE_OK;
}
static ACPI_STATUS get_ec_gpe_info(
ACPI_HANDLE ec_handle, ACPI_HANDLE* gpe_block, UINT32* gpe) {
ACPI_BUFFER buffer = {
.Length = ACPI_ALLOCATE_BUFFER,
.Pointer = NULL,
};
ACPI_STATUS status = AcpiEvaluateObject(
ec_handle, (char*)"_GPE", NULL, &buffer);
if (status != AE_OK) {
return status;
}
/* According to section 12.11 of ACPI v6.1, a _GPE object on this device
* evaluates to either an integer specifying bit in the GPEx_STS blocks
* to use, or a package specifying which GPE block and which bit inside
* that block to use. */
ACPI_OBJECT* gpe_obj = buffer.Pointer;
if (gpe_obj->Type == ACPI_TYPE_INTEGER) {
*gpe_block = NULL;
*gpe = gpe_obj->Integer.Value;
} else if (gpe_obj->Type == ACPI_TYPE_PACKAGE) {
if (gpe_obj->Package.Count != 2) {
goto bailout;
}
ACPI_OBJECT* block_obj = &gpe_obj->Package.Elements[0];
ACPI_OBJECT* gpe_num_obj = &gpe_obj->Package.Elements[1];
if (block_obj->Type != ACPI_TYPE_LOCAL_REFERENCE) {
goto bailout;
}
if (gpe_num_obj->Type != ACPI_TYPE_INTEGER) {
goto bailout;
}
*gpe_block = block_obj->Reference.Handle;
*gpe = gpe_num_obj->Integer.Value;
} else {
goto bailout;
}
ACPI_FREE(buffer.Pointer);
return AE_OK;
bailout:
xprintf("Failed to intepret EC GPE number");
ACPI_FREE(buffer.Pointer);
return AE_BAD_DATA;
}
struct ec_ports_callback_ctx {
uint16_t* data_port;
uint16_t* cmd_port;
unsigned int resource_num;
};
static ACPI_STATUS get_ec_ports_callback(
ACPI_RESOURCE* Resource, void* Context) {
struct ec_ports_callback_ctx* ctx = Context;
if (Resource->Type == ACPI_RESOURCE_TYPE_END_TAG) {
return AE_OK;
}
/* The spec says there will be at most 3 resources */
if (ctx->resource_num >= 3) {
return AE_BAD_DATA;
}
/* The third resource only exists on HW-Reduced platforms, which we don't
* support at the moment. */
if (ctx->resource_num == 2) {
xprintf("RESOURCE TYPE %d\n", Resource->Type);
return AE_NOT_IMPLEMENTED;
}
/* The two resources we're expecting are both address regions. First the
* data one, then the command one. We assume they're single IO ports. */
if (Resource->Type != ACPI_RESOURCE_TYPE_IO) {
return AE_SUPPORT;
}
if (Resource->Data.Io.Maximum != Resource->Data.Io.Minimum) {
return AE_SUPPORT;
}
uint16_t port = Resource->Data.Io.Minimum;
if (ctx->resource_num == 0) {
*ctx->data_port = port;
} else {
*ctx->cmd_port = port;
}
ctx->resource_num++;
return AE_OK;
}
static ACPI_STATUS get_ec_ports(
ACPI_HANDLE ec_handle, uint16_t* data_port, uint16_t* cmd_port) {
struct ec_ports_callback_ctx ctx = {
.data_port = data_port,
.cmd_port = cmd_port,
.resource_num = 0,
};
return AcpiWalkResources(ec_handle, (char*)"_CRS", get_ec_ports_callback, &ctx);
}
static void acpi_ec_release(void* ctx) {
acpi_ec_device_t* dev = ctx;
if (dev->ec_space_setup) {
AcpiRemoveAddressSpaceHandler(ACPI_ROOT_OBJECT, ACPI_ADR_SPACE_EC, ec_space_request_handler);
}
if (dev->gpe_setup) {
AcpiDisableGpe(dev->gpe_block, dev->gpe);
AcpiRemoveGpeHandler(dev->gpe_block, dev->gpe, raw_ec_event_gpe_handler);
}
if (dev->interrupt_event != ZX_HANDLE_INVALID) {
if (dev->thread_setup) {
/* Shutdown the EC thread */
zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN);
zx_object_wait_one(dev->interrupt_event, EC_THREAD_SHUTDOWN_DONE, ZX_TIME_INFINITE, NULL);
thrd_join(dev->evt_thread, NULL);
}
zx_handle_close(dev->interrupt_event);
}
free(dev);
}
static zx_status_t acpi_ec_suspend(void* ctx, uint32_t flags) {
acpi_ec_device_t* dev = ctx;
if (flags != DEVICE_SUSPEND_FLAG_MEXEC) {
return ZX_ERR_NOT_SUPPORTED;
}
AcpiRemoveAddressSpaceHandler(ACPI_ROOT_OBJECT, ACPI_ADR_SPACE_EC, ec_space_request_handler);
dev->ec_space_setup = false;
AcpiDisableGpe(dev->gpe_block, dev->gpe);
AcpiRemoveGpeHandler(dev->gpe_block, dev->gpe, raw_ec_event_gpe_handler);
dev->gpe_setup = false;
zx_object_signal(dev->interrupt_event, 0, EC_THREAD_SHUTDOWN);
zx_object_wait_one(dev->interrupt_event, EC_THREAD_SHUTDOWN_DONE, ZX_TIME_INFINITE, NULL);
thrd_join(dev->evt_thread, NULL);
zx_handle_close(dev->interrupt_event);
dev->interrupt_event = ZX_HANDLE_INVALID;
return ZX_OK;
}
static zx_protocol_device_t acpi_ec_device_proto = {
.version = DEVICE_OPS_VERSION,
.release = acpi_ec_release,
.suspend = acpi_ec_suspend,
};
zx_status_t ec_init(zx_device_t* parent, ACPI_HANDLE acpi_handle) {
xprintf("acpi-ec: init\n");
acpi_ec_device_t* dev = calloc(1, sizeof(acpi_ec_device_t));
if (!dev) {
return ZX_ERR_NO_MEMORY;
}
dev->acpi_handle = acpi_handle;
zx_status_t err = zx_event_create(0, &dev->interrupt_event);
if (err != ZX_OK) {
xprintf("acpi-ec: Failed to create event: %d\n", err);
acpi_ec_release(dev);
return err;
}
ACPI_STATUS status = get_ec_gpe_info(acpi_handle, &dev->gpe_block, &dev->gpe);
if (status != AE_OK) {
xprintf("acpi-ec: Failed to decode GPE info: %d\n", status);
goto acpi_error;
}
status = get_ec_ports(
acpi_handle, &dev->data_port, &dev->cmd_port);
if (status != AE_OK) {
xprintf("acpi-ec: Failed to decode comm info: %d\n", status);
goto acpi_error;
}
/* Setup GPE handling */
status = AcpiInstallGpeHandler(
dev->gpe_block, dev->gpe, ACPI_GPE_EDGE_TRIGGERED,
raw_ec_event_gpe_handler, dev);
if (status != AE_OK) {
xprintf("acpi-ec: Failed to install GPE %d: %x\n", dev->gpe, status);
goto acpi_error;
}
status = AcpiEnableGpe(dev->gpe_block, dev->gpe);
if (status != AE_OK) {
xprintf("acpi-ec: Failed to enable GPE %d: %x\n", dev->gpe, status);
AcpiRemoveGpeHandler(dev->gpe_block, dev->gpe, raw_ec_event_gpe_handler);
goto acpi_error;
}
dev->gpe_setup = true;
/* TODO(teisenbe): This thread should ideally be at a high priority, since
it takes the ACPI global lock which is shared with SMM. */
int ret = thrd_create_with_name(&dev->evt_thread, acpi_ec_thread, dev, "acpi-ec-evt");
if (ret != thrd_success) {
xprintf("acpi-ec: Failed to create thread\n");
acpi_ec_release(dev);
return ZX_ERR_INTERNAL;
}
dev->thread_setup = true;
status = AcpiInstallAddressSpaceHandler(ACPI_ROOT_OBJECT, ACPI_ADR_SPACE_EC,
ec_space_request_handler,
ec_space_setup_handler,
dev);
if (status != AE_OK) {
xprintf("acpi-ec: Failed to install ec space handler\n");
acpi_ec_release(dev);
return acpi_to_zx_status(status);
}
dev->ec_space_setup = true;
device_add_args_t args = {
.version = DEVICE_ADD_ARGS_VERSION,
.name = "acpi-ec",
.ctx = dev,
.ops = &acpi_ec_device_proto,
.proto_id = ZX_PROTOCOL_MISC,
};
status = device_add(parent, &args, &dev->zxdev);
if (status != ZX_OK) {
xprintf("acpi-ec: could not add device! err=%d\n", status);
acpi_ec_release(dev);
return status;
}
printf("acpi-ec: initialized\n");
return ZX_OK;
acpi_error:
acpi_ec_release(dev);
return acpi_to_zx_status(status);
}
| 31.750449 | 102 | 0.6311 | [
"object"
] |
e2c9485e006b3b1ff1cf9d8b99c9cb836c12c4cf | 727 | h | C | src/al_graphic/include/HwAbsFBObject.h | imalimin/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 83 | 2020-11-13T01:35:13.000Z | 2022-03-25T02:12:13.000Z | src/al_graphic/include/HwAbsFBObject.h | mohsinnaqvi110/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 3 | 2020-03-23T07:28:29.000Z | 2020-09-11T17:16:48.000Z | src/al_graphic/include/HwAbsFBObject.h | lmylr/hwvc | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 32 | 2020-11-09T04:20:35.000Z | 2022-03-22T04:11:45.000Z | /*
* Copyright (c) 2018-present, lmyooyo@gmail.com.
*
* This source code is licensed under the GPL license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef HWVC_ANDROID_HWABSFBOBJECT_H
#define HWVC_ANDROID_HWABSFBOBJECT_H
#include "Object.h"
#include "Size.h"
#include "AlBuffer.h"
class HwAbsTexture;
class HwAbsFBObject : public Object {
public:
HwAbsFBObject();
virtual ~HwAbsFBObject();
void bindTex(HwAbsTexture *tex);
void unbindTex();
void bind();
void unbind();
virtual bool read(uint8_t *pixels);
virtual bool read(AlBuffer *pixels);
private:
uint32_t fbo = 0;
HwAbsTexture *tex = nullptr;
};
#endif //HWVC_ANDROID_HWABSFBOBJECT_H
| 17.309524 | 65 | 0.711142 | [
"object"
] |
e2d1881e9a5b6404c3cdfcd81c6ef1b6e3b2149e | 608 | h | C | lab_06/src/include/Matrix.h | bmstu-ics7/analysis-of-algorithms | 9d1dd85cba6d137b671cb137084db9a6ae4f8e39 | [
"MIT"
] | 2 | 2020-06-08T18:50:45.000Z | 2021-02-27T11:21:03.000Z | lab_06/src/include/Matrix.h | bmstu-ics7/analysis-of-algorithms | 9d1dd85cba6d137b671cb137084db9a6ae4f8e39 | [
"MIT"
] | null | null | null | lab_06/src/include/Matrix.h | bmstu-ics7/analysis-of-algorithms | 9d1dd85cba6d137b671cb137084db9a6ae4f8e39 | [
"MIT"
] | null | null | null | #ifndef __MATRIX_H
#define __MATRIX_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
template <typename T>
class Matrix
{
public:
Matrix(size_t size);
Matrix(size_t size, T el);
Matrix(const std::string& filename);
size_t size();
size_t size() const;
std::vector< T >& operator[](size_t index);
const std::vector< T >& operator[](size_t index) const;
private:
std::vector< std::vector< T > > data;
};
template <typename T>
std::ostream& operator<< (std::ostream& output, const Matrix<T>& matrix);
#include "Matrix.hpp"
#endif // __MATRIX_H
| 18.424242 | 73 | 0.669408 | [
"vector"
] |
e2dd41059862f06d3df8c1ae1c393b1656025190 | 1,477 | h | C | src/mockdata/Names.h | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | src/mockdata/Names.h | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | src/mockdata/Names.h | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2014 Mario Alviano, Carmine Dodaro, Francesco Ricca and
* Pierfrancesco Veltri.
*
* 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: Names.h
* Author: cesco
*
* Created on 19 aprile 2014, 16.06
*/
#ifndef NAMES_H
#define NAMES_H
#include <string>
#include <vector>
namespace DLV2{ namespace MOCK{
class Names {
public:
static unsigned addPredicateName( std::string );
static std::string getPredicateName( unsigned );
static unsigned addStringConstant( std::string );
static std::string getStringConstant( unsigned );
static unsigned addIntegerConstant( int );
static int getIntegerConstant( unsigned );
private:
Names() { }
static std::vector<std::string> predicateNames;
static std::vector<std::string> stringConstants;
static std::vector<int> integerConstants;
};
};};
#endif /* NAMES_H */
| 26.375 | 76 | 0.672309 | [
"vector"
] |
53829375a041dd351dc96a5002b187bbce0a97dd | 4,562 | h | C | Direct2DNet/Direct2DNet/ID2D1PathGeometry1.h | SansyHuman/Direct2DNet | 345d981a07fd8cbdf7cf7e6ca9d7b493439dbd17 | [
"MIT"
] | null | null | null | Direct2DNet/Direct2DNet/ID2D1PathGeometry1.h | SansyHuman/Direct2DNet | 345d981a07fd8cbdf7cf7e6ca9d7b493439dbd17 | [
"MIT"
] | null | null | null | Direct2DNet/Direct2DNet/ID2D1PathGeometry1.h | SansyHuman/Direct2DNet | 345d981a07fd8cbdf7cf7e6ca9d7b493439dbd17 | [
"MIT"
] | null | null | null | #pragma once
#include "IDirect2DObject.h"
#include "D2DNetHeaders.h"
#include "D2DSettings.h"
#include "ID2D1PathGeometry.h"
using namespace System::Runtime::InteropServices;
using namespace System::Runtime::CompilerServices;
namespace D2DNet
{
namespace Direct2DNet
{
ref class ID2D1Factory1;
// Done.
/// <summary>
/// The ID2D1PathGeometry1 interface adds functionality to ID2D1PathGeometry. In
/// particular, it provides the path geometry-specific
/// ComputePointAndSegmentAtLength method.
/// </summary>
[System::Runtime::InteropServices::GuidAttribute("62baa2d2-ab54-41b7-b872-787e0106a421")]
public ref class ID2D1PathGeometry1 : Direct2DNet::ID2D1PathGeometry
{
internal:
ID2D1PathGeometry1() : Direct2DNet::ID2D1PathGeometry() {}
ID2D1PathGeometry1(Direct2DNet::ID2D1Factory1 ^factory);
public:
/// <summary>
/// Computes the point that exists at a given distance along the path geometry along with the
/// index of the segment the point is on and the directional vector at that point.
/// </summary>
/// <param name="length">The distance to walk along the path.</param>
/// <param name="startSegment">The index of the segment at which to begin walking.
/// This index is global to the entire path, not just a particular figure.</param>
/// <param name="worldTransform">The transform to apply to the path prior to walking.
/// The default value is the identity matrix.</param>
/// <param name="flatteningTolerance">The maximum error allowed when constructing a polygonal
/// approximation of the geometry. No point in the polygonal representation will diverge from
/// the original geometry by more than the flattening tolerance. Smaller values produce more
/// accurate results but cause slower execution.
/// The default value is 0.25.</param>
/// <returns>
/// (HRESULT, <see cref="Direct2DNet::D2D1_POINT_DESCRIPTION"/>) tuple.
/// If this method succeeds, HRESULT is S_OK. Otherwise, HRESULT is an error code.
/// <see cref="Direct2DNet::D2D1_POINT_DESCRIPTION"/> describes a point along a path.
/// </returns>
System::ValueTuple<HRESULT, Direct2DNet::D2D1_POINT_DESCRIPTION> ComputePointAndSegmentAtLength(
float length,
unsigned int startSegment,
[OptionalAttribute] System::Nullable<Direct2DNet::D2D1_MATRIX_3X2_F> worldTransform,
[OptionalAttribute] System::Nullable<float> flatteningTolerance
);
/// <summary>
/// Computes the point that exists at a given distance along the path geometry along with the
/// index of the segment the point is on and the directional vector at that point.
/// </summary>
/// <param name="pointDescription">Description of a point along a path(out parameter).</param>
/// <param name="length">The distance to walk along the path.</param>
/// <param name="startSegment">The index of the segment at which to begin walking.
/// This index is global to the entire path, not just a particular figure.</param>
/// <param name="worldTransform">The transform to apply to the path prior to walking.
/// The default value is the identity matrix.</param>
/// <param name="flatteningTolerance">The maximum error allowed when constructing a polygonal
/// approximation of the geometry. No point in the polygonal representation will diverge from
/// the original geometry by more than the flattening tolerance. Smaller values produce more
/// accurate results but cause slower execution.
/// The default value is 0.25.</param>
/// <returns>
/// If this method succeeds, returns S_OK. Otherwise, returns an error code.
/// </returns>
HRESULT ComputePointAndSegmentAtLength(
[OutAttribute] Direct2DNet::D2D1_POINT_DESCRIPTION %pointDescription,
float length,
unsigned int startSegment,
[OptionalAttribute] System::Nullable<Direct2DNet::D2D1_MATRIX_3X2_F> worldTransform,
[OptionalAttribute] System::Nullable<float> flatteningTolerance
);
};
}
} | 53.046512 | 108 | 0.640947 | [
"geometry",
"vector",
"transform"
] |
538f7e4dea00a436f768498b6ceb2e44cd13f07b | 662 | h | C | 0783-Minimum-Distance-Between-BST-Nodes/cpp_0783/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | 12 | 2020-03-18T14:36:23.000Z | 2021-12-19T02:24:33.000Z | 0783-Minimum-Distance-Between-BST-Nodes/cpp_0783/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | 0783-Minimum-Distance-Between-BST-Nodes/cpp_0783/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | //
// Created by ooooo on 2020/1/5.
//
#ifndef CPP_0783_SOLUTION1_H
#define CPP_0783_SOLUTION1_H
#include "TreeNode.h"
#include <vector>
class Solution {
public:
void dfs(TreeNode *node, vector<int> &vec) {
if (!node) return;
dfs(node->left, vec);
vec.push_back(node->val);
dfs(node->right, vec);
}
int minDiffInBST(TreeNode *root) {
if (!root) return 0;
vector<int> vec;
dfs(root, vec);
int min = INT_MAX;
for (int i = 0; i < vec.size() - 1; ++i) {
min = std::min(min, vec[i + 1] - vec[i]);
}
return min;
}
};
#endif //CPP_0783_SOLUTION1_H
| 20.060606 | 53 | 0.545317 | [
"vector"
] |
5391c82262ca811f150d8de5c2c365c664942556 | 3,841 | h | C | 3rd/xulrunner-sdk/include/nsIStringStream.h | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | 3rd/xulrunner-sdk/include/nsIStringStream.h | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | 3rd/xulrunner-sdk/include/nsIStringStream.h | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/xpcom/io/nsIStringStream.idl
*/
#ifndef __gen_nsIStringStream_h__
#define __gen_nsIStringStream_h__
#ifndef __gen_nsIInputStream_h__
#include "nsIInputStream.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIStringInputStream */
#define NS_ISTRINGINPUTSTREAM_IID_STR "450cd2d4-f0fd-424d-b365-b1251f80fd53"
#define NS_ISTRINGINPUTSTREAM_IID \
{0x450cd2d4, 0xf0fd, 0x424d, \
{ 0xb3, 0x65, 0xb1, 0x25, 0x1f, 0x80, 0xfd, 0x53 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIStringInputStream : public nsIInputStream {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISTRINGINPUTSTREAM_IID)
/* void setData (in string data, in long dataLen); */
NS_SCRIPTABLE NS_IMETHOD SetData(const char * data, PRInt32 dataLen) = 0;
/* [noscript] void adoptData (in charPtr data, in long dataLen); */
NS_IMETHOD AdoptData(char *data, PRInt32 dataLen) = 0;
/* [noscript] void shareData (in string data, in long dataLen); */
NS_IMETHOD ShareData(const char * data, PRInt32 dataLen) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIStringInputStream, NS_ISTRINGINPUTSTREAM_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISTRINGINPUTSTREAM \
NS_SCRIPTABLE NS_IMETHOD SetData(const char * data, PRInt32 dataLen); \
NS_IMETHOD AdoptData(char *data, PRInt32 dataLen); \
NS_IMETHOD ShareData(const char * data, PRInt32 dataLen);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISTRINGINPUTSTREAM(_to) \
NS_SCRIPTABLE NS_IMETHOD SetData(const char * data, PRInt32 dataLen) { return _to SetData(data, dataLen); } \
NS_IMETHOD AdoptData(char *data, PRInt32 dataLen) { return _to AdoptData(data, dataLen); } \
NS_IMETHOD ShareData(const char * data, PRInt32 dataLen) { return _to ShareData(data, dataLen); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISTRINGINPUTSTREAM(_to) \
NS_SCRIPTABLE NS_IMETHOD SetData(const char * data, PRInt32 dataLen) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetData(data, dataLen); } \
NS_IMETHOD AdoptData(char *data, PRInt32 dataLen) { return !_to ? NS_ERROR_NULL_POINTER : _to->AdoptData(data, dataLen); } \
NS_IMETHOD ShareData(const char * data, PRInt32 dataLen) { return !_to ? NS_ERROR_NULL_POINTER : _to->ShareData(data, dataLen); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsStringInputStream : public nsIStringInputStream
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTRINGINPUTSTREAM
nsStringInputStream();
private:
~nsStringInputStream();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsStringInputStream, nsIStringInputStream)
nsStringInputStream::nsStringInputStream()
{
/* member initializers and constructor code */
}
nsStringInputStream::~nsStringInputStream()
{
/* destructor code */
}
/* void setData (in string data, in long dataLen); */
NS_IMETHODIMP nsStringInputStream::SetData(const char * data, PRInt32 dataLen)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [noscript] void adoptData (in charPtr data, in long dataLen); */
NS_IMETHODIMP nsStringInputStream::AdoptData(char *data, PRInt32 dataLen)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [noscript] void shareData (in string data, in long dataLen); */
NS_IMETHODIMP nsStringInputStream::ShareData(const char * data, PRInt32 dataLen)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIStringStream_h__ */
| 33.112069 | 143 | 0.76152 | [
"object"
] |
5399e856881ee6b260d656b98e6080d14874aed6 | 3,695 | h | C | WickedEngine/wiServer.h | belleCrazySnail/WickedEngine | b339f8405ef3257f41ca1329042396c6c77f8f31 | [
"Zlib",
"MIT"
] | 1 | 2019-09-10T21:28:54.000Z | 2019-09-10T21:28:54.000Z | WickedEngine/wiServer.h | belleCrazySnail/WickedEngine | b339f8405ef3257f41ca1329042396c6c77f8f31 | [
"Zlib",
"MIT"
] | null | null | null | WickedEngine/wiServer.h | belleCrazySnail/WickedEngine | b339f8405ef3257f41ca1329042396c6c77f8f31 | [
"Zlib",
"MIT"
] | null | null | null | #ifndef SERVER_H
#define SERVER_H
#include "wiNetwork.h"
#include <ctime>
#include <map>
class wiServer : public wiNetwork
{
#ifndef WINSTORE_SUPPORT
private:
std::map<SOCKET, std::string> clients;
public:
wiServer(const std::string& newName = "SERVER", const std::string& ipaddress = "0.0.0.0", int port = PORT);
~wiServer(void);
bool active(){return !clients.empty();}
bool sendText(const std::string& text, int packettype, const std::string& clientName = "", int clientID = -1);
template <typename T>
bool sendData(const T& value){
if(clients.begin()==clients.end())
return false;
Network::sendData(PACKET_TYPE_OTHER,clients.begin()->first);
return Network::sendData(value,clients.begin()->first);
}
template <typename T>
bool receiveData(T& value){
if(clients.begin()==clients.end())
return false;
return Network::receiveData(value,clients.begin()->first);
}
bool changeName(const std::string& newName);
bool sendMessage(const std::string& text, const std::string& clientName = "", int clientID = -1);
bool ListenOnPort(int portno, const char* ipaddress);
SOCKET CreateAccepter();
template<typename T>
void Poll(T& data)
{
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(s, &readfds);
SOCKET max_sd = s;
for (std::map<SOCKET,string>::iterator it = clients.begin(); it != clients.end(); ++it) {
if(it->first>0)
FD_SET( it->first, &readfds );
if(it->first>max_sd)
max_sd=it->first;
}
timeval time=timeval();
time.tv_sec=0;
time.tv_usec=1;
if ((select( (int)max_sd + 1, &readfds , NULL , NULL , &time) < 0) && (errno!=EINTR))
{
wiBackLog::post("select error");
}
//If something happened on the master socket , then its an incoming connection
if (FD_ISSET(s, &readfds))
{
SOCKET new_socket = CreateAccepter();
if(new_socket != SOCKET_ERROR){
if(wiNetwork::sendText(name,new_socket)){
stringstream ss("");
ss<<"Name sent, client ["<<new_socket<<"] connected";
wiBackLog::post(ss.str().c_str());
ss.str("");
ss<<"Unnamed_client_"<<new_socket;
clients.insert(pair<SOCKET,string>(new_socket,ss.str()));
}
else
wiBackLog::post("Welcome message could NOT be sent, client ignored");
}
}
//else its some IO operation on some other socket :)
for (std::map<SOCKET,string>::iterator it = clients.begin(); it != clients.end(); ) {
if (FD_ISSET( it->first , &readfds))
{
int command;
bool receiveSuccess = wiNetwork::receiveData(command,it->first);
if(!receiveSuccess){
wiBackLog::post("Client disconnected.");
closesocket(it->first);
clients.erase(it++);
continue;
}
else{
switch(command){
case PACKET_TYPE_CHANGENAME:
{
string text;
if(receiveText(text,it->first)){
stringstream ss("");
ss<<"Client "<<it->second<<" now registered as "<<text;
wiBackLog::post(ss.str().c_str());
it->second=text;
}
break;
}
case PACKET_TYPE_TEXTMESSAGE:
{
string text;
if(receiveText(text,it->first)){
stringstream ss("");
ss<<it->second<<": "<<text;
wiBackLog::post(ss.str().c_str());
}
break;
}
case PACKET_TYPE_OTHER:
{
wiNetwork::receiveData(data,it->first);
break;
}
default:
break;
}
}
}
++it;
}
}
std::vector<std::string> listClients();
#else
public:
wiServer(const std::string& newName = "SERVER", const std::string& ipaddress = "0.0.0.0", int port = PORT) {}
template<typename T>
void Poll(T& data) {}
#endif // WINSTORE_SUPPORT
};
#endif | 22.393939 | 111 | 0.623004 | [
"vector"
] |
539f98c9d96e675d35be7554c4b086a02ffdcd15 | 6,509 | h | C | aws-cpp-sdk-mediaconnect/include/aws/mediaconnect/model/RemoveFlowVpcInterfaceResult.h | orinem/aws-sdk-cpp | f38413cc1f278689ef14e9ebdd74a489a48776be | [
"Apache-2.0"
] | 1 | 2020-07-16T19:02:58.000Z | 2020-07-16T19:02:58.000Z | aws-cpp-sdk-mediaconnect/include/aws/mediaconnect/model/RemoveFlowVpcInterfaceResult.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-mediaconnect/include/aws/mediaconnect/model/RemoveFlowVpcInterfaceResult.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/mediaconnect/MediaConnect_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace MediaConnect
{
namespace Model
{
class AWS_MEDIACONNECT_API RemoveFlowVpcInterfaceResult
{
public:
RemoveFlowVpcInterfaceResult();
RemoveFlowVpcInterfaceResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
RemoveFlowVpcInterfaceResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* The ARN of the flow that is associated with the VPC interface you removed.
*/
inline const Aws::String& GetFlowArn() const{ return m_flowArn; }
/**
* The ARN of the flow that is associated with the VPC interface you removed.
*/
inline void SetFlowArn(const Aws::String& value) { m_flowArn = value; }
/**
* The ARN of the flow that is associated with the VPC interface you removed.
*/
inline void SetFlowArn(Aws::String&& value) { m_flowArn = std::move(value); }
/**
* The ARN of the flow that is associated with the VPC interface you removed.
*/
inline void SetFlowArn(const char* value) { m_flowArn.assign(value); }
/**
* The ARN of the flow that is associated with the VPC interface you removed.
*/
inline RemoveFlowVpcInterfaceResult& WithFlowArn(const Aws::String& value) { SetFlowArn(value); return *this;}
/**
* The ARN of the flow that is associated with the VPC interface you removed.
*/
inline RemoveFlowVpcInterfaceResult& WithFlowArn(Aws::String&& value) { SetFlowArn(std::move(value)); return *this;}
/**
* The ARN of the flow that is associated with the VPC interface you removed.
*/
inline RemoveFlowVpcInterfaceResult& WithFlowArn(const char* value) { SetFlowArn(value); return *this;}
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline const Aws::Vector<Aws::String>& GetNonDeletedNetworkInterfaceIds() const{ return m_nonDeletedNetworkInterfaceIds; }
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline void SetNonDeletedNetworkInterfaceIds(const Aws::Vector<Aws::String>& value) { m_nonDeletedNetworkInterfaceIds = value; }
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline void SetNonDeletedNetworkInterfaceIds(Aws::Vector<Aws::String>&& value) { m_nonDeletedNetworkInterfaceIds = std::move(value); }
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline RemoveFlowVpcInterfaceResult& WithNonDeletedNetworkInterfaceIds(const Aws::Vector<Aws::String>& value) { SetNonDeletedNetworkInterfaceIds(value); return *this;}
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline RemoveFlowVpcInterfaceResult& WithNonDeletedNetworkInterfaceIds(Aws::Vector<Aws::String>&& value) { SetNonDeletedNetworkInterfaceIds(std::move(value)); return *this;}
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline RemoveFlowVpcInterfaceResult& AddNonDeletedNetworkInterfaceIds(const Aws::String& value) { m_nonDeletedNetworkInterfaceIds.push_back(value); return *this; }
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline RemoveFlowVpcInterfaceResult& AddNonDeletedNetworkInterfaceIds(Aws::String&& value) { m_nonDeletedNetworkInterfaceIds.push_back(std::move(value)); return *this; }
/**
* IDs of network interfaces associated with the removed VPC interface that Media
* Connect was unable to remove.
*/
inline RemoveFlowVpcInterfaceResult& AddNonDeletedNetworkInterfaceIds(const char* value) { m_nonDeletedNetworkInterfaceIds.push_back(value); return *this; }
/**
* The name of the VPC interface that was removed.
*/
inline const Aws::String& GetVpcInterfaceName() const{ return m_vpcInterfaceName; }
/**
* The name of the VPC interface that was removed.
*/
inline void SetVpcInterfaceName(const Aws::String& value) { m_vpcInterfaceName = value; }
/**
* The name of the VPC interface that was removed.
*/
inline void SetVpcInterfaceName(Aws::String&& value) { m_vpcInterfaceName = std::move(value); }
/**
* The name of the VPC interface that was removed.
*/
inline void SetVpcInterfaceName(const char* value) { m_vpcInterfaceName.assign(value); }
/**
* The name of the VPC interface that was removed.
*/
inline RemoveFlowVpcInterfaceResult& WithVpcInterfaceName(const Aws::String& value) { SetVpcInterfaceName(value); return *this;}
/**
* The name of the VPC interface that was removed.
*/
inline RemoveFlowVpcInterfaceResult& WithVpcInterfaceName(Aws::String&& value) { SetVpcInterfaceName(std::move(value)); return *this;}
/**
* The name of the VPC interface that was removed.
*/
inline RemoveFlowVpcInterfaceResult& WithVpcInterfaceName(const char* value) { SetVpcInterfaceName(value); return *this;}
private:
Aws::String m_flowArn;
Aws::Vector<Aws::String> m_nonDeletedNetworkInterfaceIds;
Aws::String m_vpcInterfaceName;
};
} // namespace Model
} // namespace MediaConnect
} // namespace Aws
| 36.567416 | 177 | 0.716854 | [
"vector",
"model"
] |
53ab2ad24292571bbcbc94cf06bf93a77de5fa6c | 1,176 | h | C | Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Vehicle/WheelPhysicsControl.h | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 103 | 2020-03-10T04:21:50.000Z | 2022-03-29T13:26:57.000Z | Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Vehicle/WheelPhysicsControl.h | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 12 | 2020-04-11T11:36:01.000Z | 2021-12-09T11:35:56.000Z | Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Vehicle/WheelPhysicsControl.h | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 8 | 2020-11-21T07:47:12.000Z | 2022-03-25T13:41:05.000Z | // Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#pragma once
#include "WheelPhysicsControl.generated.h"
USTRUCT(BlueprintType)
struct CARLA_API FWheelPhysicsControl
{
GENERATED_BODY()
UPROPERTY(Category = "Wheel Tire Friction", EditAnywhere, BlueprintReadWrite)
float TireFriction = 3.5f;
UPROPERTY(Category = "Wheel Damping Rate", EditAnywhere, BlueprintReadWrite)
float DampingRate = 1.0f;
UPROPERTY(Category = "Wheel Max Steer Angle", EditAnywhere, BlueprintReadWrite)
float MaxSteerAngle = 70.0f;
UPROPERTY(Category = "Wheel Shape Radius", EditAnywhere, BlueprintReadWrite)
float Radius = 30.0f;
UPROPERTY(Category = "Wheel Max Brake Torque (Nm)", EditAnywhere, BlueprintReadWrite)
float MaxBrakeTorque = 1500.0f;
UPROPERTY(Category = "Wheel Max Handbrake Torque (Nm)", EditAnywhere, BlueprintReadWrite)
float MaxHandBrakeTorque = 3000.0f;
UPROPERTY(Category = "Wheel Position", EditAnywhere, BlueprintReadWrite)
FVector Position = FVector::ZeroVector;
};
| 31.783784 | 91 | 0.759354 | [
"shape"
] |
53adb018102a6ec9dca7ad529df54b857bcddcfa | 23,965 | c | C | src/other/ext/tk/macosx/tkMacOSXMenubutton.c | dservin/brlcad | 34b72d3efd24ac2c84abbccf9452323231751cd1 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 83 | 2021-03-10T05:54:52.000Z | 2022-03-31T16:33:46.000Z | src/other/ext/tk/macosx/tkMacOSXMenubutton.c | dservin/brlcad | 34b72d3efd24ac2c84abbccf9452323231751cd1 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 13 | 2021-06-24T17:07:48.000Z | 2022-03-31T15:31:33.000Z | src/other/ext/tk/macosx/tkMacOSXMenubutton.c | dservin/brlcad | 34b72d3efd24ac2c84abbccf9452323231751cd1 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 54 | 2021-03-10T07:57:06.000Z | 2022-03-28T23:20:37.000Z | /*
* tkMacOSXMenubutton.c --
*
* This file implements the Macintosh specific portion of the menubutton
* widget.
*
* Copyright (c) 1996 by Sun Microsystems, Inc.
* Copyright 2001, Apple Computer, Inc.
* Copyright (c) 2006-2007 Daniel A. Steffen <das@users.sourceforge.net>
* Copyright 2007 Revar Desmera.
* Copyright 2015 Kevin Walzer/WordTech Communications LLC.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
*/
#include "tkMacOSXPrivate.h"
#include "tkMenu.h"
#include "tkMenubutton.h"
#include "tkMacOSXFont.h"
#include "tkMacOSXDebug.h"
#define FIRST_DRAW 2
#define ACTIVE 4
typedef struct {
Tk_3DBorder border;
int relief;
GC gc;
int hasImageOrBitmap;
} DrawParams;
/*
* Declaration of Mac specific button structure.
*/
typedef struct MacMenuButton {
TkMenuButton info; /* Generic button info. */
int flags;
ThemeButtonKind btnkind;
HIThemeButtonDrawInfo drawinfo;
HIThemeButtonDrawInfo lastdrawinfo;
DrawParams drawParams;
} MacMenuButton;
/*
* Forward declarations for static functions defined later in this file:
*/
static void MenuButtonEventProc(ClientData clientData,
XEvent *eventPtr);
static void MenuButtonBackgroundDrawCB(MacMenuButton *ptr,
SInt16 depth, Boolean isColorDev);
static void MenuButtonContentDrawCB(ThemeButtonKind kind,
const HIThemeButtonDrawInfo *info,
MacMenuButton *ptr, SInt16 depth,
Boolean isColorDev);
static void MenuButtonEventProc(ClientData clientData,
XEvent *eventPtr);
static void TkMacOSXComputeMenuButtonParams(TkMenuButton *butPtr,
ThemeButtonKind *btnkind,
HIThemeButtonDrawInfo *drawinfo);
static void TkMacOSXComputeMenuButtonDrawParams(
TkMenuButton *butPtr, DrawParams *dpPtr);
static void TkMacOSXDrawMenuButton(MacMenuButton *butPtr, GC gc,
Pixmap pixmap);
static void DrawMenuButtonImageAndText(TkMenuButton *butPtr);
/*
* The structure below defines menubutton class behavior by means of
* procedures that can be invoked from generic window code.
*/
Tk_ClassProcs tkpMenubuttonClass = {
sizeof(Tk_ClassProcs), /* size */
TkMenuButtonWorldChanged, /* worldChangedProc */
};
/*
* We use Apple's Pop-Up Button widget to represent the Tk Menubutton.
* However, we do not use the NSPopUpButton class for this control. Instead we
* render the Pop-Up Button using the HITheme library. This imposes some
* constraints on what can be done. The HITheme renderer allows only specific
* dimensions for the button.
*
* The HITheme library allows drawing a Pop-Up Button with an arbitrary bounds
* rectangle. However the button is always drawn as a rounded box which is 22
* pixels high. If the bounds rectangle is less than 22 pixels high, the
* button is drawn at the top of the rectangle and the bottom of the button is
* clipped away. So we set a minimum height of 22 pixels for a Menubutton. If
* the bounds rectangle is more than 22 pixels high, then the button is drawn
* centered vertically in the bounds rectangle.
*
* The content rectangle of the button is inset by 14 pixels on the left and 28
* pixels on the right. The rightmost part of the button contains the blue
* double-arrow symbol which is 28 pixels wide.
*
* To maintain compatibility with code that runs on multiple operating systems,
* the width and height of the content rectangle includes the borderWidth, the
* highlightWidth and the padX and padY dimensions of the Menubutton. However,
* to be consistent with the standard Apple appearance, the content is always
* be drawn at the left side of the content rectangle. All of the excess space
* appears on the right side of the content, and the anchor property is
* ignored. The easiest way to comply with Apple's Human Interface Guidelines
* would be to set bd = highlightthickness = padx = 0 and to specify an
* explicit width for the button. Apple also recommends using the same width
* for all Pop-Up Buttons in a given window.
*/
#define LEFT_INSET 8
#define RIGHT_INSET 28
#define MIN_HEIGHT 22
/*
*----------------------------------------------------------------------
*
* TkpCreateMenuButton --
*
* Allocate a new TkMenuButton structure.
*
* Results:
* Returns a newly allocated TkMenuButton structure.
*
* Side effects:
* Registers an event handler for the widget.
*
*----------------------------------------------------------------------
*/
TkMenuButton *
TkpCreateMenuButton(
Tk_Window tkwin)
{
MacMenuButton *mbPtr = (MacMenuButton *) ckalloc(sizeof(MacMenuButton));
Tk_CreateEventHandler(tkwin, ActivateMask, MenuButtonEventProc, mbPtr);
mbPtr->flags = FIRST_DRAW;
mbPtr->btnkind = kThemePopupButton;
bzero(&mbPtr->drawinfo, sizeof(mbPtr->drawinfo));
bzero(&mbPtr->lastdrawinfo, sizeof(mbPtr->lastdrawinfo));
return (TkMenuButton *) mbPtr;
}
/*
*----------------------------------------------------------------------
*
* TkpDisplayMenuButton --
*
* This procedure is invoked to display a menubutton widget.
*
* Results:
* None.
*
* Side effects:
* Commands are output to X to display the menubutton in its current mode.
*
*----------------------------------------------------------------------
*/
void
TkpDisplayMenuButton(
ClientData clientData) /* Information about widget. */
{
MacMenuButton *mbPtr = clientData;
TkMenuButton *butPtr = clientData;
Tk_Window tkwin = butPtr->tkwin;
Pixmap pixmap;
DrawParams *dpPtr = &mbPtr->drawParams;
butPtr->flags &= ~REDRAW_PENDING;
if ((butPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
return;
}
pixmap = (Pixmap) Tk_WindowId(tkwin);
TkMacOSXComputeMenuButtonDrawParams(butPtr, dpPtr);
/*
* Set up clipping region. Make sure the we are using the port for this
* button, or we will set the wrong window's clip.
*/
TkMacOSXSetUpClippingRgn(pixmap);
/*
* Draw the native portion of the buttons.
*/
TkMacOSXDrawMenuButton(mbPtr, dpPtr->gc, pixmap);
/*
* Draw highlight border, if needed.
*/
if (butPtr->highlightWidth < 3) {
if (butPtr->flags & GOT_FOCUS) {
GC gc = Tk_GCForColor(butPtr->highlightColorPtr, pixmap);
TkMacOSXDrawSolidBorder(tkwin, gc, 0, butPtr->highlightWidth);
}
}
}
/*
*----------------------------------------------------------------------
*
* TkpDestroyMenuButton --
*
* Free data structures associated with the menubutton control. This is a
* no-op on the Mac.
*
* Results:
* None.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
void
TkpDestroyMenuButton(
TkMenuButton *mbPtr)
{
}
/*
*----------------------------------------------------------------------
*
* TkpComputeMenuButtonGeometry --
*
* After changes in a menu button's text or bitmap, this procedure
* recomputes the menu button's geometry and passes this information
* along to the geometry manager for the window.
*
* Results:
* None.
*
* Side effects:
* The menu button's window may change size.
*
*----------------------------------------------------------------------
*/
void
TkpComputeMenuButtonGeometry(butPtr)
register TkMenuButton *butPtr; /* Widget record for menu button. */
{
int width, height, avgWidth, haveImage = 0, haveText = 0;
int txtWidth, txtHeight;
Tk_FontMetrics fm;
int highlightWidth = butPtr->highlightWidth > 0 ? butPtr->highlightWidth : 0;
/*
* First compute the size of the contents of the button.
*/
width = 0;
height = 0;
txtWidth = 0;
txtHeight = 0;
avgWidth = 0;
if (butPtr->image != NULL) {
Tk_SizeOfImage(butPtr->image, &width, &height);
haveImage = 1;
} else if (butPtr->bitmap != None) {
Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
haveImage = 1;
}
if (butPtr->text && strlen(butPtr->text) > 0) {
haveText = 1;
Tk_FreeTextLayout(butPtr->textLayout);
butPtr->textLayout = Tk_ComputeTextLayout(butPtr->tkfont,
butPtr->text, -1, butPtr->wrapLength,
butPtr->justify, 0, &butPtr->textWidth, &butPtr->textHeight);
txtWidth = butPtr->textWidth;
txtHeight = butPtr->textHeight;
avgWidth = Tk_TextWidth(butPtr->tkfont, "0", 1);
Tk_GetFontMetrics(butPtr->tkfont, &fm);
}
/*
* If the button is compound (ie, it shows both an image and text), the new
* geometry is a combination of the image and text geometry. We only honor
* the compound bit if the button has both text and an image, because
* otherwise it is not really a compound button.
*/
if (haveImage && haveText) {
switch ((enum compound) butPtr->compound) {
case COMPOUND_TOP:
case COMPOUND_BOTTOM:
/*
* Image is above or below text
*/
height += txtHeight + butPtr->padY;
width = (width > txtWidth ? width : txtWidth);
break;
case COMPOUND_LEFT:
case COMPOUND_RIGHT:
/*
* Image is left or right of text
*/
width += txtWidth + butPtr->padX;
height = (height > txtHeight ? height : txtHeight);
break;
case COMPOUND_CENTER:
/*
* Image and text are superimposed
*/
width = (width > txtWidth ? width : txtWidth);
height = (height > txtHeight ? height : txtHeight);
break;
case COMPOUND_NONE:
break;
}
if (butPtr->width > 0) {
width = butPtr->width;
}
if (butPtr->height > 0) {
height = butPtr->height;
}
} else {
if (haveImage) { /* Image only */
if (butPtr->width > 0) {
width = butPtr->width;
}
if (butPtr->height > 0) {
height = butPtr->height;
}
} else { /* Text only */
width = txtWidth;
height = txtHeight;
if (butPtr->width > 0) {
width = butPtr->width * avgWidth + 2*butPtr->padX;
}
if (butPtr->height > 0) {
height = butPtr->height * fm.linespace + 2*butPtr->padY;
}
}
}
butPtr->inset = highlightWidth + butPtr->borderWidth;
width += LEFT_INSET + RIGHT_INSET + 2*butPtr->inset;
height += 2*butPtr->inset;
height = height < MIN_HEIGHT ? MIN_HEIGHT : height;
Tk_GeometryRequest(butPtr->tkwin, width, height);
Tk_SetInternalBorder(butPtr->tkwin, butPtr->inset);
}
/*
*----------------------------------------------------------------------
*
* DrawMenuButtonImageAndText --
*
* Draws the image and text associated witha button or label.
*
* Results:
* None.
*
* Side effects:
* The image and text are drawn.
*
*----------------------------------------------------------------------
*/
void
DrawMenuButtonImageAndText(
TkMenuButton *butPtr)
{
MacMenuButton *mbPtr = (MacMenuButton *) butPtr;
Tk_Window tkwin = butPtr->tkwin;
Pixmap pixmap;
int haveImage = 0, haveText = 0;
int imageWidth = 0, imageHeight = 0;
int imageXOffset = 0, imageYOffset = 0;
int textXOffset = 0, textYOffset = 0;
int width = 0, height = 0;
int fullWidth = 0, fullHeight = 0;
if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
return;
}
DrawParams *dpPtr = &mbPtr->drawParams;
pixmap = (Pixmap) Tk_WindowId(tkwin);
if (butPtr->image != None) {
Tk_SizeOfImage(butPtr->image, &width, &height);
haveImage = 1;
} else if (butPtr->bitmap != None) {
Tk_SizeOfBitmap(butPtr->display, butPtr->bitmap, &width, &height);
haveImage = 1;
}
imageWidth = width;
imageHeight = height;
haveText = (butPtr->textWidth != 0 && butPtr->textHeight != 0);
if (butPtr->compound != COMPOUND_NONE && haveImage && haveText) {
int x = 0, y = 0;
textXOffset = 0;
textYOffset = 0;
fullWidth = 0;
fullHeight = 0;
switch ((enum compound) butPtr->compound) {
case COMPOUND_TOP:
case COMPOUND_BOTTOM:
/*
* Image is above or below text.
*/
if (butPtr->compound == COMPOUND_TOP) {
textYOffset = height + butPtr->padY;
} else {
imageYOffset = butPtr->textHeight + butPtr->padY;
}
fullHeight = height + butPtr->textHeight + butPtr->padY;
fullWidth = (width > butPtr->textWidth ?
width : butPtr->textWidth);
textXOffset = (fullWidth - butPtr->textWidth)/2;
imageXOffset = (fullWidth - width)/2;
break;
case COMPOUND_LEFT:
case COMPOUND_RIGHT:
/*
* Image is left or right of text
*/
if (butPtr->compound == COMPOUND_LEFT) {
textXOffset = width + butPtr->padX - 2;
} else {
imageXOffset = butPtr->textWidth + butPtr->padX;
}
fullWidth = butPtr->textWidth + butPtr->padX + width;
fullHeight = (height > butPtr->textHeight ? height :
butPtr->textHeight);
textYOffset = (fullHeight - butPtr->textHeight)/2;
imageYOffset = (fullHeight - height)/2;
break;
case COMPOUND_CENTER:
/*
* Image and text are superimposed
*/
fullWidth = (width > butPtr->textWidth ? width : butPtr->textWidth);
fullHeight = (height > butPtr->textHeight ? height :
butPtr->textHeight);
textXOffset = (fullWidth - butPtr->textWidth) / 2;
imageXOffset = (fullWidth - width) / 2;
textYOffset = (fullHeight - butPtr->textHeight) / 2;
imageYOffset = (fullHeight - height) / 2;
break;
case COMPOUND_NONE:
break;
}
TkComputeAnchor(butPtr->anchor, tkwin,
butPtr->padX + butPtr->inset, butPtr->padY + butPtr->inset,
fullWidth, fullHeight, &x, &y);
imageXOffset = LEFT_INSET;
imageYOffset += y;
textYOffset -= 1;
if (butPtr->image != NULL) {
Tk_RedrawImage(butPtr->image, 0, 0, width,
height, pixmap, imageXOffset, imageYOffset);
} else {
XSetClipOrigin(butPtr->display, dpPtr->gc,
imageXOffset, imageYOffset);
XCopyPlane(butPtr->display, butPtr->bitmap, pixmap, dpPtr->gc,
0, 0, (unsigned int) width, (unsigned int) height,
imageXOffset, imageYOffset, 1);
XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
}
Tk_DrawTextLayout(butPtr->display, pixmap,
dpPtr->gc, butPtr->textLayout,
x + textXOffset, y + textYOffset, 0, -1);
Tk_UnderlineTextLayout(butPtr->display, pixmap, dpPtr->gc,
butPtr->textLayout, x + textXOffset, y + textYOffset,
butPtr->underline);
} else {
int x, y;
if (haveImage) {
TkComputeAnchor(butPtr->anchor, tkwin,
butPtr->padX + butPtr->borderWidth,
butPtr->padY + butPtr->borderWidth,
width, height, &x, &y);
imageXOffset = LEFT_INSET;
imageYOffset += y;
if (butPtr->image != NULL) {
Tk_RedrawImage(butPtr->image, 0, 0, width, height,
pixmap, imageXOffset, imageYOffset);
} else {
XSetClipOrigin(butPtr->display, dpPtr->gc, x, y);
XCopyPlane(butPtr->display, butPtr->bitmap,
pixmap, dpPtr->gc,
0, 0, (unsigned int) width,
(unsigned int) height,
imageXOffset, imageYOffset, 1);
XSetClipOrigin(butPtr->display, dpPtr->gc, 0, 0);
}
} else {
textXOffset = LEFT_INSET;
TkComputeAnchor(butPtr->anchor, tkwin, butPtr->padX, butPtr->padY,
butPtr->textWidth, butPtr->textHeight, &x, &y);
Tk_DrawTextLayout(butPtr->display, pixmap, dpPtr->gc,
butPtr->textLayout, textXOffset, y, 0, -1);
y += butPtr->textHeight/2;
}
}
}
/*
*--------------------------------------------------------------
*
* TkMacOSXDrawMenuButton --
*
* This function draws the tk menubutton using Mac controls. In
* addition, this code may apply custom colors passed in the
* TkMenubutton.
*
* Results:
* None.
*
* Side effects:
* None.
*
*--------------------------------------------------------------
*/
static void
TkMacOSXDrawMenuButton(
MacMenuButton *mbPtr, /* Mac menubutton. */
GC gc, /* The GC we are drawing into - needed for the bevel
* button */
Pixmap pixmap) /* The pixmap we are drawing into - needed for the
* bevel button */
{
TkMenuButton *butPtr = (TkMenuButton *) mbPtr;
TkWindow *winPtr = (TkWindow *) butPtr->tkwin;
HIRect cntrRect;
TkMacOSXDrawingContext dc;
DrawParams *dpPtr = &mbPtr->drawParams;
int useNewerHITools = 1;
TkMacOSXComputeMenuButtonParams(butPtr, &mbPtr->btnkind, &mbPtr->drawinfo);
cntrRect = CGRectMake(winPtr->privatePtr->xOff, winPtr->privatePtr->yOff,
Tk_Width(butPtr->tkwin), Tk_Height(butPtr->tkwin));
if (useNewerHITools == 1) {
HIRect contHIRec;
static HIThemeButtonDrawInfo hiinfo;
MenuButtonBackgroundDrawCB(mbPtr, 32, true);
if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
return;
}
hiinfo.version = 0;
hiinfo.state = mbPtr->drawinfo.state;
hiinfo.kind = mbPtr->btnkind;
hiinfo.value = mbPtr->drawinfo.value;
hiinfo.adornment = mbPtr->drawinfo.adornment;
hiinfo.animation.time.current = CFAbsoluteTimeGetCurrent();
if (hiinfo.animation.time.start == 0) {
hiinfo.animation.time.start = hiinfo.animation.time.current;
}
/*
* To avoid menubuttons with white text on a white background, we
* always set the state to inactive in Dark Mode. It isn't perfect but
* it is usable. Using a ttk::menubutton would be a better choice,
* however.
*/
if (TkMacOSXInDarkMode(butPtr->tkwin)) {
hiinfo.state = kThemeStateInactive;
}
HIThemeDrawButton(&cntrRect, &hiinfo, dc.context,
kHIThemeOrientationNormal, &contHIRec);
TkMacOSXRestoreDrawingContext(&dc);
MenuButtonContentDrawCB(mbPtr->btnkind, &mbPtr->drawinfo,
mbPtr, 32, true);
} else {
if (!TkMacOSXSetupDrawingContext(pixmap, dpPtr->gc, 1, &dc)) {
return;
}
TkMacOSXRestoreDrawingContext(&dc);
}
mbPtr->lastdrawinfo = mbPtr->drawinfo;
}
/*
*--------------------------------------------------------------
*
* MenuButtonBackgroundDrawCB --
*
* This function draws the background that lies under checkboxes and
* radiobuttons.
*
* Results:
* None.
*
* Side effects:
* The background gets updated to the current color.
*
*--------------------------------------------------------------
*/
static void
MenuButtonBackgroundDrawCB (
MacMenuButton *ptr,
SInt16 depth,
Boolean isColorDev)
{
TkMenuButton* butPtr = (TkMenuButton *) ptr;
Tk_Window tkwin = butPtr->tkwin;
Pixmap pixmap;
if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
return;
}
pixmap = (Pixmap) Tk_WindowId(tkwin);
Tk_Fill3DRectangle(tkwin, pixmap, butPtr->normalBorder, 0, 0,
Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
}
/*
*--------------------------------------------------------------
*
* MenuButtonContentDrawCB --
*
* This function draws the label and image for the button.
*
* Results:
* None.
*
* Side effects:
* The content of the button gets updated.
*
*--------------------------------------------------------------
*/
static void
MenuButtonContentDrawCB (
ThemeButtonKind kind,
const HIThemeButtonDrawInfo *drawinfo,
MacMenuButton *ptr,
SInt16 depth,
Boolean isColorDev)
{
TkMenuButton *butPtr = (TkMenuButton *) ptr;
Tk_Window tkwin = butPtr->tkwin;
if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
return;
}
DrawMenuButtonImageAndText(butPtr);
}
/*
*--------------------------------------------------------------
*
* MenuButtonEventProc --
*
* This procedure is invoked by the Tk dispatcher for various events on
* buttons.
*
* Results:
* None.
*
* Side effects:
* When it gets exposed, it is redisplayed.
*
*--------------------------------------------------------------
*/
static void
MenuButtonEventProc(
ClientData clientData, /* Information about window. */
XEvent *eventPtr) /* Information about event. */
{
TkMenuButton *buttonPtr = clientData;
MacMenuButton *mbPtr = clientData;
if (eventPtr->type == ActivateNotify
|| eventPtr->type == DeactivateNotify) {
if ((buttonPtr->tkwin == NULL) || (!Tk_IsMapped(buttonPtr->tkwin))) {
return;
}
if (eventPtr->type == ActivateNotify) {
mbPtr->flags |= ACTIVE;
} else {
mbPtr->flags &= ~ACTIVE;
}
if ((buttonPtr->flags & REDRAW_PENDING) == 0) {
Tcl_DoWhenIdle(TkpDisplayMenuButton, (ClientData) buttonPtr);
buttonPtr->flags |= REDRAW_PENDING;
}
}
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXComputeMenuButtonParams --
*
* This procedure computes the various parameters used when creating a
* Carbon Appearance control. These are determined by the various Tk
* button parameters
*
* Results:
* None.
*
* Side effects:
* Sets the btnkind and drawinfo parameters
*
*----------------------------------------------------------------------
*/
static void
TkMacOSXComputeMenuButtonParams(
TkMenuButton *butPtr,
ThemeButtonKind *btnkind,
HIThemeButtonDrawInfo *drawinfo)
{
MacMenuButton *mbPtr = (MacMenuButton *) butPtr;
if (butPtr->image || butPtr->bitmap || butPtr->text) {
/* TODO: allow for Small and Mini menubuttons. */
*btnkind = kThemePopupButton;
} else { /* This should never happen. */
*btnkind = kThemeArrowButton;
}
drawinfo->value = kThemeButtonOff;
if ((mbPtr->flags & FIRST_DRAW) != 0) {
mbPtr->flags &= ~FIRST_DRAW;
if (Tk_MacOSXIsAppInFront()) {
mbPtr->flags |= ACTIVE;
}
}
drawinfo->state = kThemeStateInactive;
if ((mbPtr->flags & ACTIVE) == 0) {
if (butPtr->state == STATE_DISABLED) {
drawinfo->state = kThemeStateUnavailableInactive;
} else {
drawinfo->state = kThemeStateInactive;
}
} else if (butPtr->state == STATE_DISABLED) {
drawinfo->state = kThemeStateUnavailable;
} else {
drawinfo->state = kThemeStateActive;
}
drawinfo->adornment = kThemeAdornmentNone;
if (butPtr->highlightWidth >= 3) {
if ((butPtr->flags & GOT_FOCUS)) {
drawinfo->adornment |= kThemeAdornmentFocus;
}
}
drawinfo->adornment |= kThemeAdornmentArrowDoubleArrow;
}
/*
*----------------------------------------------------------------------
*
* TkMacOSXComputeMenuButtonDrawParams --
*
* This procedure selects an appropriate drawing context for drawing a
* menubutton.
*
* Results:
* None.
*
* Side effects:
* Sets the button draw parameters.
*
*----------------------------------------------------------------------
*/
static void
TkMacOSXComputeMenuButtonDrawParams(
TkMenuButton *butPtr,
DrawParams *dpPtr)
{
dpPtr->hasImageOrBitmap =
((butPtr->image != NULL) || (butPtr->bitmap != None));
dpPtr->border = butPtr->normalBorder;
if ((butPtr->state == STATE_DISABLED) && (butPtr->disabledFg != NULL)) {
dpPtr->gc = butPtr->disabledGC;
} else if (butPtr->state == STATE_ACTIVE) {
dpPtr->gc = butPtr->activeTextGC;
dpPtr->border = butPtr->activeBorder;
} else {
dpPtr->gc = butPtr->normalTextGC;
}
}
/*
* Local Variables:
* mode: objc
* c-basic-offset: 4
* fill-column: 79
* coding: utf-8
* End:
*/
| 29.048485 | 81 | 0.596787 | [
"geometry",
"render"
] |
53b2d5553cd600d1103e63d58f890319081a2001 | 184 | h | C | src/line-counter/Include/Paths.h | michalovsky/LineCounter | dd41308707a4865b2c3f0d0f6a009dd631a932bc | [
"MIT"
] | 1 | 2021-06-14T09:35:41.000Z | 2021-06-14T09:35:41.000Z | src/line-counter/Include/Paths.h | michalovsky/line-counter | dd41308707a4865b2c3f0d0f6a009dd631a932bc | [
"MIT"
] | null | null | null | src/line-counter/Include/Paths.h | michalovsky/line-counter | dd41308707a4865b2c3f0d0f6a009dd631a932bc | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
namespace lineCounter
{
using Path = std::string;
using Paths = std::vector<Path>;
using FilePath = Path;
using FilePaths = Paths;
}
| 14.153846 | 32 | 0.722826 | [
"vector"
] |
53b3df420d27576d0e6bb6f4fefd14363096e521 | 1,973 | h | C | Raven.CppClient/IAttachmentsSessionOperationsBase.h | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 3 | 2019-04-24T02:34:53.000Z | 2019-08-01T08:22:26.000Z | Raven.CppClient/IAttachmentsSessionOperationsBase.h | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 2 | 2019-03-21T09:00:02.000Z | 2021-02-28T23:49:26.000Z | Raven.CppClient/IAttachmentsSessionOperationsBase.h | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 3 | 2019-03-04T11:58:54.000Z | 2021-03-01T00:25:49.000Z | #pragma once
#include "AttachmentName.h"
namespace ravendb::client::documents::session
{
class IAttachmentsSessionOperationsBase
{
public:
virtual ~IAttachmentsSessionOperationsBase() = 0;
virtual std::vector<documents::operations::attachments::AttachmentName> get_attachments_names(std::shared_ptr<void> entity) const = 0;
virtual void store_attachment(const std::string& document_id, const std::string& name, std::istream& stream,
const std::optional<std::string>& content_type = {}) = 0;
virtual void store_attachment(std::shared_ptr<void> entity, const std::string& name, std::istream& stream,
const std::optional<std::string>& content_type = {}) = 0;
virtual void delete_attachment(const std::string& document_id, const std::string& name) = 0;
virtual void delete_attachment(std::shared_ptr<void> entity, const std::string& name) = 0;
virtual void rename_attachment(const std::string& document_id, const std::string& name, const std::string& new_name) = 0;
virtual void rename_attachment(std::shared_ptr<void> entity, const std::string& name, const std::string& new_name) = 0;
virtual void copy_attachment(const std::string& source_document_id, const std::string& source_name,
const std::string& destination_document_id, const std::string& destination_name) = 0;
virtual void copy_attachment(std::shared_ptr<void> source_entity, const std::string& source_name,
std::shared_ptr<void> destination_entity, const std::string& destination_name) = 0;
virtual void move_attachment(const std::string& source_document_id, const std::string& source_name,
const std::string& destination_document_id, const std::string& destination_name) = 0;
virtual void move_attachment(std::shared_ptr<void> source_entity, const std::string& source_name,
std::shared_ptr<void> destination_entity, const std::string& destination_name) = 0;
};
inline IAttachmentsSessionOperationsBase::~IAttachmentsSessionOperationsBase() = default;
}
| 46.97619 | 136 | 0.767359 | [
"vector"
] |
53c926c3fc275c41de8c814f17145252f3347dce | 5,565 | h | C | src/render/Shader.h | Vishwas-Venkatachalapathy/travis-lab | cd6de78a7a6b9d515bb973f2824686679b9a3843 | [
"BSD-3-Clause"
] | 184 | 2015-01-12T10:40:50.000Z | 2022-03-23T20:27:15.000Z | src/render/Shader.h | Vishwas-Venkatachalapathy/travis-lab | cd6de78a7a6b9d515bb973f2824686679b9a3843 | [
"BSD-3-Clause"
] | 154 | 2015-01-14T13:16:39.000Z | 2022-01-11T16:53:42.000Z | src/render/Shader.h | Vishwas-Venkatachalapathy/travis-lab | cd6de78a7a6b9d515bb973f2824686679b9a3843 | [
"BSD-3-Clause"
] | 87 | 2015-01-12T04:36:55.000Z | 2022-03-16T06:54:28.000Z | // Copyright 2015, Christopher J. Foster and the other displaz contributors.
// Use of this code is governed by the BSD-style license found in LICENSE.txt
#ifndef SHADER_H_INCLUDED
#define SHADER_H_INCLUDED
#include <memory>
#include <QMap>
#include <QGLShader>
#include <QGLShaderProgram>
/// Representation of a shader "parameter" (uniform variable or attribute)
struct ShaderParam
{
enum Type {
Float,
Int,
Vec3
};
Type type; ///< Variable type
QByteArray name; ///< Name of the variable in the shader
QVariant defaultValue; ///< Default value
QMap<QString,QString> kvPairs; ///< name,value pairs with additional metadata
int ordering; ///< Ordering in source file
QString uiName() const
{
return kvPairs.value("uiname", name);
}
double getDouble(QString name, double defaultVal) const
{
if (!kvPairs.contains(name))
return defaultVal;
bool convOk = false;
double val = kvPairs[name].toDouble(&convOk);
if (!convOk)
return defaultVal;
return val;
}
int getInt(QString name, int defaultVal) const
{
if (!kvPairs.contains(name))
return defaultVal;
bool convOk = false;
double val = kvPairs[name].toInt(&convOk);
if (!convOk)
return defaultVal;
return val;
}
ShaderParam(Type type=Float, QByteArray name="",
QVariant defaultValue = QVariant())
: type(type), name(name), defaultValue(defaultValue), ordering(0) {}
};
inline bool operator==(const ShaderParam& p1, const ShaderParam& p2)
{
return p1.name == p2.name && p1.type == p2.type &&
p1.defaultValue == p2.defaultValue &&
p1.kvPairs == p2.kvPairs && p1.ordering == p2.ordering;
}
// Operator for ordering in QMap
inline bool operator<(const ShaderParam& p1, const ShaderParam& p2)
{
if (p1.name != p2.name)
return p1.name < p2.name;
return p1.type < p2.type;
}
/// Wrapper for QGLShader, with functionality added to parse
/// the list of uniform parameters.
class Shader
{
public:
Shader(QGLShader::ShaderType type)
: m_shader(type)
{ }
/// Return list of uniform shader parameters
const QList<ShaderParam>& uniforms() const
{
return m_uniforms;
}
/// Return original source code.
QByteArray sourceCode() const
{
return m_source;
}
/// Access to underlying shader
QGLShader* shader()
{
return &m_shader;
}
bool compileSourceCode(const QByteArray& src);
private:
QList<ShaderParam> m_uniforms;
QGLShader m_shader; ///< Underlying shader
QByteArray m_source; ///< Non-mangled source code
};
/// Wrapper around QGLShaderProgram providing parameter tweaking UI
///
/// When compiling a new shader, the shader source code is scanned for
/// annotations in the comments which indicate which uniform values should be
/// tweakable by the user. An appropriate UI editor widget is automatically
/// created for each such uniform value by a call to setupParameterUI().
///
class ShaderProgram : public QObject
{
Q_OBJECT
public:
ShaderProgram(QObject* parent = 0);
/// Access to the underlying shader program
QGLShaderProgram& shaderProgram() { return *m_shaderProgram; }
/// Set up UI for the shader
void setupParameterUI(QWidget* parentWidget);
/// Send current uniform values to the underlying OpenGL shader
void setUniforms();
/// Read shader source from given file and call setShader()
bool setShaderFromSourceFile(QString fileName);
/// Get shader source code
QByteArray shaderSource() const;
/// Return true if shader program is ready to use
bool isValid() const { return static_cast<bool>(m_shaderProgram); }
public slots:
/// Set, compile and link shader source.
///
/// Retain old shader if compilation or linking fails
///
/// The shader source should contain both vertex and fragment shaders,
/// separated inside #ifdef blocks using the macros VERTEX_SHADER and
/// FRAGMENT_SHADER, which will be defined as appropriate when
/// compiling the individual shader types.
bool setShader(QString src);
signals:
/// Emitted when the list of user-settable uniform parameters to this
/// shader change.
///
/// The listening object should take this as a hint to update the UI.
void paramsChanged();
/// Emitted when the shader source code is updated.
void shaderChanged();
/// Emitted when a value of one of the current parameters changes
///
/// Listeners should take this as a hint that the scene should be
/// updated.
void uniformValuesChanged();
private slots:
void setUniformValue(int value);
void setUniformValue(double value);
private:
void setupParameters();
double m_pointSize;
double m_exposure;
double m_contrast;
int m_selector;
typedef QMap<ShaderParam,QVariant> ParamMap;
ParamMap m_params;
std::unique_ptr<Shader> m_vertexShader;
std::unique_ptr<Shader> m_fragmentShader;
std::unique_ptr<QGLShaderProgram> m_shaderProgram;
};
#endif // SHADER_H_INCLUDED
| 28.984375 | 81 | 0.631447 | [
"object"
] |
53d2698c6b68dc9f90cb6af3fe384677c44eda60 | 3,716 | c | C | Role.c | twtyypmb/DawnOfTheCircle | d56c314c916b8b8e500566c67c24f1b264515fa3 | [
"libtiff",
"BSD-3-Clause"
] | null | null | null | Role.c | twtyypmb/DawnOfTheCircle | d56c314c916b8b8e500566c67c24f1b264515fa3 | [
"libtiff",
"BSD-3-Clause"
] | null | null | null | Role.c | twtyypmb/DawnOfTheCircle | d56c314c916b8b8e500566c67c24f1b264515fa3 | [
"libtiff",
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include "Role.h"
#include "CommonResource.h"
static void HandleEventCore(void* obj)
{
PRole _this = (PRole)obj;
GameCoreProcessInterface_HandleEvent(_this->living_thing_ptr);
}
static void UpdateDataCore(void* _this_obj)
{
PRole _this=(PRole)_this_obj;
GameCoreProcessInterface_UpdateData(_this->living_thing_ptr);
}
static void RenderCore(void* _this_obj)
{
PRole _this=(PRole)_this_obj;
GameCoreProcessInterface_Render(_this->living_thing_ptr);
}
PRole NewRole(void)
{
PRole temp=(PRole)malloc(sizeof(Role));
temp->living_thing_ptr=NewLivingThing(GetSDLEvnet);
temp->HandleEvent = HandleEventCore;
temp->UpdateData = UpdateDataCore;
temp->Render = RenderCore;
temp->living_thing_ptr->game_object_ptr->_position_ptr->X=10;
temp->living_thing_ptr->game_object_ptr->_position_ptr->Y=10;
int i,j,k,index,t,t_back;
i=j=k=index=t=t_back=0;
char buffer[200],word[10],frame1[10],frame2[10],frame3[10],frame4[10],frame5[10],frame6[10],frame7[10],frame8[10];
FILE* fp = fopen("resource/role/img.rol","r");
do
{
while( NULL != fgets(buffer,200,fp) && j<DIRECTION_ENUM_MAX )
{
index =0;
k=0;
if(sscanf(buffer,"%s %s %s %s %s %s %s %s",frame1,frame2,frame3,frame4,frame5,frame6,frame7,frame8) < 1)
{
continue;
}
DebugTools_PrintDebugInfo("%s %s %s %s %s %s %s %s",frame1,frame2,frame3,frame4,frame5,frame6,frame7,frame8);
temp->living_thing_ptr->Frames[IDLE][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame2),GetTotalSurface(),atoi(frame1));
temp->living_thing_ptr->Frames[IDLE][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame4),GetTotalSurface(),atoi(frame3));
temp->living_thing_ptr->Frames[IDLE][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame6),GetTotalSurface(),atoi(frame5));
temp->living_thing_ptr->Frames[IDLE][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame8),GetTotalSurface(),atoi(frame7));
DisPlayTexture(GetRenderer(),temp->living_thing_ptr->Frames[0][j][k-1]);
j++;
}
j=0;
while( NULL != fgets(buffer,200,fp) && j<DIRECTION_ENUM_MAX )
{
index =0;
k=0;
if(sscanf(buffer,"%s %s %s %s %s %s %s %s",frame1,frame2,frame3,frame4,frame5,frame6,frame7,frame8) < 1)
{
continue;
}
DebugTools_PrintDebugInfo("%s %s %s %s %s %s %s %s",frame1,frame2,frame3,frame4,frame5,frame6,frame7,frame8);
temp->living_thing_ptr->Frames[MOVING][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame2),GetTotalSurface(),atoi(frame1));
temp->living_thing_ptr->Frames[MOVING][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame4),GetTotalSurface(),atoi(frame3));
temp->living_thing_ptr->Frames[MOVING][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame6),GetTotalSurface(),atoi(frame5));
temp->living_thing_ptr->Frames[MOVING][j][k++] = GetTransparentTexture(GetTotalSurface(),atoi(frame8),GetTotalSurface(),atoi(frame7));
DisPlayTexture(GetRenderer(),temp->living_thing_ptr->Frames[MOVING][j][k-1]);
j++;
}
fclose(fp);
temp->living_thing_ptr->game_object_ptr->SwitchFrames(temp->living_thing_ptr->game_object_ptr,temp->living_thing_ptr->Frames[IDLE][UP],LIVING_THING_FRAME_MAX);
return temp;
}while(false);
fclose(fp);
FreeRole(temp);
return temp;
}
void FreeRole(PRole role)
{
FreeGameObject(role);
}
| 36.431373 | 167 | 0.651776 | [
"render"
] |
53d846cd11b08ae41d3126f208a569d5b4d6120f | 21,422 | h | C | external/pcl/include/pcl/StatusMonitor.h | AstrocatApp/AstrocatApp | 0b3b33861260ed495bfcbd4c8601ab82ad247d37 | [
"MIT"
] | 2 | 2021-03-12T08:36:37.000Z | 2021-04-05T19:34:08.000Z | external/pcl/include/pcl/StatusMonitor.h | OzerOzdemir/AstrocatApp | 8da06ab819bc71010daa921f7a2c214c200d1ad3 | [
"MIT"
] | 9 | 2021-02-08T08:58:33.000Z | 2021-10-07T05:16:07.000Z | external/pcl/include/pcl/StatusMonitor.h | OzerOzdemir/AstrocatApp | 8da06ab819bc71010daa921f7a2c214c200d1ad3 | [
"MIT"
] | 1 | 2021-02-05T06:40:16.000Z | 2021-02-05T06:40:16.000Z | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 2.4.7
// ----------------------------------------------------------------------------
// pcl/StatusMonitor.h - Released 2020-12-17T15:46:29Z
// ----------------------------------------------------------------------------
// This file is part of the PixInsight Class Library (PCL).
// PCL is a multiplatform C++ framework for development of PixInsight modules.
//
// Copyright (c) 2003-2020 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (https://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ----------------------------------------------------------------------------
#ifndef __PCL_StatusMonitor_h
#define __PCL_StatusMonitor_h
/// \file pcl/StatusMonitor.h
#include <pcl/Defs.h>
#include <pcl/Exception.h>
#include <pcl/String.h>
#include <pcl/Utility.h>
namespace pcl
{
class PCL_CLASS StatusMonitor;
// ----------------------------------------------------------------------------
/*!
* \class StatusCallback
* \brief Provides status monitoring callback functions.
*
* %StatusCallback is an abstract base class providing a set of pure virtual
* functions that must be reimplemented in derived classes. These virtual
* functions must provide feedback to the user as part of the <em>status
* monitoring</em> of a process.
*
* Status monitoring consists of a set of PCL classes and functions to provide
* feedback and progress information about ongoing processes. Each instance of
* a %StatusCallback subclass is directly managed by a <em>status monitor</em>
* object. A status monitor object is an instance of the StatusMonitor class.
*
* Status monitors provide a generalized mechanism to generate progress
* information while a process is running. A %StatusCallback subclass receives
* that progress information and provides feedback to the user, controlling the
* information provided, its format and its appearance.
*
* The best example of %StatusCallback subclass is the StandardStatus class.
* StandardStatus reimplements %StatusCallback's pure virtual functions to show
* processing progress information on the processing console of the current
* processing thread.
*
* \sa StatusMonitor, StandardStatus, SpinStatus, ProgressBarStatus,
* MuteStatus, Console, Thread
*/
class PCL_CLASS StatusCallback
{
public:
/*!
* Constructs a default %StatusCallback object.
*/
StatusCallback() = default;
/*!
* Copy constructor.
*/
StatusCallback( const StatusCallback& ) = default;
/*!
* Move constructor.
*/
StatusCallback( StatusCallback&& ) = default;
/*!
* Destroys this %StatusCallback instance.
*/
virtual ~StatusCallback()
{
}
/*!
* Copy assignment operator. Returns a reference to this object.
*/
StatusCallback& operator =( const StatusCallback& ) = default;
/*!
* Move assignment operator. Returns a reference to this object.
*/
StatusCallback& operator =( StatusCallback&& ) = default;
/*!
* This function is called by a status \a monitor object when a new
* monitored process is about to start.
*
* The progress <em>total count</em> can be obtained by calling
* StatusMonitor::Total() for the passed \a monitor object. Similarly, the
* <em>progress information</em> string is given by StatusMonitor::Info().
*
* This function must return zero if the process can continue. If this
* function returns a nonzero value, the new process is aborted by throwing
* a ProcessAborted exception.
*/
virtual int Initialized( const StatusMonitor& monitor ) const = 0;
/*!
* Function called by a status \a monitor object to signal an update of the
* progress count for the current process.
*
* The <em>progress count</em> can be obtained by calling
* StatusMonitor::Count() for the passed \a monitor object. Similarly, the
* <em>total count</em> is given by StatusMonitor::Total().
*
* This function is called repeatedly at regular time intervals until the
* progress count reaches the total count, or until the process is aborted.
*
* This function must return zero if the process can continue. If this
* function returns a nonzero value, the current process is aborted by
* throwing a ProcessAborted exception.
*/
virtual int Updated( const StatusMonitor& monitor ) const = 0;
/*!
* Function called by a status \a monitor object to signal that the current
* process has finished.
*
* When this function is invoked by the status \a monitor, its progress
* count has already reached its total count.
*
* This function must return zero if the process can continue. If this
* function returns a nonzero value, the current process is aborted by
* throwing a ProcessAborted exception.
*
* \note This function allows aborting a process even when it has
* finished. This makes sense, since after a process has finished, the
* PixInsight core application still has some important work to do: update
* the target view's processing history, organize temporary swap files, send
* notifications, update masking relations, etc.
*/
virtual int Completed( const StatusMonitor& monitor ) const = 0;
/*!
* Function called by a status \a monitor object when the progress
* information for the current process has been changed.
*
* The <em>progress information</em> is a string that can be obtained by
* calling StatusMonitor::Info() for the passed \a monitor object.
*/
virtual void InfoUpdated( const StatusMonitor& monitor ) const = 0;
};
// ----------------------------------------------------------------------------
/*!
* \class StatusMonitor
* \brief An asynchronous status monitoring system.
*
* Status monitoring consists of a set of PCL classes and functions to manage
* progress information about ongoing processes. A <em>status monitor</em> is
* an instance of the %StatusMonitor class.
*
* Status monitors provide a generalized mechanism to generate and manage
* progress information while a process is running. A status monitor sends
* progress \e events to an instance of a StatusCallback subclass, whose
* primary responsibility is to provide feedback to the user. Progress feedback
* typically consists of a running percentage or similar text-based information
* written to the standard console.
*
* Along with providing progress feedback, the status monitoring concept is
* quite flexible and has other control applications in PCL, some of them quite
* sophisticated. For example, many standard tools use specialized status
* monitors to implement their real-time preview routines as asynchronously
* interruptible processes.
*
* %StatusMonitor utilizes a low-priority timing thread to generate callback
* monitoring calls asynchronously at constant time intervals. This has
* virtually zero impact on the performance of the monitored processes.
*
* \sa StatusCallback, StandardStatus, SpinStatus, MuteStatus, Console, Thread
*/
class PCL_CLASS StatusMonitor
{
public:
/*!
* Constructs a default %StatusMonitor object.
*/
StatusMonitor() = default;
/*!
* Constructs a %StatusMonitor object as a duplicate of an existing
* instance.
*/
StatusMonitor( const StatusMonitor& x )
{
Assign( x );
}
/*!
* Destroys this %StatusMonitor object.
*/
virtual ~StatusMonitor()
{
Clear();
}
/*!
* Copy assignment operator. Returns a reference to this object.
*/
StatusMonitor& operator =( const StatusMonitor& x )
{
if ( this != &x )
Assign( x );
return *this;
}
/*!
* Initializes this status monitor to start a new monitoring procedure.
*
* \param info Progress information.
*
* \param count Total progress count. If a zero total progress count is
* specified, this monitor will be <em>unbounded</em>. That
* means that the monitor will never reach a completed state
* by increasing or incrementing it. To complete an unbounded
* status monitor, the Complete() member function must be
* called explicitly.
*
* If this monitor has an associated status callback object, this function
* will call the StatusCallback::Initialized() virtual member function of
* the associated callback object.
*
* If this function is invoked while an ongoing monitoring procedure is
* active, it is interrupted and a new monitoring procedure is initialized.
*/
void Initialize( const String& info, size_type count = 0 );
/*!
* Increments the initialization disabling counter for this status monitor.
*
* When the disabling counter is greater than zero, initialization is
* disabled for this monitor, and subsequent calls to the Initialize()
* member function have no effect.
*
* This is useful if your process calls other subroutines that try to
* initialize private monitoring procedures. If such subroutines are called
* as independent processes, they can perform initialization, but if they
* are used as part of a higher level process, they should update a common
* status monitor without reinitializing it.
*
* Here is an example:
*
* \code
* FunctionA( StatusMonitor& m )
* {
* if ( m.IsInitializationEnabled() )
* m.Initialize( "This is function A...", 100 );
* // ...
* for ( int i = 0; i < 100; ++i, ++m )
* // ...
* }
*
* FunctionB( StatusMonitor& m )
* {
* if ( m.IsInitializationEnabled() )
* m.Initialize( "This is function B...", 100 );
* // ...
* for ( int i = 0; i < 10; ++i, m += 10 )
* // ...
* }
*
* ALargerFunction( StatusMonitor& m )
* {
* m.Initialize( "This is some high-level routine...", 200 );
* m.DisableInitialization();
* // ...
* FunctionA( m );
* FunctionB( m );
* // ...
* m.EnableInitialization();
* }
* \endcode
*
* In this example, both FunctionA() and FunctionB() update a %StatusMonitor
* object by a total count of 100 steps. However, these functions don't try
* to initialize the passed monitor if initialization has been disabled.
*
* ALargerFunction() initializes a status monitor with a total count of 200
* and its own information string, then disables monitor initialization. The
* subsequent calls to FunctionA() and FunctionB() will update the monitor
* by 100 steps each, without reinitializing it.
*
* The final call to EnableInitialization() in ALargerFunction() is
* necessary to return the status monitor to its initial enabled or disabled
* state.
*/
void DisableInitialization()
{
++m_initDisableCount;
}
/*!
* Decrements the initialization disabling counter for this status monitor.
*
* When the disabling counter is equal or less than zero, initialization is
* enabled for this monitor.
*
* See DisableInitialization() for further information on the initialization
* enabled/disabled states and a source code example.
*/
void EnableInitialization()
{
--m_initDisableCount;
}
/*!
* Returns true iff monitor initialization has been disabled for this status
* monitor object.
*
* See DisableInitialization() for further information on the initialization
* enabled/disabled states and a source code example.
*/
bool IsInitializationEnabled() const
{
return m_initDisableCount <= 0;
}
/*!
* Returns true iff this status monitor has been initialized.
*
* A status monitor is initialized by a call to its Initialize() member
* function.
*/
bool IsInitialized() const
{
return m_initialized;
}
/*!
* Returns true iff this status monitor has completed a monitoring procedure.
*
* A monitoring procedure is completed if the current monitoring counter
* reaches the total count, or if the Complete() member function is called.
*/
bool IsCompleted() const
{
return m_completed;
}
/*!
* Returns true iff a monitoring procedure has been aborted.
*
* When a monitoring procedure is aborted, the status monitor object throws
* a ProcessAborted exception.
*
* A monitoring procedure can only be aborted by its associated status
* callback object. This is done by returning a nonzero value from the
* StatusCallback::Initialized(), StatusCallback::Updated(), or
* StatusCallback::Completed() virtual member functions implemented by
* a StatusCallback descendant class.
*/
bool IsAborted() const
{
return m_aborted;
}
/*!
* Changes the progress information text for this status monitor.
*
* If there is a status callback object associated with this monitor, its
* StatusCallback::InfoUpdated() member function is invoked.
*/
void SetInfo( const String& s )
{
m_info = s;
if ( m_callback != nullptr )
m_callback->InfoUpdated( *this );
}
/*!
* Increments the progress counter of this status monitor.
*
* If the progress counter reaches Total(), and this monitor has an
* associated status callback object, its StatusCallback::Completed() member
* function is invoked. If the progress counter is less than Total(), the
* StatusCallback::Updated() member function will be invoked by the
* monitoring thread asynchronously.
*
* Note that for \e unbounded monitors the completed state is never reached
* unless a explicit call to Complete() is made, hence the
* StatusCallback::Completed() member function of the status callback
* object, if any, will never be called by this increment operator.
*/
void operator ++()
{
if ( ++m_count == m_total || m_needsUpdate )
Update();
}
/*!
* Increments the progress counter of this status monitor by the specified
* number \a n of progress steps.
*
* This function behaves essentially like the operator ++() function.
*/
void operator +=( size_type n )
{
m_count += n;
if ( m_total != 0 ) // if not an unbounded monitor
if ( m_count > m_total )
m_count = m_total;
if ( m_needsUpdate || m_count == m_total )
Update();
}
/*!
* Forces this monitor to complete the current monitoring procedure, by
* assigning the total progress count to the progress counter.
*
* This function forces a call to StatusCallback::Completed(), if this
* monitor has an associated status callback object.
*/
void Complete()
{
m_count = m_total;
Update();
}
/*!
* Returns the address of the immutable status callback object associated
* with this status monitor. Returns zero if this monitor has no associated
* status callback object.
*/
const StatusCallback* Callback() const
{
return m_callback;
}
/*!
* Returns the address of the status callback object associated with this
* status monitor. Returns zero if this monitor has no associated status
* callback object.
*/
StatusCallback* Callback()
{
return m_callback;
}
/*!
* Associates a status callback object with this status monitor.
*
* Calling this function forces a call to Clear(), which interrupts the
* current monitoring procedure, if any, and reinitializes the internal
* state of this monitor.
*
* To associate no status callback object with this monitor, pass \c nullptr
* as the argument to this function.
*/
void SetCallback( StatusCallback* callback )
{
Reset();
m_callback = callback;
}
/*!
* Returns the last status callback return value.
*
* The returned value is the return value of the last call to
* StatusCallback::Initialized(), StatusCallback::Updated() or
* StatusCallback::Completed() for the associated status callback object, or
* zero if no status callback object has been associated with this monitor.
*
* If a nonzero value is returned, then the current monitoring procedure has
* already been aborted.
*/
int ReturnValue() const
{
return m_retVal;
}
/*!
* Returns the progress information string that has been set for this status
* monitor object.
*/
String Info() const
{
return m_info;
}
/*!
* Returns the progress counter for the current monitoring procedure.
*
* When the progress counter reaches the total count, the monitoring
* procedure has been completed.
*/
size_type Count() const
{
return m_count;
}
/*!
* Returns the total progress count for the current monitoring procedure.
*
* When the progress counter reaches the total count, the monitoring
* procedure has been completed.
*/
size_type Total() const
{
return m_total;
}
/*!
* Interrupts the current monitoring procedure, if any, and reinitializes
* the internal state of this status monitor.
*/
void Clear()
{
Reset();
}
/*!
* Returns the progress monitoring refresh rate in milliseconds.
*
* The StatusCallback::Updated() member functions of all active status
* callback objects are called asynchronously by a low-priority thread. The
* refresh rate is the interval between successive callback update calls. It
* can be in the range from 25 to 999 milliseconds.
*/
static unsigned RefreshRate()
{
return s_msRefreshRate;
}
/*!
* Sets a new progress monitoring refresh rate in milliseconds.
*
* \param ms New monitoring refresh rate in milliseconds. The specified
* value must be between 25 and 999 milliseconds. If the passed
* value is outside that range, it is discarded and the nearest
* valid bound is set.
*
* The default refresh rate is 250 milliseconds, or 4 monitoring events per
* second. The new refresh rate does take effect immediately, even if there
* are active status monitors.
*/
static void SetRefreshRate( unsigned ms );
private:
StatusCallback* m_callback = nullptr;
bool m_initialized = false;
bool m_completed = false;
bool m_aborted = false;
bool m_needsUpdate = false; // thread-safe flag set by the dispatcher
int m_initDisableCount = 0;
int m_retVal = 0;
String m_info;
size_type m_total = 0;
size_type m_count = 0;
static unsigned s_msRefreshRate;
void Reset();
void Assign( const StatusMonitor& );
void Update();
friend class MonitorDispatcherThread;
};
// ----------------------------------------------------------------------------
} // pcl
#endif // __PCL_StatusMonitor_h
// ----------------------------------------------------------------------------
// EOF pcl/StatusMonitor.h - Released 2020-12-17T15:46:29Z
| 34.607431 | 83 | 0.66301 | [
"object"
] |
53de8ee40b17606706d73a79f8fe839fd5ffc20f | 104,142 | c | C | MEukaron/Platform/X64/rme_platform_x64.c | EDI-Systems/M7M1_MuEukaron | 9ffc6cc82b3b773b5b18d98b828b014ecec2b5cb | [
"Unlicense"
] | 78 | 2018-02-21T16:03:52.000Z | 2019-11-05T07:05:02.000Z | MEukaron/Platform/X64/rme_platform_x64.c | EDI-Systems/M7M1_MuEukaron | 9ffc6cc82b3b773b5b18d98b828b014ecec2b5cb | [
"Unlicense"
] | null | null | null | MEukaron/Platform/X64/rme_platform_x64.c | EDI-Systems/M7M1_MuEukaron | 9ffc6cc82b3b773b5b18d98b828b014ecec2b5cb | [
"Unlicense"
] | 28 | 2018-02-27T21:16:47.000Z | 2019-11-12T10:01:00.000Z | /******************************************************************************
Filename : platform_x64.c
Author : pry
Date : 01/04/2017
Licence : The Unlicense; see LICENSE for details.
Description : The hardware abstraction layer for ACPI compliant x86-64 machines.
TODO list:
1. Fix all the system call/int gates, make sure that they cannot cause DOS.
2. Implement NMI to a different stack, thus the NMI will not currupt the
kernel stack. The NMI stack does not have to be large. Use NMIw/LAPIC
timer as watchdog on each core, and if something bad happens we just reboot.
we also need to display whether this is due to hardware fault or something
else.
3. Fix error handling - now they just display info.
4. Test multi-core stuff.
5. User-level: Consider running VMs. We support FULL virtualization
instead of paravirtualization. Use virtualization extensions to do that.
6. Display something on screen at system boot-up. A console will be great.
7. Consider how do we pass COMPLEX system configuration data to the INIT
process. We have multi-sockets and this is going to be very complex if
not well handled.
8. Look into FPU support. Also, FPU support on Cortex-M should be reexamined
if possible. The current FPU support is purely theoretical.
9. Consider using the AML interpreter. Or we will not be able to detect
more complex peripherals.
10. Run this on a real machine to watch output.
11. Consider complex PCI device support and driver compatibility.
12. Make the system NUMA-aware.
******************************************************************************/
/* Includes ******************************************************************/
#define __HDR_DEFS__
#include "Kernel/rme_kernel.h"
#include "Platform/X64/rme_platform_x64.h"
#undef __HDR_DEFS__
#define __HDR_STRUCTS__
#include "Platform/X64/rme_platform_x64.h"
#include "Kernel/rme_kernel.h"
#undef __HDR_STRUCTS__
/* Private include */
#include "Platform/X64/rme_platform_x64.h"
#define __HDR_PUBLIC_MEMBERS__
#include "Kernel/rme_kernel.h"
#undef __HDR_PUBLIC_MEMBERS__
/* End Includes **************************************************************/
/* Begin Function:main ********************************************************
Description : The entrance of the operating system.
Input : rme_ptr_t MBInfo - The multiboot information structure's physical address.
Output : None.
Return : int - This function never returns.
******************************************************************************/
int main(rme_ptr_t MBInfo)
{
RME_X64_MBInfo=(struct multiboot_info*)(MBInfo+RME_X64_VA_BASE);
/* The main function of the kernel - we will start our kernel boot here */
_RME_Kmain(RME_KMEM_STACK_ADDR);
return 0;
}
/* End Function:main *********************************************************/
/* Begin Function:__RME_Putchar ***********************************************
Description : Output a character to console. In Cortex-M, under most circumstances,
we should use the ITM for such outputs.
Input : char Char - The character to print.
Output : None.
Return : rme_ptr_t - Always 0.
******************************************************************************/
rme_ptr_t __RME_Putchar(char Char)
{
if(RME_X64_UART_Exist==0)
return 0;
/* Wait until we have transmitted */
while((__RME_X64_In(RME_X64_COM1+5)&0x20)==0);
__RME_X64_Out(RME_X64_COM1, Char);
return 0;
}
/* End Function:__RME_Putchar ************************************************/
/* Begin Function:__RME_X64_UART_Init *****************************************
Description : Initialize the UART of X64 platform.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_UART_Init(void)
{
/* Disable interrupts */
__RME_X64_Out(RME_X64_COM1+1, 0);
/* Unlock divisor */
__RME_X64_Out(RME_X64_COM1+3, 0x80);
/* Set baudrate - on some computer, the hardware only support this reliably */
__RME_X64_Out(RME_X64_COM1+0, 115200/9600);
__RME_X64_Out(RME_X64_COM1+1, 0);
/* Lock divisor, 8 data bits, 1 stop bit, parity off */
__RME_X64_Out(RME_X64_COM1+3, 0x03);
/* Turn on the FIFO */
__RME_X64_Out(RME_X64_COM1+2, 0xC7);
/* Turn off all model control, fully asynchronous */
__RME_X64_Out(RME_X64_COM1+4, 0);
/* If status is 0xFF, no serial port */
if(__RME_X64_In(RME_X64_COM1+5)==0xFF)
RME_X64_UART_Exist=0;
else
RME_X64_UART_Exist=1;
}
/* End Function:__RME_X64_UART_Init ******************************************/
/* Begin Function:__RME_X64_RDSP_Scan *****************************************
Description : Scan for a valid RDSP structure in the given physical memory segment.
Input : rme_ptr_t Base - The base address of the physical memory segment.
rme_ptr_t Base - The length of the memory segment.
Output : None.
Return : struct RME_X64_ACPI_RDSP_Desc* - The descriptor physical address.
******************************************************************************/
struct RME_X64_ACPI_RDSP_Desc* __RME_X64_RDSP_Scan(rme_ptr_t Base, rme_ptr_t Len)
{
rme_u8_t* Pos;
rme_cnt_t Count;
rme_ptr_t Checksum;
rme_cnt_t Check_Cnt;
Pos=(rme_u8_t*)RME_X64_PA2VA(Base);
/* Search a word at a time */
for(Count=0;Count<=Len-sizeof(struct RME_X64_ACPI_RDSP_Desc);Count+=4)
{
/* It seemed that we have found one. See if the checksum is good */
if(_RME_Memcmp(&(Pos[Count]),"RSD PTR ",8)==0)
{
Checksum=0;
/* 20 is the length of the first part of the table */
for(Check_Cnt=0;Check_Cnt<20;Check_Cnt++)
Checksum+=Pos[Count+Check_Cnt];
/* Is the checksum good? */
if((Checksum&0xFF)==0)
return (struct RME_X64_ACPI_RDSP_Desc*)&(Pos[Count]);
}
}
return 0;
}
/* End Function:__RME_X64_RDSP_Scan ******************************************/
/* Begin Function:__RME_X64_RDSP_Find *****************************************
Description : Find a valid RDSP structure and return it.
Input : None.
Output : None.
Return : struct RME_X64_ACPI_RDSP_Desc* - The descriptor address.
******************************************************************************/
struct RME_X64_ACPI_RDSP_Desc*__RME_X64_RDSP_Find(void)
{
struct RME_X64_ACPI_RDSP_Desc* RDSP;
rme_ptr_t Paddr;
/* 0x40E contains the address of Extended BIOS Data Area (EBDA). Let's try
* to find the RDSP there first */
Paddr=*((rme_u16_t*)RME_X64_PA2VA(0x40E))<<4;
if(Paddr!=0)
{
RDSP=__RME_X64_RDSP_Scan(Paddr,1024);
/* Found */
if(RDSP!=0)
return RDSP;
}
/* If that fails, the RDSP must be here */
return __RME_X64_RDSP_Scan(0xE0000, 0x20000);
}
/* End Function:__RME_X64_RDSP_Find ******************************************/
/* Begin Function:__RME_X64_SMP_Detect ****************************************
Description : Detect the SMP configuration in the system and set up the per-CPU info.
Input : struct RME_X64_ACPI_MADT_Hdr* MADT - The pointer to the MADT header.
Output : None.
Return : rme_ret_t - If successful, 0; else -1.
******************************************************************************/
rme_ret_t __RME_X64_SMP_Detect(struct RME_X64_ACPI_MADT_Hdr* MADT)
{
struct RME_X64_ACPI_MADT_LAPIC_Record* LAPIC;
struct RME_X64_ACPI_MADT_IOAPIC_Record* IOAPIC;
struct RME_X64_ACPI_MADT_SRC_OVERRIDE_Record* OVERRIDE;
rme_ptr_t Length;
rme_u8_t* Ptr;
rme_u8_t* End;
/* Is there a MADT? */
if(MADT==0)
return -1;
/* Is the MADT valid? */
if(MADT->Header.Length<sizeof(struct RME_X64_ACPI_MADT_Hdr))
return -1;
RME_X64_LAPIC_Addr=MADT->LAPIC_Addr_Phys;
/* Where does the actual table contents start? */
Ptr=MADT->Table;
/* Where does it end? */
End=Ptr+MADT->Header.Length-sizeof(struct RME_X64_ACPI_MADT_Hdr);
RME_X64_Num_IOAPIC=0;
RME_X64_Num_CPU=0;
while(Ptr<End)
{
/* See if we have finished scanning the table */
if((End-Ptr)<2)
break;
Length=Ptr[1];
if((End-Ptr)<Length)
break;
/* See what is in the table */
switch(Ptr[0])
{
/* This is a LAPIC */
case RME_X64_MADT_LAPIC:
{
LAPIC=(struct RME_X64_ACPI_MADT_LAPIC_Record*)Ptr;
/* Is the length correct? */
if(Length<sizeof(struct RME_X64_ACPI_MADT_LAPIC_Record))
break;
/* Is this LAPIC enabled? */
if((LAPIC->Flags&RME_X64_APIC_LAPIC_ENABLED)==0)
break;
RME_PRINTK_S("\n\rACPI: CPU ");
RME_Print_Int(RME_X64_Num_CPU);
RME_PRINTK_S(", LAPIC ID ");
RME_Print_Int(LAPIC->APIC_ID);
/* Log this CPU into our per-CPU data structure */
RME_X64_CPU_Info[RME_X64_Num_CPU].LAPIC_ID=LAPIC->APIC_ID;
RME_X64_CPU_Info[RME_X64_Num_CPU].Boot_Done=0;
RME_X64_Num_CPU++;
RME_ASSERT(RME_X64_Num_CPU<=RME_X64_CPU_NUM);
break;
}
/* This is an IOAPIC */
case RME_X64_MADT_IOAPIC:
{
IOAPIC=(struct RME_X64_ACPI_MADT_IOAPIC_Record*)Ptr;
/* Is the length correct? */
if(Length<sizeof(struct RME_X64_ACPI_MADT_IOAPIC_Record))
break;
RME_PRINTK_S("\n\rACPI: IOAPIC ");
RME_Print_Int(RME_X64_Num_IOAPIC);
RME_PRINTK_S(" @ ");
RME_Print_Uint(IOAPIC->Addr);
RME_PRINTK_S(", ID ");
RME_Print_Int(IOAPIC->ID);
RME_PRINTK_S(", IBASE ");
RME_Print_Int(IOAPIC->Interrupt_Base);
/* Support multiple APICS */
if(RME_X64_Num_IOAPIC!=0)
{
RME_PRINTK_S("Warning: multiple ioapics are not supported - currently we will not initialize IOAPIC > 1\n");
}
else
{
RME_X64_IOAPIC_Info[RME_X64_Num_IOAPIC].IOAPIC_ID=IOAPIC->ID;
}
RME_X64_Num_IOAPIC++;
RME_ASSERT(RME_X64_Num_IOAPIC<=RME_X64_IOAPIC_NUM);
break;
}
/* This is interrupt override information */
case RME_X64_MADT_INT_SRC_OVERRIDE:
{
OVERRIDE=(struct RME_X64_ACPI_MADT_SRC_OVERRIDE_Record*)Ptr;
if(Length<sizeof(struct RME_X64_ACPI_MADT_SRC_OVERRIDE_Record))
break;
RME_PRINTK_S("\n\rACPI: OVERRIDE Bus ");
RME_Print_Int(OVERRIDE->Bus);
RME_PRINTK_S(", Source ");
RME_Print_Uint(OVERRIDE->Source);
RME_PRINTK_S(", GSI ");
RME_Print_Int(OVERRIDE->GS_Interrupt);
RME_PRINTK_S(", Flags ");
RME_Print_Int(OVERRIDE->MPS_Int_Flags);
break;
}
/* All other types are ignored */
default:break;
}
Ptr+=Length;
}
return 0;
}
/* End Function:__RME_X64_SMP_Detect *****************************************/
/* Begin Function:__RME_X64_ACPI_Debug ****************************************
Description : Print the information about the ACPI table entry.
Input : struct RME_X64_ACPI_MADT_Hdr* MADT - The pointer to the MADT header.
Output : None.
Return : rme_ret_t - If successful, 0; else -1.
******************************************************************************/
void __RME_X64_ACPI_Debug(struct RME_X64_ACPI_Desc_Hdr *Header)
{
rme_u8_t Signature[5];
rme_u8_t ID[7];
rme_u8_t Table_ID[9];
rme_u8_t Creator[5];
rme_ptr_t OEM_Rev;
rme_ptr_t Creator_Rev;
/* Copy everything into our buffer */
_RME_Memcpy(Signature, Header->Signature, 4);
Signature[4]='\0';
_RME_Memcpy(ID, Header->OEM_ID, 6);
ID[6]='\0';
_RME_Memcpy(Table_ID, Header->OEM_Table_ID, 8);
Table_ID[8]='\0';
_RME_Memcpy(Creator, Header->Creator_ID, 4);
Creator[4]='\0';
OEM_Rev=Header->OEM_Revision;
Creator_Rev=Header->Creator_Revision;
/* And print these entries */
RME_PRINTK_S("\n\rACPI:");
RME_PRINTK_S(Signature);
RME_PRINTK_S(", ");
RME_PRINTK_S(ID);
RME_PRINTK_S(", ");
RME_PRINTK_S(Table_ID);
RME_PRINTK_S(", ");
RME_PRINTK_S(OEM_Rev);
RME_PRINTK_S(", ");
RME_PRINTK_S(Creator);
RME_PRINTK_S(", ");
RME_PRINTK_S(Creator_Rev);
RME_PRINTK_S(".");
}
/* End Function:__RME_X64_ACPI_Debug *****************************************/
/* Begin Function:__RME_X64_ACPI_Init *****************************************
Description : Detect the SMP configuration in the system and set up the per-CPU info.
Input : struct RME_X64_ACPI_MADT_Hdr* MADT - The pointer to the MADT header.
Output : None.
Return : rme_ret_t - If successful, 0; else -1.
******************************************************************************/
rme_ret_t __RME_X64_ACPI_Init(void)
{
rme_cnt_t Count;
rme_cnt_t Table_Num;
struct RME_X64_ACPI_RDSP_Desc* RDSP;
struct RME_X64_ACPI_RSDT_Hdr* RSDT;
struct RME_X64_ACPI_MADT_Hdr* MADT;
struct RME_X64_ACPI_Desc_Hdr* Header;
/* Try to find RDSP */
RDSP=__RME_X64_RDSP_Find();
RME_PRINTK_S("\r\nRDSP address: ");
RME_PRINTK_U((rme_ptr_t)RDSP);
/* Find the RSDT */
RSDT=(struct RME_X64_ACPI_RSDT_Hdr*)RME_X64_PA2VA(RDSP->RSDT_Addr_Phys);
RME_PRINTK_S("\r\nRSDT address: ");
RME_PRINTK_U((rme_ptr_t)RSDT);
Table_Num=(RSDT->Header.Length-sizeof(struct RME_X64_ACPI_RSDT_Hdr))>>2;
for(Count=0;Count<Table_Num;Count++)
{
/* See what did we find */
Header=(struct RME_X64_ACPI_Desc_Hdr*)RME_X64_PA2VA(RSDT->Entry[Count]);
__RME_X64_ACPI_Debug(Header);
/* See if this is the MADT */
if(_RME_Memcmp(Header->Signature, "APIC", 4)==0)
MADT=(struct RME_X64_ACPI_MADT_Hdr*)Header;
}
return __RME_X64_SMP_Detect(MADT);
}
/* End Function:__RME_X64_ACPI_Init ******************************************/
/* Begin Function:__RME_X64_Feature_Get ***************************************
Description : Use the CPUID instruction extensively to get all the processor
information. We assume that all processors installed have the same
features.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_Feature_Get(void)
{
rme_cnt_t Count;
/* What's the maximum feature? */
RME_X64_Feature.Max_Func=__RME_X64_CPUID_Get(RME_X64_CPUID_0_VENDOR_ID,
(rme_ptr_t*)&(RME_X64_Feature.Func[0][1]),
(rme_ptr_t*)&(RME_X64_Feature.Func[0][2]),
(rme_ptr_t*)&(RME_X64_Feature.Func[0][3]));
RME_X64_Feature.Func[0][0]=RME_X64_Feature.Max_Func;
/* Get all the feature bits */
for(Count=1;Count<=RME_X64_Feature.Max_Func;Count++)
{
RME_X64_Feature.Func[Count][0]=__RME_X64_CPUID_Get(Count,
(rme_ptr_t*)&(RME_X64_Feature.Func[Count][1]),
(rme_ptr_t*)&(RME_X64_Feature.Func[Count][2]),
(rme_ptr_t*)&(RME_X64_Feature.Func[Count][3]));
}
/* What's the maximum extended feature? */
RME_X64_Feature.Max_Ext=__RME_X64_CPUID_Get(RME_X64_CPUID_E0_EXT_MAX,
(rme_ptr_t*)&(RME_X64_Feature.Ext[0][1]),
(rme_ptr_t*)&(RME_X64_Feature.Ext[0][2]),
(rme_ptr_t*)&(RME_X64_Feature.Ext[0][3]));
RME_X64_Feature.Ext[0][0]=RME_X64_Feature.Max_Ext;
/* Get all the feature bits */
for(Count=1;Count<=RME_X64_Feature.Max_Ext-RME_X64_CPUID_E0_EXT_MAX;Count++)
{
RME_X64_Feature.Ext[Count][0]=__RME_X64_CPUID_Get(RME_X64_CPUID_E0_EXT_MAX|Count,
(rme_ptr_t*)&(RME_X64_Feature.Ext[Count][1]),
(rme_ptr_t*)&(RME_X64_Feature.Ext[Count][2]),
(rme_ptr_t*)&(RME_X64_Feature.Ext[Count][3]));
}
/* TODO: Check these flags. If not satisfied, we hang immediately. */
}
/* End Function:__RME_X64_Feature_Get ****************************************/
/* Begin Function:__RME_X64_Mem_Init ******************************************
Description : Initialize the memory map, and get the size of kernel object
allocation registration table(Kotbl) and page table reference
count registration table(Pgreg).
Input : rme_ptr_t MMap_Addr - The GRUB multiboot memory map data address.
rme_ptr_t MMap_Length - The GRUB multiboot memory map data length.
Output : None.
Return : None.
******************************************************************************/
/* We place this here because these are never exported, and are local to this
* file. This is a little workaround for the header inclusion problem */
struct __RME_X64_Mem
{
struct RME_List Head;
rme_ptr_t Start_Addr;
rme_ptr_t Length;
};
/* The header of the physical memory linked list */
struct RME_List RME_X64_Phys_Mem;
/* The BIOS wouldn't really report more than 1024 blocks of memory */
struct __RME_X64_Mem RME_X64_Mem[1024];
void __RME_X64_Mem_Init(rme_ptr_t MMap_Addr, rme_ptr_t MMap_Length)
{
struct multiboot_mmap_entry* MMap;
volatile struct RME_List* Trav_Ptr;
rme_ptr_t MMap_Cnt;
rme_ptr_t Info_Cnt;
MMap_Cnt=0;
Info_Cnt=0;
__RME_List_Crt(&RME_X64_Phys_Mem);
while(MMap_Cnt<MMap_Length)
{
MMap=(struct multiboot_mmap_entry*)(MMap_Addr+MMap_Cnt);
MMap_Cnt+=MMap->size+4;
if(MMap->type!=1)
continue;
Trav_Ptr=RME_X64_Phys_Mem.Next;
while(Trav_Ptr!=&RME_X64_Phys_Mem)
{
if(((struct __RME_X64_Mem*)(Trav_Ptr))->Start_Addr>MMap->addr)
break;
Trav_Ptr=Trav_Ptr->Next;
}
RME_X64_Mem[Info_Cnt].Start_Addr=MMap->addr;
RME_X64_Mem[Info_Cnt].Length=MMap->len;
__RME_List_Ins(&(RME_X64_Mem[Info_Cnt].Head),Trav_Ptr->Prev,Trav_Ptr);
/* Just print them then */
RME_PRINTK_S("\n\rPhysical memory: 0x");
RME_Print_Uint(MMap->addr);
RME_PRINTK_S(", 0x");
RME_Print_Uint(MMap->len);
RME_PRINTK_S(", ");
RME_Print_Uint(MMap->type);
Info_Cnt++;
}
/* Check if any memory segment overlaps. If yes, merge them into one,
* until there is no overlapping segments */
Trav_Ptr=RME_X64_Phys_Mem.Next;
while((Trav_Ptr!=&RME_X64_Phys_Mem)&&((Trav_Ptr->Next)!=&RME_X64_Phys_Mem))
{
if((((struct __RME_X64_Mem*)(Trav_Ptr))->Start_Addr+
((struct __RME_X64_Mem*)(Trav_Ptr))->Length)>
((struct __RME_X64_Mem*)(Trav_Ptr->Next))->Start_Addr)
{
/* Merge these two blocks */
((struct __RME_X64_Mem*)(Trav_Ptr))->Length=
((struct __RME_X64_Mem*)(Trav_Ptr->Next))->Start_Addr+
((struct __RME_X64_Mem*)(Trav_Ptr->Next))->Length-
((struct __RME_X64_Mem*)(Trav_Ptr))->Start_Addr;
__RME_List_Del(Trav_Ptr,Trav_Ptr->Next->Next);
continue;
}
Trav_Ptr=Trav_Ptr->Next;
}
/* Calculate total memory */
MMap_Cnt=0;
Trav_Ptr=RME_X64_Phys_Mem.Next;
while(Trav_Ptr!=&RME_X64_Phys_Mem)
{
MMap_Cnt+=((struct __RME_X64_Mem*)(Trav_Ptr))->Length;
Trav_Ptr=Trav_Ptr->Next;
}
RME_PRINTK_S("\n\rTotal physical memory: 0x");
RME_Print_Uint(MMap_Cnt);
/* At least 256MB memory required on x64 architecture */
RME_ASSERT(MMap_Cnt>=RME_POW2(RME_PGTBL_SIZE_256M));
/* Kernel virtual memory layout */
RME_X64_Layout.Kotbl_Start=(rme_ptr_t)RME_KOTBL;
/* +1G in cases where we have > 3GB memory for covering the memory hole */
Info_Cnt=(MMap_Cnt>3*RME_POW2(RME_PGTBL_SIZE_1G))?(MMap_Cnt+RME_POW2(RME_PGTBL_SIZE_1G)):MMap_Cnt;
RME_X64_Layout.Kotbl_Size=((Info_Cnt>>RME_KMEM_SLOT_ORDER)>>RME_WORD_ORDER)+1;
/* Calculate the size of page table registration table size - we always assume 4GB range */
Info_Cnt=(MMap_Cnt>RME_POW2(RME_PGTBL_SIZE_4G))?RME_POW2(RME_PGTBL_SIZE_4G):MMap_Cnt;
RME_X64_Layout.Pgreg_Start=RME_X64_Layout.Kotbl_Start+RME_X64_Layout.Kotbl_Size;
RME_X64_Layout.Pgreg_Size=((Info_Cnt>>RME_PGTBL_SIZE_4K)+1)*sizeof(struct __RME_X64_Pgreg);
/* Calculate the per-CPU data structure size - each CPU have two 4k pages */
RME_X64_Layout.PerCPU_Start=RME_ROUND_UP(RME_X64_Layout.Pgreg_Start+RME_X64_Layout.Pgreg_Size,RME_PGTBL_SIZE_4K);
RME_X64_Layout.PerCPU_Size=2*RME_POW2(RME_PGTBL_SIZE_4K)*RME_X64_Num_CPU;
/* Now decide the size of the stack */
RME_X64_Layout.Stack_Size=RME_X64_Num_CPU<<RME_X64_KSTACK_ORDER;
}
/* End Function:__RME_X64_Mem_Init *******************************************/
/* Begin Function:__RME_X64_CPU_Local_Init ************************************
Description : Initialize CPU-local data structures. The layout of each CPU-local
data structure is:
| 4kB | 1kB | 3kB-3*8Bytes | 3*8Bytes |
| IDT[255:0] | GDT/TSS | RME_CPU_Local | RME_X64_Temp |
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_CPU_Local_Init(void)
{
volatile rme_u16_t Desc[5];
struct RME_X64_IDT_Entry* IDT_Table;
struct RME_X64_Temp* Temp;
struct RME_CPU_Local* CPU_Local;
rme_ptr_t* GDT_Table;
rme_ptr_t TSS_Table;
rme_cnt_t Count;
IDT_Table=(struct RME_X64_IDT_Entry*)RME_X64_CPU_LOCAL_BASE(RME_X64_CPU_Cnt);
/* Clean up the whole IDT */
for(Count=0;Count<256;Count++)
IDT_Table[Count].Type_Attr=0;
/* Install the vectors - only the INT3 is trap (for debugging), all other ones are interrupt */
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_DE, RME_X64_IDT_VECT, __RME_X64_FAULT_DE_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_TRAP_DB, RME_X64_IDT_VECT, __RME_X64_TRAP_DB_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_INT_NMI, RME_X64_IDT_VECT, __RME_X64_INT_NMI_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_TRAP_BP, RME_X64_IDT_TRAP, __RME_X64_TRAP_BP_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_TRAP_OF, RME_X64_IDT_VECT, __RME_X64_TRAP_OF_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_BR, RME_X64_IDT_VECT, __RME_X64_FAULT_BR_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_UD, RME_X64_IDT_VECT, __RME_X64_FAULT_UD_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_NM, RME_X64_IDT_VECT, __RME_X64_FAULT_NM_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_ABORT_DF, RME_X64_IDT_VECT, __RME_X64_ABORT_DF_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_ABORT_OLD_MF, RME_X64_IDT_VECT, __RME_X64_ABORT_OLD_MF_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_TS, RME_X64_IDT_VECT, __RME_X64_FAULT_TS_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_NP, RME_X64_IDT_VECT, __RME_X64_FAULT_NP_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_SS, RME_X64_IDT_VECT, __RME_X64_FAULT_SS_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_GP, RME_X64_IDT_VECT, __RME_X64_FAULT_GP_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_PF, RME_X64_IDT_VECT, __RME_X64_FAULT_PF_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_MF, RME_X64_IDT_VECT, __RME_X64_FAULT_MF_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_AC, RME_X64_IDT_VECT, __RME_X64_FAULT_AC_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_ABORT_MC, RME_X64_IDT_VECT, __RME_X64_ABORT_MC_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_XM, RME_X64_IDT_VECT, __RME_X64_FAULT_XM_Handler);
RME_X64_SET_IDT(IDT_Table, RME_X64_FAULT_VE, RME_X64_IDT_VECT, __RME_X64_FAULT_VE_Handler);
/* Install user handlers */
RME_X64_USER_IDT(IDT_Table, 32); RME_X64_USER_IDT(IDT_Table, 33);
RME_X64_USER_IDT(IDT_Table, 34); RME_X64_USER_IDT(IDT_Table, 35);
RME_X64_USER_IDT(IDT_Table, 36); RME_X64_USER_IDT(IDT_Table, 37);
RME_X64_USER_IDT(IDT_Table, 38); RME_X64_USER_IDT(IDT_Table, 39);
RME_X64_USER_IDT(IDT_Table, 40); RME_X64_USER_IDT(IDT_Table, 41);
RME_X64_USER_IDT(IDT_Table, 42); RME_X64_USER_IDT(IDT_Table, 43);
RME_X64_USER_IDT(IDT_Table, 44); RME_X64_USER_IDT(IDT_Table, 45);
RME_X64_USER_IDT(IDT_Table, 46); RME_X64_USER_IDT(IDT_Table, 47);
RME_X64_USER_IDT(IDT_Table, 48); RME_X64_USER_IDT(IDT_Table, 49);
RME_X64_USER_IDT(IDT_Table, 50); RME_X64_USER_IDT(IDT_Table, 51);
RME_X64_USER_IDT(IDT_Table, 52); RME_X64_USER_IDT(IDT_Table, 53);
RME_X64_USER_IDT(IDT_Table, 54); RME_X64_USER_IDT(IDT_Table, 55);
RME_X64_USER_IDT(IDT_Table, 56); RME_X64_USER_IDT(IDT_Table, 57);
RME_X64_USER_IDT(IDT_Table, 58); RME_X64_USER_IDT(IDT_Table, 59);
RME_X64_USER_IDT(IDT_Table, 60); RME_X64_USER_IDT(IDT_Table, 61);
RME_X64_USER_IDT(IDT_Table, 62); RME_X64_USER_IDT(IDT_Table, 63);
RME_X64_USER_IDT(IDT_Table, 64); RME_X64_USER_IDT(IDT_Table, 65);
RME_X64_USER_IDT(IDT_Table, 66); RME_X64_USER_IDT(IDT_Table, 67);
RME_X64_USER_IDT(IDT_Table, 68); RME_X64_USER_IDT(IDT_Table, 69);
RME_X64_USER_IDT(IDT_Table, 70); RME_X64_USER_IDT(IDT_Table, 71);
RME_X64_USER_IDT(IDT_Table, 72); RME_X64_USER_IDT(IDT_Table, 73);
RME_X64_USER_IDT(IDT_Table, 74); RME_X64_USER_IDT(IDT_Table, 75);
RME_X64_USER_IDT(IDT_Table, 76); RME_X64_USER_IDT(IDT_Table, 77);
RME_X64_USER_IDT(IDT_Table, 78); RME_X64_USER_IDT(IDT_Table, 79);
RME_X64_USER_IDT(IDT_Table, 80); RME_X64_USER_IDT(IDT_Table, 81);
RME_X64_USER_IDT(IDT_Table, 82); RME_X64_USER_IDT(IDT_Table, 83);
RME_X64_USER_IDT(IDT_Table, 84); RME_X64_USER_IDT(IDT_Table, 85);
RME_X64_USER_IDT(IDT_Table, 86); RME_X64_USER_IDT(IDT_Table, 87);
RME_X64_USER_IDT(IDT_Table, 88); RME_X64_USER_IDT(IDT_Table, 89);
RME_X64_USER_IDT(IDT_Table, 90); RME_X64_USER_IDT(IDT_Table, 91);
RME_X64_USER_IDT(IDT_Table, 92); RME_X64_USER_IDT(IDT_Table, 93);
RME_X64_USER_IDT(IDT_Table, 94); RME_X64_USER_IDT(IDT_Table, 95);
RME_X64_USER_IDT(IDT_Table, 96); RME_X64_USER_IDT(IDT_Table, 97);
RME_X64_USER_IDT(IDT_Table, 98); RME_X64_USER_IDT(IDT_Table, 99);
RME_X64_USER_IDT(IDT_Table, 100); RME_X64_USER_IDT(IDT_Table, 101);
RME_X64_USER_IDT(IDT_Table, 102); RME_X64_USER_IDT(IDT_Table, 103);
RME_X64_USER_IDT(IDT_Table, 104); RME_X64_USER_IDT(IDT_Table, 105);
RME_X64_USER_IDT(IDT_Table, 106); RME_X64_USER_IDT(IDT_Table, 107);
RME_X64_USER_IDT(IDT_Table, 108); RME_X64_USER_IDT(IDT_Table, 109);
RME_X64_USER_IDT(IDT_Table, 110); RME_X64_USER_IDT(IDT_Table, 111);
RME_X64_USER_IDT(IDT_Table, 112); RME_X64_USER_IDT(IDT_Table, 113);
RME_X64_USER_IDT(IDT_Table, 114); RME_X64_USER_IDT(IDT_Table, 115);
RME_X64_USER_IDT(IDT_Table, 116); RME_X64_USER_IDT(IDT_Table, 117);
RME_X64_USER_IDT(IDT_Table, 118); RME_X64_USER_IDT(IDT_Table, 119);
RME_X64_USER_IDT(IDT_Table, 120); RME_X64_USER_IDT(IDT_Table, 121);
RME_X64_USER_IDT(IDT_Table, 122); RME_X64_USER_IDT(IDT_Table, 123);
RME_X64_USER_IDT(IDT_Table, 124); RME_X64_USER_IDT(IDT_Table, 125);
RME_X64_USER_IDT(IDT_Table, 126); RME_X64_USER_IDT(IDT_Table, 127);
RME_X64_USER_IDT(IDT_Table, 128); RME_X64_USER_IDT(IDT_Table, 129);
RME_X64_USER_IDT(IDT_Table, 130); RME_X64_USER_IDT(IDT_Table, 131);
RME_X64_USER_IDT(IDT_Table, 132); RME_X64_USER_IDT(IDT_Table, 133);
RME_X64_USER_IDT(IDT_Table, 134); RME_X64_USER_IDT(IDT_Table, 135);
RME_X64_USER_IDT(IDT_Table, 136); RME_X64_USER_IDT(IDT_Table, 137);
RME_X64_USER_IDT(IDT_Table, 138); RME_X64_USER_IDT(IDT_Table, 139);
RME_X64_USER_IDT(IDT_Table, 140); RME_X64_USER_IDT(IDT_Table, 141);
RME_X64_USER_IDT(IDT_Table, 142); RME_X64_USER_IDT(IDT_Table, 143);
RME_X64_USER_IDT(IDT_Table, 144); RME_X64_USER_IDT(IDT_Table, 145);
RME_X64_USER_IDT(IDT_Table, 146); RME_X64_USER_IDT(IDT_Table, 147);
RME_X64_USER_IDT(IDT_Table, 148); RME_X64_USER_IDT(IDT_Table, 149);
RME_X64_USER_IDT(IDT_Table, 150); RME_X64_USER_IDT(IDT_Table, 151);
RME_X64_USER_IDT(IDT_Table, 152); RME_X64_USER_IDT(IDT_Table, 153);
RME_X64_USER_IDT(IDT_Table, 154); RME_X64_USER_IDT(IDT_Table, 155);
RME_X64_USER_IDT(IDT_Table, 156); RME_X64_USER_IDT(IDT_Table, 157);
RME_X64_USER_IDT(IDT_Table, 158); RME_X64_USER_IDT(IDT_Table, 159);
RME_X64_USER_IDT(IDT_Table, 160); RME_X64_USER_IDT(IDT_Table, 161);
RME_X64_USER_IDT(IDT_Table, 162); RME_X64_USER_IDT(IDT_Table, 163);
RME_X64_USER_IDT(IDT_Table, 164); RME_X64_USER_IDT(IDT_Table, 165);
RME_X64_USER_IDT(IDT_Table, 166); RME_X64_USER_IDT(IDT_Table, 167);
RME_X64_USER_IDT(IDT_Table, 168); RME_X64_USER_IDT(IDT_Table, 169);
RME_X64_USER_IDT(IDT_Table, 170); RME_X64_USER_IDT(IDT_Table, 171);
RME_X64_USER_IDT(IDT_Table, 172); RME_X64_USER_IDT(IDT_Table, 173);
RME_X64_USER_IDT(IDT_Table, 174); RME_X64_USER_IDT(IDT_Table, 175);
RME_X64_USER_IDT(IDT_Table, 176); RME_X64_USER_IDT(IDT_Table, 177);
RME_X64_USER_IDT(IDT_Table, 178); RME_X64_USER_IDT(IDT_Table, 179);
RME_X64_USER_IDT(IDT_Table, 180); RME_X64_USER_IDT(IDT_Table, 181);
RME_X64_USER_IDT(IDT_Table, 182); RME_X64_USER_IDT(IDT_Table, 183);
RME_X64_USER_IDT(IDT_Table, 184); RME_X64_USER_IDT(IDT_Table, 185);
RME_X64_USER_IDT(IDT_Table, 186); RME_X64_USER_IDT(IDT_Table, 187);
RME_X64_USER_IDT(IDT_Table, 188); RME_X64_USER_IDT(IDT_Table, 189);
RME_X64_USER_IDT(IDT_Table, 190); RME_X64_USER_IDT(IDT_Table, 191);
RME_X64_USER_IDT(IDT_Table, 192); RME_X64_USER_IDT(IDT_Table, 193);
RME_X64_USER_IDT(IDT_Table, 194); RME_X64_USER_IDT(IDT_Table, 195);
RME_X64_USER_IDT(IDT_Table, 196); RME_X64_USER_IDT(IDT_Table, 197);
RME_X64_USER_IDT(IDT_Table, 198); RME_X64_USER_IDT(IDT_Table, 199);
RME_X64_USER_IDT(IDT_Table, 200); RME_X64_USER_IDT(IDT_Table, 201);
RME_X64_USER_IDT(IDT_Table, 202); RME_X64_USER_IDT(IDT_Table, 203);
RME_X64_USER_IDT(IDT_Table, 204); RME_X64_USER_IDT(IDT_Table, 205);
RME_X64_USER_IDT(IDT_Table, 206); RME_X64_USER_IDT(IDT_Table, 207);
RME_X64_USER_IDT(IDT_Table, 208); RME_X64_USER_IDT(IDT_Table, 209);
RME_X64_USER_IDT(IDT_Table, 210); RME_X64_USER_IDT(IDT_Table, 211);
RME_X64_USER_IDT(IDT_Table, 212); RME_X64_USER_IDT(IDT_Table, 213);
RME_X64_USER_IDT(IDT_Table, 214); RME_X64_USER_IDT(IDT_Table, 215);
RME_X64_USER_IDT(IDT_Table, 216); RME_X64_USER_IDT(IDT_Table, 217);
RME_X64_USER_IDT(IDT_Table, 218); RME_X64_USER_IDT(IDT_Table, 219);
RME_X64_USER_IDT(IDT_Table, 220); RME_X64_USER_IDT(IDT_Table, 221);
RME_X64_USER_IDT(IDT_Table, 222); RME_X64_USER_IDT(IDT_Table, 223);
RME_X64_USER_IDT(IDT_Table, 224); RME_X64_USER_IDT(IDT_Table, 225);
RME_X64_USER_IDT(IDT_Table, 226); RME_X64_USER_IDT(IDT_Table, 227);
RME_X64_USER_IDT(IDT_Table, 228); RME_X64_USER_IDT(IDT_Table, 229);
RME_X64_USER_IDT(IDT_Table, 230); RME_X64_USER_IDT(IDT_Table, 231);
RME_X64_USER_IDT(IDT_Table, 232); RME_X64_USER_IDT(IDT_Table, 233);
RME_X64_USER_IDT(IDT_Table, 234); RME_X64_USER_IDT(IDT_Table, 235);
RME_X64_USER_IDT(IDT_Table, 236); RME_X64_USER_IDT(IDT_Table, 237);
RME_X64_USER_IDT(IDT_Table, 238); RME_X64_USER_IDT(IDT_Table, 239);
RME_X64_USER_IDT(IDT_Table, 240); RME_X64_USER_IDT(IDT_Table, 241);
RME_X64_USER_IDT(IDT_Table, 242); RME_X64_USER_IDT(IDT_Table, 243);
RME_X64_USER_IDT(IDT_Table, 244); RME_X64_USER_IDT(IDT_Table, 245);
RME_X64_USER_IDT(IDT_Table, 246); RME_X64_USER_IDT(IDT_Table, 247);
RME_X64_USER_IDT(IDT_Table, 248); RME_X64_USER_IDT(IDT_Table, 249);
RME_X64_USER_IDT(IDT_Table, 250); RME_X64_USER_IDT(IDT_Table, 251);
RME_X64_USER_IDT(IDT_Table, 252); RME_X64_USER_IDT(IDT_Table, 253);
RME_X64_USER_IDT(IDT_Table, 254); RME_X64_USER_IDT(IDT_Table, 255);
/* Replace systick handler with customized ones - spurious interrupts
* and IPIs are handled in the general interrupt path. SysTick handler
* is only processed by the first processor, so we don't register it
* for other auxiliary processors */
if(RME_X64_CPU_Cnt==0)
RME_X64_SET_IDT(IDT_Table, RME_X64_INT_SYSTICK, RME_X64_IDT_VECT, SysTick_Handler);
/* Register SMP handlers */
RME_X64_SET_IDT(IDT_Table, RME_X64_INT_SMP_SYSTICK, RME_X64_IDT_VECT, SysTick_SMP_Handler);
/* Load the IDT */
Desc[0]=RME_POW2(RME_PGTBL_SIZE_4K)-1;
Desc[1]=(rme_ptr_t)IDT_Table;
Desc[2]=((rme_ptr_t)IDT_Table)>>16;
Desc[3]=((rme_ptr_t)IDT_Table)>>32;
Desc[4]=((rme_ptr_t)IDT_Table)>>48;
__RME_X64_IDT_Load((rme_ptr_t*)Desc);
GDT_Table=(rme_ptr_t*)(RME_X64_CPU_LOCAL_BASE(RME_X64_CPU_Cnt)+RME_POW2(RME_PGTBL_SIZE_4K));
TSS_Table=(rme_ptr_t)(RME_X64_CPU_LOCAL_BASE(RME_X64_CPU_Cnt)+RME_POW2(RME_PGTBL_SIZE_4K)+16*sizeof(rme_ptr_t));
/* Dummy entry */
GDT_Table[0]=0x0000000000000000ULL;
/* Kernel code, DPL=0, R/X */
GDT_Table[1]=0x0020980000000000ULL;
/* Kernel data, DPL=0, W */
GDT_Table[2]=0x0000920000000000ULL;
/* Unused entry - this is for sysret instruction's requirement */
GDT_Table[3]=0x0000000000000000ULL;
/* User data, DPL=3, W */
GDT_Table[4]=0x0000F20000000000ULL;
/* User code, DPL=3, R/X */
GDT_Table[5]=0x0020F80000000000ULL;
/* TSS */
GDT_Table[6]=(0x0067)|((TSS_Table&0xFFFFFFULL)<<16)|(0x0089ULL<<40)|(((TSS_Table>>24)&0xFFULL)<<56);
GDT_Table[7]=(TSS_Table>>32);
/* Load the GDT */
Desc[0]=8*sizeof(rme_ptr_t)-1;
Desc[1]=(rme_ptr_t)GDT_Table;
Desc[2]=((rme_ptr_t)GDT_Table)>>16;
Desc[3]=((rme_ptr_t)GDT_Table)>>32;
Desc[4]=((rme_ptr_t)GDT_Table)>>48;
__RME_X64_GDT_Load((rme_ptr_t*)Desc);
/* Set the RSP to TSS */
((rme_u32_t*)TSS_Table)[1]=RME_X64_KSTACK(RME_X64_CPU_Cnt);
((rme_u32_t*)TSS_Table)[2]=RME_X64_KSTACK(RME_X64_CPU_Cnt)>>32;
/* IO Map Base = End of TSS (What's this?) */
((rme_u32_t*)TSS_Table)[16]=0x00680000;
__RME_X64_TSS_Load(6*sizeof(rme_ptr_t));
/* Initialize the RME per-cpu data here */
CPU_Local=(struct RME_CPU_Local*)(RME_X64_CPU_LOCAL_BASE(RME_X64_CPU_Cnt)+
RME_POW2(RME_PGTBL_SIZE_4K)+
RME_POW2(RME_PGTBL_SIZE_1K));
_RME_CPU_Local_Init(CPU_Local,RME_X64_CPU_Cnt);
/* Initialize x64 specific CPU-local data structure */
Temp=(struct RME_X64_Temp*)(RME_X64_CPU_LOCAL_BASE(RME_X64_CPU_Cnt+1)-sizeof(struct RME_X64_Temp));
Temp->CPU_Local_Addr=(rme_ptr_t)CPU_Local;
Temp->Kernel_SP=RME_X64_KSTACK(RME_X64_CPU_Cnt);
Temp->Temp_User_SP=0;
/* Set the base of GS to this memory */
__RME_X64_Write_MSR(RME_X64_MSR_IA32_KERNEL_GS_BASE, (rme_ptr_t)IDT_Table);
__RME_X64_Write_MSR(RME_X64_MSR_IA32_GS_BASE, (rme_ptr_t)IDT_Table);
/* Enable SYSCALL/SYSRET */
__RME_X64_Write_MSR(RME_X64_MSR_IA32_EFER,__RME_X64_Read_MSR(RME_X64_MSR_IA32_EFER)|RME_X64_MSR_IA32_EFER_SCE);
/* Set up SYSCALL/SYSRET parameters */
__RME_X64_Write_MSR(RME_X64_MSR_IA32_LSTAR, (rme_ptr_t)SVC_Handler);
__RME_X64_Write_MSR(RME_X64_MSR_IA32_FMASK, ~RME_X64_RFLAGS_IF);
/* The SYSRET, when returning to user mode in 64-bit, will load the SS from +8, and CS from +16.
* The original place for CS is reserved for 32-bit usages and is thus not usable by 64-bit */
__RME_X64_Write_MSR(RME_X64_MSR_IA32_STAR, (((rme_ptr_t)RME_X64_SEG_EMPTY)<<48)|(((rme_ptr_t)RME_X64_SEG_KERNEL_CODE)<<32));
}
/* End Function:__RME_X64_CPU_Local_Init *************************************/
/* Begin Function:__RME_X64_CPU_Local_Get_By_CPUID ****************************
Description : Given the CPUID of a CPU, get its RME CPU-local data structure.
Input : None.
Output : None.
Return : None.
******************************************************************************/
struct RME_CPU_Local* __RME_X64_CPU_Local_Get_By_CPUID(rme_ptr_t CPUID)
{
return (struct RME_CPU_Local*)(RME_X64_CPU_LOCAL_BASE(CPUID)+
RME_POW2(RME_PGTBL_SIZE_4K)+
RME_POW2(RME_PGTBL_SIZE_1K));
}
/* End Function:__RME_X64_CPU_Local_Get_By_CPUID *****************************/
/* Begin Function:__RME_X64_LAPIC_Ack *****************************************
Description : Acknowledge the interrupt on LAPIC.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_LAPIC_Ack(void)
{
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_EOI, 0);
}
/* End Function:__RME_X64_LAPIC_Ack ******************************************/
/* Begin Function:__RME_X64_LAPIC_Init ****************************************
Description : Initialize LAPIC controllers - this will be run once on everycore.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_LAPIC_Init(void)
{
/* LAPIC initialization - Check if there is any LAPIC */
RME_ASSERT(RME_X64_LAPIC_Addr!=0);
/* Enable local APIC; set spurious interrupt vector to 32 */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_SVR, RME_X64_LAPIC_SVR_ENABLE|RME_X64_INT_SPUR);
/* Disable local interrupt lines */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_LINT0, RME_X64_LAPIC_MASKED);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_LINT1, RME_X64_LAPIC_MASKED);
/* Disable performance counter overflow interrupts when there is one */
if(((RME_X64_LAPIC_READ(RME_X64_LAPIC_VER)>>16)&0xFF)>=4)
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_PCINT, RME_X64_LAPIC_MASKED);
/* Map error interrupt to IRQ_ERROR */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ERROR, RME_X64_INT_ERROR);
/* Clear error status register (requires back-to-back writes) */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ESR, 0);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ESR, 0);
/* Acknowledge any outstanding interrupts */
__RME_X64_LAPIC_Ack();
/* Send an Init Level De-Assert to synchronise arbitration IDs */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRHI, 0);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRLO, RME_X64_LAPIC_ICRLO_BCAST|
RME_X64_LAPIC_ICRLO_INIT|
RME_X64_LAPIC_ICRLO_LEVEL);
while(RME_X64_LAPIC_READ(RME_X64_LAPIC_ICRLO)&RME_X64_LAPIC_ICRLO_DELIVS);
/* Enable interrupts on the APIC */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_TPR, 0);
}
/* End Function:__RME_X64_LAPIC_Init *****************************************/
/* Begin Function:__RME_X64_PIC_Init ******************************************
Description : Initialize PIC controllers - we just disable it once and for all.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_PIC_Init(void)
{
/* Mask all interrupts */
__RME_X64_Out(RME_X64_PIC1+1, 0xFF);
__RME_X64_Out(RME_X64_PIC2+1, 0xFF);
/* Set up master (8259A-1) */
__RME_X64_Out(RME_X64_PIC1, 0x11);
__RME_X64_Out(RME_X64_PIC1+1, RME_X64_INT_USER(0));
__RME_X64_Out(RME_X64_PIC1+1, 1<<2);
__RME_X64_Out(RME_X64_PIC1+1, 0x3);
/* Set up slave (8259A-2) */
__RME_X64_Out(RME_X64_PIC2, 0x11);
__RME_X64_Out(RME_X64_PIC2+1, RME_X64_INT_USER(8));
__RME_X64_Out(RME_X64_PIC2+1, 2);
__RME_X64_Out(RME_X64_PIC2+1, 0x3);
__RME_X64_Out(RME_X64_PIC1, 0x68);
__RME_X64_Out(RME_X64_PIC1, 0x0A);
__RME_X64_Out(RME_X64_PIC2, 0x68);
__RME_X64_Out(RME_X64_PIC2, 0x0A);
/* Mask all interrupts - we do not use the PIC at all */
__RME_X64_Out(RME_X64_PIC1+1, 0xFF);
__RME_X64_Out(RME_X64_PIC2+1, 0xFF);
}
/* End Function:__RME_X64_PIC_Init *******************************************/
/* Begin Function:__RME_X64_IOAPIC_Int_Enable *********************************
Description : Enable a specific vector on one CPU.
Input : rme_ptr_t IRQ - The user vector to enable.
rme_ptr_t CPUID - The CPU to enable this IRQ on.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_IOAPIC_Int_Enable(rme_ptr_t IRQ, rme_ptr_t CPUID)
{
/* Mark interrupt edge-triggered, active high, enabled, and routed to the
* given cpunum, which happens to be that cpu's APIC ID. */
RME_X64_IOAPIC_WRITE(RME_X64_IOAPIC_REG_TABLE+(IRQ<<1),RME_X64_INT_USER(IRQ));
RME_X64_IOAPIC_WRITE(RME_X64_IOAPIC_REG_TABLE+(IRQ<<1)+1,CPUID<<24);
}
/* End Function:__RME_X64_IOAPIC_Int_Enable **********************************/
/* Begin Function:__RME_X64_IOAPIC_Int_Disable ********************************
Description : Disable a specific vector.
Input : rme_ptr_t IRQ - The user vector to enable.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_IOAPIC_Int_Disable(rme_ptr_t IRQ)
{
/* Mark interrupt edge-triggered, active high, enabled, and routed to the
* given cpunum, which happens to be that cpu's APIC ID. */
RME_X64_IOAPIC_WRITE(RME_X64_IOAPIC_REG_TABLE+(IRQ<<1),RME_X64_IOAPIC_INT_DISABLED|RME_X64_INT_USER(IRQ));
RME_X64_IOAPIC_WRITE(RME_X64_IOAPIC_REG_TABLE+(IRQ<<1)+1,0);
}
/* End Function:__RME_X64_IOAPIC_Int_Disable *********************************/
/* Begin Function:__RME_X64_IOAPIC_Init ***************************************
Description : Initialize IOAPIC controllers - this will be run once only.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_IOAPIC_Init(void)
{
rme_ptr_t Max_Int;
rme_ptr_t IOAPIC_ID;
rme_cnt_t Count;
/* IOAPIC initialization */
RME_X64_IOAPIC_READ(RME_X64_IOAPIC_REG_VER,Max_Int);
Max_Int=((Max_Int>>16)&0xFF);
RME_PRINTK_S("\n\rMax int is: ");
RME_PRINTK_I(Max_Int);
RME_X64_IOAPIC_READ(RME_X64_IOAPIC_REG_ID,IOAPIC_ID);
IOAPIC_ID>>=24;
/* This is not necessarily true when we have >1 IOAPICs */
/* RME_ASSERT(IOAPIC_ID==RME_X64_IOAPIC_Info[0].IOAPIC_ID); */
RME_PRINTK_S("\n\rIOAPIC ID is: ");
RME_PRINTK_I(IOAPIC_ID);
/* Disable all interrupts */
for(Count=0;Count<=Max_Int;Count++)
__RME_X64_IOAPIC_Int_Disable(Count);
}
/* End Function:__RME_X64_IOAPIC_Init ****************************************/
/* Begin Function:__RME_X64_SMP_Init ******************************************
Description : Start all other processors, one by one. We cannot start all of them
at once because of the stupid self modifying code of X64!
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_SMP_Init(void)
{
rme_u8_t* Code;
rme_cnt_t Count;
rme_u16_t* Warm_Reset;
/* Write entry code to unused memory at 0x7000 */
Code=(rme_u8_t*)RME_X64_PA2VA(0x7000);
for(Count=0;Count<sizeof(RME_X64_Boot_Code);Count++)
Code[Count]=RME_X64_Boot_Code[Count];
/* Start the CPUs one by one - the first one is ourself */
RME_X64_CPU_Cnt=1;
for(Count=1;Count<RME_X64_Num_CPU;Count++)
{
RME_PRINTK_S("\n\rBooting CPU ");
RME_PRINTK_I(Count);
/* Temporary stack */
*(rme_u32_t*)(Code-4)=0x8000;
*(rme_u32_t*)(Code-8)=RME_X64_TEXT_VA2PA(__RME_X64_SMP_Boot_32);
*(rme_ptr_t*)(Code-16)=RME_X64_KSTACK(Count);
/* Initialize CMOS shutdown code to 0AH */
__RME_X64_Out(RME_X64_RTC_CMD,0xF);
__RME_X64_Out(RME_X64_RTC_DATA,0xA);
/* Warm reset vector point to AP code */
Warm_Reset=(rme_u16_t*)RME_X64_PA2VA((0x40<<4|0x67));
Warm_Reset[0]=0;
Warm_Reset[1]=0x7000>>4;
/* Send INIT (level-triggered) interrupt to reset other CPU */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRHI, RME_X64_CPU_Info[Count].LAPIC_ID<<24);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRLO, RME_X64_LAPIC_ICRLO_INIT|
RME_X64_LAPIC_ICRLO_LEVEL|
RME_X64_LAPIC_ICRLO_ASSERT);
RME_X64_UDELAY(200);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRLO, RME_X64_LAPIC_ICRLO_INIT|
RME_X64_LAPIC_ICRLO_LEVEL);
RME_X64_UDELAY(10000);
/* Send startup IPI twice according to Intel manuals */
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRHI, RME_X64_CPU_Info[Count].LAPIC_ID<<24);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRLO, RME_X64_LAPIC_ICRLO_STARTUP|(0x7000>>12));
RME_X64_UDELAY(200);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRHI, RME_X64_CPU_Info[Count].LAPIC_ID<<24);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRLO, RME_X64_LAPIC_ICRLO_STARTUP|(0x7000>>12));
RME_X64_UDELAY(200);
/* Wait for CPU to finish its own initialization */
while(RME_X64_CPU_Info[RME_X64_CPU_Cnt].Boot_Done==0);
RME_X64_CPU_Cnt++;
}
}
/* End Function:__RME_X64_SMP_Init *******************************************/
/* Begin Function:__RME_X64_SMP_Tick ******************************************
Description : Send IPI to all other cores,to run their handler on the time.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_SMP_Tick(void)
{
/* Is this a SMP? */
if(RME_X64_Num_CPU>1)
{
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRHI, 0xFFULL<<24);
RME_X64_LAPIC_WRITE(RME_X64_LAPIC_ICRLO, RME_X64_LAPIC_ICRLO_EXC_SELF|
RME_X64_LAPIC_ICRLO_FIXED|
RME_X64_INT_SMP_SYSTICK);
}
}
/* End Function:__RME_X64_SMP_Tick *******************************************/
/* Begin Function:__RME_X64_Timer_Init ****************************************
Description : Initialize the on-board timer. We use the PIT because it is stable;
Then we let the main CPU send out timer IPI interrupts to all other
CPUs.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_X64_Timer_Init(void)
{
/* For timer interrupts, they will always be handled by core 1, and all the other
* cores should receive a IPI for that, so their scheduler can look after their
* threads. We are using square wave mode. */
__RME_X64_Out(RME_X64_PIT_CMD,0x34);
__RME_X64_Out(RME_X64_PIT_CH0,(1193182/2/RME_X64_TIMER_FREQ)&0xFF);
__RME_X64_Out(RME_X64_PIT_CH0,((1193182/2/RME_X64_TIMER_FREQ)>>8)&0xFF);
}
/* End Function:__RME_X64_Timer_Init *****************************************/
/* Begin Function:__RME_Low_Level_Init ****************************************
Description : Initialize the low-level hardware.
Input : None.
Output : None.
Return : rme_ptr_t - Always 0.
******************************************************************************/
rme_ptr_t __RME_Low_Level_Init(void)
{
/* We are here now ! */
__RME_X64_UART_Init();
/* Read APIC tables and detect the configurations. Now we are not NUMA-aware */
RME_ASSERT(__RME_X64_ACPI_Init()==0);
/* Detect CPU features */
__RME_X64_Feature_Get();
/* Extract memory specifications */
__RME_X64_Mem_Init(RME_X64_MBInfo->mmap_addr,RME_X64_MBInfo->mmap_length);
return 0;
}
/* End Function:__RME_Low_Level_Init *****************************************/
/* Begin Function:__RME_Pgtbl_Kmem_Init ***************************************
Description : Initialize the kernel mapping tables, so it can be added to all the
top-level page tables. Currently this have no consideration for >1TB
RAM, and is not NUMA-aware.
Input : None.
Output : None.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Kmem_Init(void)
{
rme_cnt_t PML4_Cnt;
rme_cnt_t PDP_Cnt;
rme_cnt_t PDE_Cnt;
rme_cnt_t Addr_Cnt;
struct __RME_X64_Pgreg* Pgreg;
struct __RME_X64_Mem* Mem;
/* Now initialize the kernel object allocation table */
_RME_Kotbl_Init(RME_X64_Layout.Kotbl_Size/sizeof(rme_ptr_t));
/* Reset PCID counter */
RME_X64_PCID_Inc=0;
/* And the page table registration table as well */
Pgreg=(struct __RME_X64_Pgreg*)RME_X64_Layout.Pgreg_Start;
for(PML4_Cnt=0;PML4_Cnt<RME_X64_Layout.Pgreg_Size/sizeof(struct __RME_X64_Pgreg);PML4_Cnt++)
{
Pgreg[PML4_Cnt].Child_Cnt=0;
Pgreg[PML4_Cnt].Parent_Cnt=0;
}
/* Create the frame for kernel page tables */
for(PML4_Cnt=0;PML4_Cnt<256;PML4_Cnt++)
{
RME_X64_Kpgt.PML4[PML4_Cnt]=RME_X64_MMU_ADDR(RME_X64_TEXT_VA2PA(&(RME_X64_Kpgt.PDP[PML4_Cnt][0])))|
RME_X64_MMU_KERN_PML4;
for(PDP_Cnt=0;PDP_Cnt<512;PDP_Cnt++)
RME_X64_Kpgt.PDP[PML4_Cnt][PDP_Cnt]=RME_X64_MMU_KERN_PDP;
}
/* Map in the first 4GB as linear mappings as always, 4 super pages, including the device hole.
* We need to detect whether the 1GB page is supported. If not, we just map the initial tables
* in, and we know where they are hard-coded in the assembly file */
if((RME_X64_EXT(RME_X64_CPUID_E1_INFO_FEATURE,3)&RME_X64_E1_EDX_PDPE1GB)!=0)
{
/* Can use 1GB pages */
RME_PRINTK_S("\n\rThis CPU have 1GB superpage support");
RME_X64_Kpgt.PDP[0][0]|=RME_X64_MMU_ADDR(0)|RME_X64_MMU_PDE_SUP|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[0][1]|=RME_X64_MMU_ADDR(RME_POW2(RME_PGTBL_SIZE_1G))|RME_X64_MMU_PDE_SUP|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[0][2]|=RME_X64_MMU_ADDR(2*RME_POW2(RME_PGTBL_SIZE_1G))|RME_X64_MMU_PDE_SUP|RME_X64_MMU_P;
/* We need to mark the device hole as unbufferable */
RME_X64_Kpgt.PDP[0][3]|=RME_X64_MMU_ADDR(3*RME_POW2(RME_PGTBL_SIZE_1G))|RME_X64_MMU_PDE_SUP|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[0][3]|=RME_X64_MMU_PWT|RME_X64_MMU_PCD;
/* Map the first 2GB to the last position too, where the kernel text segment is at */
RME_X64_Kpgt.PDP[255][510]|=RME_X64_MMU_ADDR(0)|RME_X64_MMU_PDE_SUP|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[255][511]|=RME_X64_MMU_ADDR(RME_POW2(RME_PGTBL_SIZE_1G))|RME_X64_MMU_PDE_SUP|RME_X64_MMU_P;
}
else
{
RME_PRINTK_S("\n\rThis CPU do not have 1GB superpage support");
/* Cannot use 1GB pages, we revert to 2MB pages used during kernel startup */
RME_X64_Kpgt.PDP[0][0]|=0x104000|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[0][1]|=0x105000|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[0][2]|=0x106000|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[0][3]|=0x107000|RME_X64_MMU_PCD|RME_X64_MMU_PWT|RME_X64_MMU_P;
/* Map the first 2GB to the last position too, where the kernel text segment is at */
RME_X64_Kpgt.PDP[255][510]|=0x104000|RME_X64_MMU_P;
RME_X64_Kpgt.PDP[255][511]|=0x105000|RME_X64_MMU_P;
}
/* Ignore all memory below 4G, but we need to get the size of such memory above 16MB */
Mem=(struct __RME_X64_Mem*)RME_X64_Phys_Mem.Next;
while(Mem!=(struct __RME_X64_Mem*)(&RME_X64_Phys_Mem))
{
/* See if this memory segment passes 16MB limit */
if((Mem->Start_Addr+Mem->Length)<=RME_POW2(RME_PGTBL_SIZE_16M))
Mem=(struct __RME_X64_Mem*)(Mem->Head.Next);
else
break;
}
/* The first Kmem1 trunk must start at smaller or equal to 16MB */
RME_ASSERT(Mem->Start_Addr<=RME_POW2(RME_PGTBL_SIZE_16M));
/* The raw sizes of kernel memory segment 1 - per CPU area is already aligned so no need to align again */
RME_X64_Layout.Kmem1_Start[0]=RME_X64_Layout.PerCPU_Start+RME_X64_Layout.PerCPU_Size;
RME_X64_Layout.Kmem1_Size[0]=Mem->Start_Addr+Mem->Length-RME_POW2(RME_PGTBL_SIZE_16M)-
RME_X64_VA2PA(RME_X64_Layout.Kmem1_Start[0]);
/* Add the rest of Kmem1 into the array */
Addr_Cnt=1;
while(Mem!=(struct __RME_X64_Mem*)(&RME_X64_Phys_Mem))
{
/* Add all segments under 4GB to Kmem1 */
Mem=(struct __RME_X64_Mem*)(Mem->Head.Next);
/* If detected anything above 4GB, then this is not Kmem1, exiting */
if(Mem->Start_Addr>=RME_POW2(RME_PGTBL_SIZE_4G))
break;
/* If this memory trunk have less than 4MB, drop it */
if(Mem->Length<RME_POW2(RME_PGTBL_SIZE_4M))
{
RME_PRINTK_S("\n\rAbandoning physical memory below 4G: addr 0x");
RME_PRINTK_U(Mem->Start_Addr);
RME_PRINTK_S(", length 0x");
RME_PRINTK_U(Mem->Length);
continue;
}
if(Addr_Cnt>=RME_X64_KMEM1_MAXSEGS)
{
RME_PRINTK_S("\r\nThe memory under 4G is too fragmented. Aborting.");
RME_ASSERT(0);
}
RME_X64_Layout.Kmem1_Start[Addr_Cnt]=RME_X64_PA2VA(RME_ROUND_UP(Mem->Start_Addr,RME_PGTBL_SIZE_2M));
RME_X64_Layout.Kmem1_Size[Addr_Cnt]=RME_ROUND_DOWN(Mem->Length,RME_PGTBL_SIZE_2M);
Addr_Cnt++;
}
RME_X64_Layout.Kmem1_Trunks=Addr_Cnt;
/* This is the hole */
RME_X64_Layout.Hole_Start=RME_X64_Layout.Kmem1_Start[Addr_Cnt-1]+RME_X64_Layout.Kmem1_Size[Addr_Cnt-1];
RME_X64_Layout.Hole_Size=RME_POW2(RME_PGTBL_SIZE_4G)-RME_X64_VA2PA(RME_X64_Layout.Hole_Start);
/* Create kernel page mappings for memory above 4GB - we assume only one segment below 4GB */
RME_X64_Layout.Kpgtbl_Start=RME_X64_Layout.Kmem1_Start[0];
RME_X64_Layout.Kmem2_Start=RME_X64_PA2VA(RME_POW2(RME_PGTBL_SIZE_4G));
RME_X64_Layout.Kmem2_Size=0;
/* We have filled the first 4 1GB superpages */
PML4_Cnt=0;
PDP_Cnt=3;
PDE_Cnt=511;
while(Mem!=(struct __RME_X64_Mem*)(&RME_X64_Phys_Mem))
{
/* Throw away small segments */
if(Mem->Length<2*RME_POW2(RME_PGTBL_SIZE_2M))
{
RME_PRINTK_S("\n\rAbandoning physical memory above 4G: addr 0x");
RME_PRINTK_U(Mem->Start_Addr);
RME_PRINTK_S(", length 0x");
RME_PRINTK_U(Mem->Length);
Mem=(struct __RME_X64_Mem*)(Mem->Head.Next);
continue;
}
/* Align the memory segment to 2MB */
Mem->Start_Addr=RME_ROUND_UP(Mem->Start_Addr,RME_PGTBL_SIZE_2M);
Mem->Length=RME_ROUND_DOWN(Mem->Length-1,RME_PGTBL_SIZE_2M);
/* Add these pages into the kernel at addresses above 4GB offset as 2MB pages */
for(Addr_Cnt=0;Addr_Cnt<Mem->Length;Addr_Cnt+=RME_POW2(RME_PGTBL_SIZE_2M))
{
PDE_Cnt++;
if(PDE_Cnt==512)
{
PDE_Cnt=0;
PDP_Cnt++;
if(PDP_Cnt==512)
{
PDP_Cnt=0;
PML4_Cnt++;
}
/* Map this PDE into the PDP */
RME_X64_Kpgt.PDP[PML4_Cnt][PDP_Cnt]|=RME_X64_MMU_ADDR(RME_X64_VA2PA(RME_X64_Layout.Kmem1_Start[0]))|RME_X64_MMU_P;
}
((rme_ptr_t*)(RME_X64_Layout.Kmem1_Start[0]))[0]=RME_X64_MMU_ADDR(Mem->Start_Addr+Addr_Cnt)|RME_X64_MMU_KERN_PDE;
RME_X64_Layout.Kmem1_Start[0]+=sizeof(rme_ptr_t);
RME_X64_Layout.Kmem1_Size[0]-=sizeof(rme_ptr_t);
RME_X64_Layout.Kmem2_Size+=RME_POW2(RME_PGTBL_SIZE_2M);
}
Mem=(struct __RME_X64_Mem*)(Mem->Head.Next);
}
/* Copy the new page tables to the temporary entries, so that we can boot SMP */
for(PML4_Cnt=0;PML4_Cnt<256;PML4_Cnt++)
((rme_ptr_t*)RME_X64_PA2VA(0x101000))[PML4_Cnt+256]=RME_X64_Kpgt.PML4[PML4_Cnt];
/* Page table allocation finished. Now need to align Kmem1 to 2MB page boundary */
RME_X64_Layout.Kmem1_Start[0]=RME_ROUND_UP(RME_X64_Layout.Kmem1_Start[0],RME_PGTBL_SIZE_2M);
RME_X64_Layout.Kmem1_Size[0]=RME_ROUND_DOWN(RME_X64_Layout.Kmem1_Size[0]-1,RME_PGTBL_SIZE_2M);
/* All memory is mapped. Now figure out the size of kernel stacks */
RME_X64_Layout.Kpgtbl_Size=RME_X64_Layout.Kmem1_Start[0]-RME_X64_Layout.Kpgtbl_Start;
/* See if we are allocating the stack from Kmem2 or Kmem1 */
if(RME_X64_Layout.Kmem2_Size==0)
{
RME_X64_Layout.Stack_Start=RME_ROUND_DOWN(RME_X64_Layout.Kmem1_Start[0]+RME_X64_Layout.Kmem1_Size[0]-1,RME_X64_KSTACK_ORDER);
RME_X64_Layout.Stack_Start-=RME_X64_Layout.Stack_Size;
RME_X64_Layout.Kmem1_Size[0]=RME_X64_Layout.Stack_Start-RME_X64_Layout.Kmem1_Start[0];
}
else
{
RME_X64_Layout.Stack_Start=RME_ROUND_DOWN(RME_X64_Layout.Kmem2_Start+RME_X64_Layout.Kmem2_Size-1,RME_X64_KSTACK_ORDER);
RME_X64_Layout.Stack_Start-=RME_X64_Layout.Stack_Size;
RME_X64_Layout.Kmem2_Size=RME_X64_Layout.Stack_Start-RME_X64_Layout.Kmem2_Start;
}
/* Now report all mapping info */
RME_PRINTK_S("\n\r\n\rKotbl_Start: 0x");
RME_PRINTK_U(RME_X64_Layout.Kotbl_Start);
RME_PRINTK_S("\n\rKotbl_Size: 0x");
RME_PRINTK_U(RME_X64_Layout.Kotbl_Size);
RME_PRINTK_S("\n\rPgreg_Start: 0x");
RME_PRINTK_U(RME_X64_Layout.Pgreg_Start);
RME_PRINTK_S("\n\rPgreg_Size: 0x");
RME_PRINTK_U(RME_X64_Layout.Pgreg_Size);
RME_PRINTK_S("\n\rPerCPU_Start: 0x");
RME_PRINTK_U(RME_X64_Layout.PerCPU_Start);
RME_PRINTK_S("\n\rPerCPU_Size: 0x");
RME_PRINTK_U(RME_X64_Layout.PerCPU_Size);
RME_PRINTK_S("\n\rKpgtbl_Start: 0x");
RME_PRINTK_U(RME_X64_Layout.Kpgtbl_Start);
RME_PRINTK_S("\n\rKpgtbl_Size: 0x");
RME_PRINTK_U(RME_X64_Layout.Kpgtbl_Size);
for(Addr_Cnt=0;Addr_Cnt<RME_X64_Layout.Kmem1_Trunks;Addr_Cnt++)
{
RME_PRINTK_S("\n\rKmem1_Start[");
RME_PRINTK_I(Addr_Cnt);
RME_PRINTK_S("]: 0x");
RME_PRINTK_U(RME_X64_Layout.Kmem1_Start[Addr_Cnt]);
RME_PRINTK_S("\n\rKmem1_Size[");
RME_PRINTK_I(Addr_Cnt);
RME_PRINTK_S("]: 0x");
RME_PRINTK_U(RME_X64_Layout.Kmem1_Size[Addr_Cnt]);
}
RME_PRINTK_S("\n\rHole_Start: 0x");
RME_PRINTK_U(RME_X64_Layout.Hole_Start);
RME_PRINTK_S("\n\rHole_Size: 0x");
RME_PRINTK_U(RME_X64_Layout.Hole_Size);
RME_PRINTK_S("\n\rKmem2_Start: 0x");
RME_PRINTK_U(RME_X64_Layout.Kmem2_Start);
RME_PRINTK_S("\n\rKmem2_Size: 0x");
RME_PRINTK_U(RME_X64_Layout.Kmem2_Size);
RME_PRINTK_S("\n\rStack_Start: 0x");
RME_PRINTK_U(RME_X64_Layout.Stack_Start);
RME_PRINTK_S("\n\rStack_Size: 0x");
RME_PRINTK_U(RME_X64_Layout.Stack_Size);
return 0;
}
/* End Function:__RME_Pgtbl_Kmem_Init ****************************************/
/* Begin Function:__RME_SMP_Low_Level_Init ************************************
Description : Low-level initialization for all other cores.
Input : None.
Output : None.
Return : None.
******************************************************************************/
rme_ptr_t __RME_SMP_Low_Level_Init(void)
{
struct RME_CPU_Local* CPU_Local;
/* Initialize all vector tables */
__RME_X64_CPU_Local_Init();
/* Initialize LAPIC */
__RME_X64_LAPIC_Init();
/* Check to see if we are booting this correctly */
CPU_Local=RME_CPU_LOCAL();
RME_ASSERT(CPU_Local->CPUID==RME_X64_CPU_Cnt);
RME_X64_CPU_Info[RME_X64_CPU_Cnt].Boot_Done=1;
/* Spin until the global CPU counter is zero again, which means the booting
* processor has done booting and we can proceed now */
while(RME_X64_CPU_Cnt!=0);
/* The booting CPU must have created everything necessary for us. Let's
* check to see if they are there. */
RME_ASSERT(CPU_Local->Cur_Thd!=0);
RME_ASSERT(CPU_Local->Tick_Sig!=0);
RME_ASSERT(CPU_Local->Vect_Sig!=0);
/* Change page tables */
__RME_Pgtbl_Set(RME_CAP_GETOBJ((CPU_Local->Cur_Thd)->Sched.Proc->Pgtbl,rme_ptr_t));
/* Boot into the init thread - never returns */
__RME_Enter_User_Mode(0, RME_X64_USTACK(CPU_Local->CPUID), CPU_Local->CPUID);
return 0;
}
/* End Function:__RME_SMP_Low_Level_Init *************************************/
/* Begin Function:__RME_Boot **************************************************
Description : Boot the first process in the system.
Input : None.
Output : None.
Return : rme_ptr_t - Always 0.
******************************************************************************/
rme_ptr_t __RME_Boot(void)
{
rme_ptr_t Cur_Addr;
rme_cnt_t Count;
rme_cnt_t Kmem1_Cnt;
rme_ptr_t Phys_Addr;
rme_ptr_t Page_Ptr;
struct RME_Cap_Captbl* Captbl;
struct RME_CPU_Local* CPU_Local;
/* Initialize our own CPU-local data structures */
RME_X64_CPU_Cnt=0;
RME_PRINTK_S("\r\nCPU 0 local IDT/GDT init");
__RME_X64_CPU_Local_Init();
/* Initialize interrupt controllers (PIC, LAPIC, IOAPIC) */
RME_PRINTK_S("\r\nCPU 0 LAPIC init");
__RME_X64_LAPIC_Init();
RME_PRINTK_S("\r\nPIC init");
__RME_X64_PIC_Init();
RME_PRINTK_S("\r\nIOAPIC init");
__RME_X64_IOAPIC_Init();
/* Start other processors, if there are any. They will keep spinning until
* the booting processor finish all its work. */
__RME_X64_SMP_Init();
/* Create all initial tables in Kmem1, which is sure to be present. We reserve 16
* pages at the start to load the init process */
Cur_Addr=RME_X64_Layout.Kmem1_Start[0]+16*RME_POW2(RME_PGTBL_SIZE_2M);
RME_PRINTK_S("\r\nKotbl registration start offset: 0x");
RME_PRINTK_U(((Cur_Addr-RME_KMEM_VA_START)>>RME_KMEM_SLOT_ORDER)/8);
/* Create the capability table for the init process - always 16 */
Captbl=(struct RME_Cap_Captbl*)Cur_Addr;
RME_ASSERT(_RME_Captbl_Boot_Init(RME_BOOT_CAPTBL,Cur_Addr,16)==RME_BOOT_CAPTBL);
Cur_Addr+=RME_KOTBL_ROUND(RME_CAPTBL_SIZE(16));
/* Create the capability table for initial page tables - now we are only
* adding 2MB pages. There will be 1 PML4, 16 PDP, and 16*512=8192 PGD.
* This should provide support for up to 4TB of memory, which will be sufficient
* for at least a decade. These data structures will eat 32MB of memory, which
* is fine */
RME_ASSERT(_RME_Captbl_Boot_Crt(RME_X64_CPT, RME_BOOT_CAPTBL, RME_BOOT_TBL_PGTBL, Cur_Addr, 1+16+8192)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_CAPTBL_SIZE(1+16+8192));
/* Align the address to 4096 to prepare for page table creation */
Cur_Addr=RME_ROUND_UP(Cur_Addr,12);
/* Create PML4 */
RME_ASSERT(_RME_Pgtbl_Boot_Crt(RME_X64_CPT, RME_BOOT_TBL_PGTBL, RME_BOOT_PML4,
Cur_Addr, 0, RME_PGTBL_TOP, RME_PGTBL_SIZE_512G, RME_PGTBL_NUM_512)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_PGTBL_SIZE_TOP(RME_PGTBL_NUM_512));
/* Create all our 16 PDPs, and cons them into the PML4 */
for(Count=0;Count<16;Count++)
{
RME_ASSERT(_RME_Pgtbl_Boot_Crt(RME_X64_CPT, RME_BOOT_TBL_PGTBL, RME_BOOT_PDP(Count),
Cur_Addr, 0, RME_PGTBL_NOM, RME_PGTBL_SIZE_1G, RME_PGTBL_NUM_512)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_PGTBL_SIZE_NOM(RME_PGTBL_NUM_512));
RME_ASSERT(_RME_Pgtbl_Boot_Con(RME_X64_CPT, RME_CAPID(RME_BOOT_TBL_PGTBL,RME_BOOT_PML4), Count,
RME_CAPID(RME_BOOT_TBL_PGTBL,RME_BOOT_PDP(Count)), RME_PGTBL_ALL_PERM)==0);
}
/* Create 8192 PDEs, and cons them into their respective PDPs */
for(Count=0;Count<8192;Count++)
{
RME_ASSERT(_RME_Pgtbl_Boot_Crt(RME_X64_CPT, RME_BOOT_TBL_PGTBL, RME_BOOT_PDE(Count),
Cur_Addr, 0, RME_PGTBL_NOM, RME_PGTBL_SIZE_2M, RME_PGTBL_NUM_512)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_PGTBL_SIZE_NOM(RME_PGTBL_NUM_512));
RME_ASSERT(_RME_Pgtbl_Boot_Con(RME_X64_CPT, RME_CAPID(RME_BOOT_TBL_PGTBL,RME_BOOT_PDP(Count>>9)), Count&0x1FF,
RME_CAPID(RME_BOOT_TBL_PGTBL,RME_BOOT_PDE(Count)), RME_PGTBL_ALL_PERM)==0);
}
/* Map all the Kmem1 that we have into it */
Page_Ptr=0;
for(Kmem1_Cnt=0;Kmem1_Cnt<RME_X64_Layout.Kmem1_Trunks;Kmem1_Cnt++)
{
for(Count=0;Count<RME_X64_Layout.Kmem1_Size[Kmem1_Cnt];Count+=RME_POW2(RME_PGTBL_SIZE_2M))
{
Phys_Addr=RME_X64_VA2PA(RME_X64_Layout.Kmem1_Start[Kmem1_Cnt])+Count;
RME_ASSERT(_RME_Pgtbl_Boot_Add(RME_X64_CPT, RME_CAPID(RME_BOOT_TBL_PGTBL,RME_BOOT_PDE(Page_Ptr>>9)),
Phys_Addr, Page_Ptr&0x1FF, RME_PGTBL_ALL_PERM)==0);
Page_Ptr++;
}
}
RME_PRINTK_S("\r\nKmem1 pages: 0x");
RME_PRINTK_U(Page_Ptr);
RME_PRINTK_S(", [0x0, 0x");
RME_PRINTK_U(Page_Ptr*RME_POW2(RME_PGTBL_SIZE_2M)+RME_POW2(RME_PGTBL_SIZE_2M)-1);
RME_PRINTK_S("]");
/* Map the Kmem2 in - don't want lookups, we know where they are. Offset by 2048 because they are mapped above 4G */
RME_PRINTK_S("\r\nKmem2 pages: 0x");
RME_PRINTK_U(RME_X64_Layout.Kmem2_Size/RME_POW2(RME_PGTBL_SIZE_2M));
RME_PRINTK_S(", [0x");
RME_PRINTK_U(Page_Ptr*RME_POW2(RME_PGTBL_SIZE_2M)+RME_POW2(RME_PGTBL_SIZE_2M));
RME_PRINTK_S(", 0x");
for(Count=2048;Count<(RME_X64_Layout.Kmem2_Size/RME_POW2(RME_PGTBL_SIZE_2M)+2048);Count++)
{
Phys_Addr=RME_X64_PA2VA(RME_X64_MMU_ADDR(RME_X64_Kpgt.PDP[Count>>18][(Count>>9)&0x1FF]));
Phys_Addr=RME_X64_MMU_ADDR(((rme_ptr_t*)Phys_Addr)[Count&0x1FF]);
RME_ASSERT(_RME_Pgtbl_Boot_Add(RME_X64_CPT, RME_CAPID(RME_BOOT_TBL_PGTBL,RME_BOOT_PDE(Page_Ptr>>9)),
Phys_Addr, Page_Ptr&0x1FF, RME_PGTBL_ALL_PERM)==0);
Page_Ptr++;
}
RME_PRINTK_U(Page_Ptr*RME_POW2(RME_PGTBL_SIZE_2M)+RME_POW2(RME_PGTBL_SIZE_2M)-1);
RME_PRINTK_S("]");
/* Activate the first process - This process cannot be deleted */
RME_ASSERT(_RME_Proc_Boot_Crt(RME_X64_CPT, RME_BOOT_CAPTBL, RME_BOOT_INIT_PROC,
RME_BOOT_CAPTBL, RME_CAPID(RME_BOOT_TBL_PGTBL,RME_BOOT_PML4), Cur_Addr)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_PROC_SIZE);
/* Create the initial kernel function capability */
RME_ASSERT(_RME_Kern_Boot_Crt(RME_X64_CPT, RME_BOOT_CAPTBL, RME_BOOT_INIT_KERN)==0);
/* Create a capability table for initial kernel memory capabilities. We need a few for Kmem1, and another one for Kmem2 */
RME_ASSERT(_RME_Captbl_Boot_Crt(RME_X64_CPT, RME_BOOT_CAPTBL, RME_BOOT_TBL_KMEM, Cur_Addr, RME_X64_KMEM1_MAXSEGS+1)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_CAPTBL_SIZE(RME_X64_KMEM1_MAXSEGS+1));
/* Create Kmem1 capabilities - can create page tables here */
for(Count=0;Count<RME_X64_Layout.Kmem1_Trunks;Count++)
{
RME_ASSERT(_RME_Kmem_Boot_Crt(RME_X64_CPT,
RME_BOOT_TBL_KMEM, Count,
RME_X64_Layout.Kmem1_Start[Count],
RME_X64_Layout.Kmem1_Start[Count]+RME_X64_Layout.Kmem1_Size[Count],
RME_KMEM_FLAG_CAPTBL|RME_KMEM_FLAG_PGTBL|RME_KMEM_FLAG_PROC|
RME_KMEM_FLAG_THD|RME_KMEM_FLAG_SIG|RME_KMEM_FLAG_INV)==0);
}
/* Create Kmem2 capability - cannot create page tables here */
RME_ASSERT(_RME_Kmem_Boot_Crt(RME_X64_CPT,
RME_BOOT_TBL_KMEM, RME_X64_KMEM1_MAXSEGS,
RME_X64_Layout.Kmem2_Start,
RME_X64_Layout.Kmem2_Start+RME_X64_Layout.Kmem2_Size,
RME_KMEM_FLAG_CAPTBL|RME_KMEM_FLAG_PROC|
RME_KMEM_FLAG_THD|RME_KMEM_FLAG_SIG|RME_KMEM_FLAG_INV)==0);
/* Create the initial kernel endpoints for timer ticks */
RME_ASSERT(_RME_Captbl_Boot_Crt(RME_X64_CPT, RME_BOOT_CAPTBL, RME_BOOT_TBL_TIMER, Cur_Addr, RME_X64_Num_CPU)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_CAPTBL_SIZE(RME_X64_Num_CPU));
for(Count=0;Count<RME_X64_Num_CPU;Count++)
{
CPU_Local=__RME_X64_CPU_Local_Get_By_CPUID(Count);
CPU_Local->Tick_Sig=(struct RME_Sig_Struct*)Cur_Addr;
RME_ASSERT(_RME_Sig_Boot_Crt(RME_X64_CPT, RME_BOOT_TBL_TIMER, Count, Cur_Addr)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_SIG_SIZE);
}
/* Create the initial kernel endpoints for all other interrupts */
RME_ASSERT(_RME_Captbl_Boot_Crt(RME_X64_CPT, RME_BOOT_CAPTBL, RME_BOOT_TBL_INT, Cur_Addr, RME_X64_Num_CPU)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_CAPTBL_SIZE(RME_X64_Num_CPU));
for(Count=0;Count<RME_X64_Num_CPU;Count++)
{
CPU_Local=__RME_X64_CPU_Local_Get_By_CPUID(Count);
CPU_Local->Vect_Sig=(struct RME_Sig_Struct*)Cur_Addr;
RME_ASSERT(_RME_Sig_Boot_Crt(RME_X64_CPT, RME_BOOT_TBL_INT, Count, Cur_Addr)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_SIG_SIZE);
}
/* Activate the first thread, and set its priority */
RME_ASSERT(_RME_Captbl_Boot_Crt(RME_X64_CPT, RME_BOOT_CAPTBL, RME_BOOT_TBL_THD, Cur_Addr, RME_X64_Num_CPU)==0);
Cur_Addr+=RME_KOTBL_ROUND(RME_CAPTBL_SIZE(RME_X64_Num_CPU));
for(Count=0;Count<RME_X64_Num_CPU;Count++)
{
CPU_Local=__RME_X64_CPU_Local_Get_By_CPUID(Count);
RME_ASSERT(_RME_Thd_Boot_Crt(RME_X64_CPT, RME_BOOT_TBL_THD, Count, RME_BOOT_INIT_PROC, Cur_Addr, 0, CPU_Local)>=0);
Cur_Addr+=RME_KOTBL_ROUND(RME_THD_SIZE);
}
RME_PRINTK_S("\r\nKotbl registration end offset: 0x");
RME_PRINTK_U(((Cur_Addr-RME_KMEM_VA_START)>>RME_KMEM_SLOT_ORDER)/8);
RME_PRINTK_S("\r\nKmem1 frontier: 0x");
RME_PRINTK_U(Cur_Addr);
/* Print sizes and halt */
RME_PRINTK_S("\r\nThread object size: ");
RME_PRINTK_I(sizeof(struct RME_Thd_Struct)/sizeof(rme_ptr_t));
RME_PRINTK_S("\r\nProcess object size: ");
RME_PRINTK_I(sizeof(struct RME_Proc_Struct)/sizeof(rme_ptr_t));
RME_PRINTK_S("\r\nInvocation object size: ");
RME_PRINTK_I(sizeof(struct RME_Inv_Struct)/sizeof(rme_ptr_t));
RME_PRINTK_S("\r\nEndpoint object size: ");
RME_PRINTK_I(sizeof(struct RME_Sig_Struct)/sizeof(rme_ptr_t));
/* Initialize the timer and start its interrupt routing */
RME_PRINTK_S("\r\nTimer init\r\n");
__RME_X64_Timer_Init();
//__RME_X64_IOAPIC_Int_Enable(2,0);
/* Change page tables */
__RME_Pgtbl_Set(RME_CAP_GETOBJ((RME_CPU_LOCAL()->Cur_Thd)->Sched.Proc->Pgtbl,rme_ptr_t));
/* Load the init process to address 0x00 - It should be smaller than 2MB */
extern const unsigned char UVM_Init[];
_RME_Memcpy(0,(void*)UVM_Init,RME_POW2(RME_PGTBL_SIZE_2M));
/* Now other non-booting processors may proceed and go into their threads */
RME_X64_CPU_Cnt=0;
/* Boot into the init thread */
__RME_Enter_User_Mode(0, RME_X64_USTACK(0), 0);
return 0;
}
/* End Function:__RME_Boot ***************************************************/
/* Begin Function:__RME_Reboot ************************************************
Description : Reboot the machine, abandon all operating system states.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_Reboot(void)
{
/* Currently we cannot parse th FADT yet. We need these info to shutdown the machine */
/* outportb(FADT->ResetReg.Address, FADT->ResetValue); */
RME_ASSERT(RME_WORD_BITS!=RME_POW2(RME_WORD_ORDER));
}
/* End Function:__RME_Reboot *************************************************/
/* Begin Function:__RME_Shutdown **********************************************
Description : Shutdown the machine, abandon all operating system states.
Input : None.
Output : None.
Return : None.
******************************************************************************/
void __RME_Shutdown(void)
{
/* Currently we cannot parse th DSDT yet. We need these info to shutdown the machine */
/* outw(PM1a_CNT,SLP_TYPa|SLP_EN) */
RME_ASSERT(RME_WORD_BITS!=RME_POW2(RME_WORD_ORDER));
}
/* End Function:__RME_Shutdown ***********************************************/
/* Begin Function:__RME_Get_Syscall_Param *************************************
Description : Get the system call parameters from the stack frame.
Input : struct RME_Reg_Struct* Reg - The register set.
Output : rme_ptr_t* Svc - The system service number.
rme_ptr_t* Capid - The capability ID number.
rme_ptr_t* Param - The parameters.
Return : None.
******************************************************************************/
void __RME_Get_Syscall_Param(struct RME_Reg_Struct* Reg, rme_ptr_t* Svc, rme_ptr_t* Capid, rme_ptr_t* Param)
{
*Svc=(Reg->RDI)>>32;
*Capid=(Reg->RDI)&0xFFFFFFFF;
Param[0]=Reg->RSI;
Param[1]=Reg->RDX;
Param[2]=Reg->R8;
}
/* End Function:__RME_Get_Syscall_Param **************************************/
/* Begin Function:__RME_Set_Syscall_Retval ************************************
Description : Set the system call return value to the stack frame. This function
may carry up to 4 return values. If the last 3 is not needed, just set
them to zero.
Input : rme_ret_t Retval - The return value.
Output : struct RME_Reg_Struct* Reg - The register set.
Return : None.
******************************************************************************/
void __RME_Set_Syscall_Retval(struct RME_Reg_Struct* Reg, rme_ret_t Retval)
{
Reg->RAX=(rme_ptr_t)Retval;
}
/* End Function:__RME_Set_Syscall_Retval *************************************/
/* Begin Function:__RME_Thd_Reg_Init ******************************************
Description : Initialize the register set for the thread.
Input : rme_ptr_t Entry - The thread entry address.
rme_ptr_t Stack - The thread stack address.
rme_ptr_t Param - The parameter to pass to it.
Output : struct RME_Reg_Struct* Reg - The register set content generated.
Return : None.
******************************************************************************/
void __RME_Thd_Reg_Init(rme_ptr_t Entry, rme_ptr_t Stack, rme_ptr_t Param, struct RME_Reg_Struct* Reg)
{
/* We use the SYSRET path on creation if possible */
Reg->INT_NUM=0x10000;
Reg->ERROR_CODE=0;
Reg->RIP=Entry;
Reg->CS=RME_X64_SEG_USER_CODE;
/* IOPL 3, IF */
Reg->RFLAGS=0x3200;
Reg->RSP=Stack;
Reg->SS=RME_X64_SEG_USER_DATA;
/* Pass the parameter */
Reg->RDI=Param;
}
/* End Function:__RME_Thd_Reg_Init *******************************************/
/* Begin Function:__RME_Thd_Reg_Copy ******************************************
Description : Copy one set of registers into another.
Input : struct RME_Reg_Struct* Src - The source register set.
Output : struct RME_Reg_Struct* Dst - The destination register set.
Return : None.
******************************************************************************/
void __RME_Thd_Reg_Copy(struct RME_Reg_Struct* Dst, struct RME_Reg_Struct* Src)
{
/* Make sure that the ordering is the same so the compiler can optimize */
Dst->RAX=Src->RAX;
Dst->RBX=Src->RBX;
Dst->RCX=Src->RCX;
Dst->RDX=Src->RDX;
Dst->RSI=Src->RSI;
Dst->RDI=Src->RDI;
Dst->RBP=Src->RBP;
Dst->R8=Src->R8;
Dst->R9=Src->R9;
Dst->R10=Src->R10;
Dst->R11=Src->R11;
Dst->R12=Src->R12;
Dst->R13=Src->R13;
Dst->R14=Src->R14;
Dst->R15=Src->R15;
/* Don't worry about user modifying INTNUM. If he or she did that it will corrupt userspace */
Dst->INT_NUM=Src->INT_NUM;
Dst->ERROR_CODE=Src->ERROR_CODE;
/* This will always be canonical upon SYSRET, because we will truncate in on return */
Dst->RIP=Src->RIP;
Dst->CS=Src->CS;
Dst->RFLAGS=Src->RFLAGS;
Dst->RSP=Src->RSP;
Dst->SS=Src->SS;
}
/* End Function:__RME_Thd_Reg_Copy *******************************************/
/* Begin Function:__RME_Thd_Cop_Init ******************************************
Description : Initialize the coprocessor register set for the thread.
Input : struct RME_Reg_Struct* Reg - The register struct to help initialize the coprocessor.
Output : struct RME_Reg_Cop_Struct* Cop_Reg - The register set content generated.
Return : None.
******************************************************************************/
void __RME_Thd_Cop_Init(struct RME_Reg_Struct* Reg, struct RME_Cop_Struct* Cop_Reg)
{
/* Empty function, return immediately. The FPU contents is not predictable */
}
/* End Function:__RME_Thd_Cop_Reg_Init ***************************************/
/* Begin Function:__RME_Thd_Cop_Save ******************************************
Description : Save the co-op register sets. This operation is flexible - If the
program does not use the FPU, we do not save its context.
Input : struct RME_Reg_Struct* Reg - The context, used to decide whether
to save the context of the coprocessor.
Output : struct RME_Cop_Struct* Cop_Reg - The pointer to the coprocessor contents.
Return : None.
******************************************************************************/
void __RME_Thd_Cop_Save(struct RME_Reg_Struct* Reg, struct RME_Cop_Struct* Cop_Reg)
{
/* Not used for now */
}
/* End Function:__RME_Thd_Cop_Save *******************************************/
/* Begin Function:__RME_Thd_Cop_Restore ***************************************
Description : Restore the co-op register sets. This operation is flexible - If the
FPU is not used, we do not restore its context.
Input : struct RME_Reg_Struct* Reg - The context, used to decide whether
to save the context of the coprocessor.
Output : struct RME_Cop_Struct* Cop_Reg - The pointer to the coprocessor contents.
Return : None.
******************************************************************************/
void __RME_Thd_Cop_Restore(struct RME_Reg_Struct* Reg, struct RME_Cop_Struct* Cop_Reg)
{
/* Not used for now */
}
/* End Function:__RME_Thd_Cop_Restore ****************************************/
/* Begin Function:__RME_Inv_Reg_Save ******************************************
Description : Save the necessary registers on invocation for returning. Only the
registers that will influence program control flow will be saved.
Input : struct RME_Reg_Struct* Reg - The register set.
Output : struct RME_Iret_Struct* Ret - The invocation return register context.
Return : None.
******************************************************************************/
void __RME_Inv_Reg_Save(struct RME_Iret_Struct* Ret, struct RME_Reg_Struct* Reg)
{
Ret->RIP=Reg->RIP;
Ret->RSP=Reg->RSP;
}
/* End Function:__RME_Inv_Reg_Save *******************************************/
/* Begin Function:__RME_Inv_Reg_Restore ***************************************
Description : Restore the necessary registers for returning from an invocation.
Input : struct RME_Iret_Struct* Ret - The invocation return register context.
Output : struct RME_Reg_Struct* Reg - The register set.
Return : None.
******************************************************************************/
void __RME_Inv_Reg_Restore(struct RME_Reg_Struct* Reg, struct RME_Iret_Struct* Ret)
{
Reg->RIP=Ret->RIP;
Reg->RSP=Ret->RSP;
}
/* End Function:__RME_Inv_Reg_Restore ****************************************/
/* Begin Function:__RME_Set_Inv_Retval ****************************************
Description : Set the invocation return value to the stack frame.
Input : rme_ret_t Retval - The return value.
Output : struct RME_Reg_Struct* Reg - The register set.
Return : None.
******************************************************************************/
void __RME_Set_Inv_Retval(struct RME_Reg_Struct* Reg, rme_ret_t Retval)
{
Reg->RDI=(rme_ptr_t)Retval;
}
/* End Function:__RME_Set_Inv_Retval *****************************************/
void NDBG(void)
{
write_string( 0x07, "Here", 0);
}
/* Crap for test */
void write_string( int colour, const char *string, rme_ptr_t pos)
{
volatile char *video = (volatile char*)RME_X64_PA2VA(pos+0xB8000);
while( *string != 0 )
{
*video++ = *string++;
*video++ = colour;
}
}
/* Begin Function:__RME_Kern_Func_Handler *************************************
Description : Handle kernel function calls.
Input : struct RME_Cap_Captbl* Captbl - The current capability table.
struct RME_Reg_Struct* Reg - The current register set.
rme_ptr_t Func_ID - The function ID.
rme_ptr_t Sub_ID - The sub function ID.
rme_ptr_t Param1 - The first parameter.
rme_ptr_t Param2 - The second parameter.
Output : None.
Return : rme_ret_t - The value that the function returned.
******************************************************************************/
rme_ret_t __RME_Kern_Func_Handler(struct RME_Cap_Captbl* Captbl, struct RME_Reg_Struct* Reg,
rme_ptr_t Func_ID, rme_ptr_t Sub_ID, rme_ptr_t Param1, rme_ptr_t Param2)
{
/* Now always call the HALT */
char String[16];
String[0]=Param1/10000000+'0';
String[1]=(Param1/1000000)%10+'0';
String[2]=(Param1/100000)%10+'0';
String[3]=(Param1/10000)%10+'0';
String[4]=(Param1/1000)%10+'0';
String[5]=(Param1/100)%10+'0';
String[6]=(Param1/10)%10+'0';
String[7]=(Param1)%10+'0';
String[8]='\0';
write_string(Func_ID, (const char *)String, Sub_ID);
//__RME_X64_Halt();
return 0;
}
/* End Function:__RME_Kern_Func_Handler **************************************/
/* Begin Function:__RME_X64_Fault_Handler *************************************
Description : The fault handler of RME. In x64, this is used to handle multiple
faults.
Input : struct RME_Reg_Struct* Reg - The register set when entering the handler.
rme_ptr_t Reason - The fault source.
Output : struct RME_Reg_Struct* Reg - The register set when exiting the handler.
Return : None.
******************************************************************************/
void __RME_X64_Fault_Handler(struct RME_Reg_Struct* Reg, rme_ptr_t Reason)
{
/* Not handling faults */
RME_PRINTK_S("\n\r\n\r*** Fault: ");RME_PRINTK_I(Reason);RME_PRINTK_S(" - ");
/* When handling debug exceptions, note CVE 2018-8897, we may get something at
* kernel level - If this is what we have, the user must have touched SS + INT */
/* Print reason */
switch(Reason)
{
case RME_X64_FAULT_DE:RME_PRINTK_S("Divide error");break;
case RME_X64_TRAP_DB:RME_PRINTK_S("Debug exception");break;
case RME_X64_INT_NMI:RME_PRINTK_S("NMI error");break;
case RME_X64_TRAP_BP:RME_PRINTK_S("Debug breakpoint");break;
case RME_X64_TRAP_OF:RME_PRINTK_S("Overflow exception");break;
case RME_X64_FAULT_BR:RME_PRINTK_S("Bound range exception");break;
case RME_X64_FAULT_UD:RME_PRINTK_S("Undefined instruction");break;
case RME_X64_FAULT_NM:RME_PRINTK_S("Device not available");break;
case RME_X64_ABORT_DF:RME_PRINTK_S("Double(nested) fault exception");break;
case RME_X64_ABORT_OLD_MF:RME_PRINTK_S("Coprocessor overrun - not used later on");break;
case RME_X64_FAULT_TS:RME_PRINTK_S("Invalid TSS exception");break;
case RME_X64_FAULT_NP:RME_PRINTK_S("Segment not present");break;
case RME_X64_FAULT_SS:RME_PRINTK_S("Stack fault exception");break;
case RME_X64_FAULT_GP:RME_PRINTK_S("General protection exception");break;
case RME_X64_FAULT_PF:RME_PRINTK_S("Page fault exception");break;
case RME_X64_FAULT_MF:RME_PRINTK_S("X87 FPU floating-point error:");break;
case RME_X64_FAULT_AC:RME_PRINTK_S("Alignment check exception");break;
case RME_X64_ABORT_MC:RME_PRINTK_S("Machine check exception");break;
case RME_X64_FAULT_XM:RME_PRINTK_S("SIMD floating-point exception");break;
case RME_X64_FAULT_VE:RME_PRINTK_S("Virtualization exception");break;
default:RME_PRINTK_S("Unknown exception");break;
}
/* Print all registers */
RME_PRINTK_S("\n\rRAX: 0x");RME_PRINTK_U(Reg->RAX);
RME_PRINTK_S("\n\rRBX: 0x");RME_PRINTK_U(Reg->RBX);
RME_PRINTK_S("\n\rRCX: 0x");RME_PRINTK_U(Reg->RCX);
RME_PRINTK_S("\n\rRDX: 0x");RME_PRINTK_U(Reg->RDX);
RME_PRINTK_S("\n\rRSI: 0x");RME_PRINTK_U(Reg->RSI);
RME_PRINTK_S("\n\rRDI: 0x");RME_PRINTK_U(Reg->RDI);
RME_PRINTK_S("\n\rRBP: 0x");RME_PRINTK_U(Reg->RBP);
RME_PRINTK_S("\n\rR8: 0x");RME_PRINTK_U(Reg->R8);
RME_PRINTK_S("\n\rR9: 0x");RME_PRINTK_U(Reg->R9);
RME_PRINTK_S("\n\rR10: 0x");RME_PRINTK_U(Reg->R10);
RME_PRINTK_S("\n\rR11: 0x");RME_PRINTK_U(Reg->R11);
RME_PRINTK_S("\n\rR12: 0x");RME_PRINTK_U(Reg->R12);
RME_PRINTK_S("\n\rR13: 0x");RME_PRINTK_U(Reg->R13);
RME_PRINTK_S("\n\rR14: 0x");RME_PRINTK_U(Reg->R14);
RME_PRINTK_S("\n\rR15: 0x");RME_PRINTK_U(Reg->R15);
RME_PRINTK_S("\n\rINT_NUM: 0x");RME_PRINTK_U(Reg->INT_NUM);
RME_PRINTK_S("\n\rERROR_CODE: 0x");RME_PRINTK_U(Reg->ERROR_CODE);
RME_PRINTK_S("\n\rRIP: 0x");RME_PRINTK_U(Reg->RIP);
RME_PRINTK_S("\n\rCS: 0x");RME_PRINTK_U(Reg->CS);
RME_PRINTK_S("\n\rRFLAGS: 0x");RME_PRINTK_U(Reg->RFLAGS);
RME_PRINTK_S("\n\rRSP: 0x");RME_PRINTK_U(Reg->RSP);
RME_PRINTK_S("\n\rSS: 0x");RME_PRINTK_U(Reg->SS);
RME_PRINTK_S("\n\rHang");
while(1);
}
/* End Function:__RME_X64_Fault_Handler **************************************/
/* Begin Function:__RME_X64_Generic_Handler ***********************************
Description : The generic interrupt handler of RME for x64.
Input : struct RME_Reg_Struct* Reg - The register set when entering the handler.
rme_ptr_t Int_Num - The interrupt number.
Output : struct RME_Reg_Struct* Reg - The register set when exiting the handler.
Return : None.
******************************************************************************/
void __RME_X64_Generic_Handler(struct RME_Reg_Struct* Reg, rme_ptr_t Int_Num)
{
/* Not handling interrupts */
RME_PRINTK_S("\r\nGeneral int:");
RME_PRINTK_I(Int_Num);
switch(Int_Num)
{
/* Is this a generic IPI from other processors? */
default:break;
}
/* Remember to perform context switch after any kernel sends */
}
/* End Function:__RME_X64_Generic_Handler ************************************/
/* Begin Function:__RME_Pgtbl_Set *********************************************
Description : Set the processor's page table.
Input : rme_ptr_t Pgtbl - The virtual address of the page table.
Output : None.
Return : None.
******************************************************************************/
void __RME_Pgtbl_Set(rme_ptr_t Pgtbl)
{
__RME_X64_Pgtbl_Set(RME_X64_VA2PA(Pgtbl)|RME_X64_PGREG_POS(Pgtbl).PCID);
}
/* End Function:__RME_Pgtbl_Set **********************************************/
/* Begin Function:__RME_Pgtbl_Check *******************************************
Description : Check if the page table parameters are feasible, according to the
parameters. This is only used in page table creation.
Input : rme_ptr_t Base_Addr - The start mapping address.
rme_ptr_t Top_Flag - The top-level flag,
rme_ptr_t Size_Order - The size order of the page directory.
rme_ptr_t Num_Order - The number order of the page directory.
rme_ptr_t Vaddr - The virtual address of the page directory.
Output : None.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Check(rme_ptr_t Base_Addr, rme_ptr_t Top_Flag,
rme_ptr_t Size_Order, rme_ptr_t Num_Order, rme_ptr_t Vaddr)
{
/* Is the table address aligned to 4kB? */
if((Vaddr&0xFFF)!=0)
return RME_ERR_PGT_OPFAIL;
/* Is the size order allowed? */
if((Size_Order!=RME_PGTBL_SIZE_512G)&&(Size_Order!=RME_PGTBL_SIZE_1G)&&
(Size_Order!=RME_PGTBL_SIZE_2M)&&(Size_Order!=RME_PGTBL_SIZE_4K))
return RME_ERR_PGT_OPFAIL;
/* Is the top-level relationship correct? */
if(((Size_Order==RME_PGTBL_SIZE_512G)^(Top_Flag!=0))!=0)
return RME_ERR_PGT_OPFAIL;
/* Is the number order allowed? */
if(Num_Order!=RME_PGTBL_NUM_512)
return RME_ERR_PGT_OPFAIL;
return 0;
}
/* End Function:__RME_Pgtbl_Check ********************************************/
/* Begin Function:__RME_Pgtbl_Init ********************************************
Description : Initialize the page table data structure, according to the capability.
Input : struct RME_Cap_Pgtbl* - The capability to the page table to operate on.
Output : None.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Init(struct RME_Cap_Pgtbl* Pgtbl_Op)
{
rme_cnt_t Count;
rme_ptr_t* Ptr;
/* Get the actual table */
Ptr=RME_CAP_GETOBJ(Pgtbl_Op,rme_ptr_t*);
/* Hopefully the compiler optimize this to rep stos */
for(Count=0;Count<256;Count++)
Ptr[Count]=0;
/* Hopefully the compiler optimize this to rep movs */
if((Pgtbl_Op->Base_Addr&RME_PGTBL_TOP)!=0)
{
for(;Count<512;Count++)
Ptr[Count]=RME_X64_Kpgt.PML4[Count-256];
RME_X64_PGREG_POS(Ptr).PCID=RME_FETCH_ADD((rme_ptr_t*)&RME_X64_PCID_Inc,1)&0xFFF;
}
else
{
for(;Count<512;Count++)
Ptr[Count]=0;
}
/* Initialize its pgreg table to all zeros */
RME_X64_PGREG_POS(Ptr).Parent_Cnt=0;
RME_X64_PGREG_POS(Ptr).Child_Cnt=0;
return 0;
}
/* End Function:__RME_Pgtbl_Init *********************************************/
/* Begin Function:__RME_Pgtbl_Del_Check ***************************************
Description : Check if the page table can be deleted.
Input : struct RME_Cap_Pgtbl Pgtbl_Op* - The capability to the page table to operate on.
Output : None.
Return : rme_ptr_t - If can be deleted, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Del_Check(struct RME_Cap_Pgtbl* Pgtbl_Op)
{
rme_ptr_t* Table;
Table=RME_CAP_GETOBJ(Pgtbl_Op,rme_ptr_t*);
/* Check if it is mapped into other page tables. If yes, then it cannot be deleted.
* also, it must not contain mappings of lower levels, or it is not deletable. */
if((RME_X64_PGREG_POS(Table).Parent_Cnt==0)&&(RME_X64_PGREG_POS(Table).Child_Cnt==0))
return 0;
return RME_ERR_PGT_OPFAIL;
}
/* End Function:__RME_Pgtbl_Del_Check ****************************************/
/* Begin Function:__RME_Pgtbl_Page_Map ****************************************
Description : Map a page into the page table. This architecture requires that the mapping is
always at least readable.
Input : struct RME_Cap_Pgtbl* - The cap ability to the page table to operate on.
rme_ptr_t Paddr - The physical address to map to. If we are unmapping, this have no effect.
rme_ptr_t Pos - The position in the page table.
rme_ptr_t Flags - The RME standard page attributes. Need to translate them into
architecture specific page table's settings.
Output : None.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Page_Map(struct RME_Cap_Pgtbl* Pgtbl_Op, rme_ptr_t Paddr, rme_ptr_t Pos, rme_ptr_t Flags)
{
rme_ptr_t* Table;
rme_ptr_t X64_Flags;
/* It should at least be readable */
if((Flags&RME_PGTBL_READ)==0)
return RME_ERR_PGT_OPFAIL;
/* Are we trying to map into the kernel space on the top level? */
if(((Pgtbl_Op->Base_Addr&RME_PGTBL_TOP)!=0)&&(Pos>=256))
return RME_ERR_PGT_OPFAIL;
/* Get the table */
Table=RME_CAP_GETOBJ(Pgtbl_Op,rme_ptr_t*);
/* Generate flags */
if(RME_PGTBL_SIZEORD(Pgtbl_Op->Size_Num_Order)==RME_PGTBL_SIZE_4K)
X64_Flags=RME_X64_MMU_ADDR(Paddr)|RME_X64_PGFLG_RME2NAT(Flags)|RME_X64_MMU_US;
else
X64_Flags=RME_X64_MMU_ADDR(Paddr)|RME_X64_PGFLG_RME2NAT(Flags)|RME_X64_MMU_PDE_SUP|RME_X64_MMU_US;
/* Try to map it in */
if(RME_COMP_SWAP(&(Table[Pos]),0,X64_Flags)==0)
return RME_ERR_PGT_OPFAIL;
return 0;
}
/* End Function:__RME_Pgtbl_Page_Map *****************************************/
/* Begin Function:__RME_Pgtbl_Page_Unmap **************************************
Description : Unmap a page from the page table.
Input : struct RME_Cap_Pgtbl* - The capability to the page table to operate on.
rme_ptr_t Pos - The position in the page table.
Output : None.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Page_Unmap(struct RME_Cap_Pgtbl* Pgtbl_Op, rme_ptr_t Pos)
{
rme_ptr_t* Table;
rme_ptr_t Temp;
/* Are we trying to unmap the kernel space on the top level? */
if(((Pgtbl_Op->Base_Addr&RME_PGTBL_TOP)!=0)&&(Pos>=256))
return RME_ERR_PGT_OPFAIL;
/* Get the table */
Table=RME_CAP_GETOBJ(Pgtbl_Op,rme_ptr_t*);
/* Make sure that there is something */
Temp=Table[Pos];
if(Temp==0)
return RME_ERR_PGT_OPFAIL;
/* Is this a page directory? We cannot unmap page directories like this */
if((RME_PGTBL_SIZEORD(Pgtbl_Op->Size_Num_Order)!=RME_PGTBL_SIZE_4K)&&((Temp&RME_X64_MMU_PDE_SUP)==0))
return RME_ERR_PGT_OPFAIL;
/* Try to unmap it. Use CAS just in case */
if(RME_COMP_SWAP(&(Table[Pos]),Temp,0)==0)
return RME_ERR_PGT_OPFAIL;
return 0;
}
/* End Function:__RME_Pgtbl_Page_Unmap ***************************************/
/* Begin Function:__RME_Pgtbl_Pgdir_Map ***************************************
Description : Map a page directory into the page table.
Input : struct RME_Cap_Pgtbl* Pgtbl_Parent - The parent page table.
struct RME_Cap_Pgtbl* Pgtbl_Child - The child page table.
rme_ptr_t Pos - The position in the destination page table.
rme_ptr_t Flags - The RME standard flags for the child page table.
Output : None.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Pgdir_Map(struct RME_Cap_Pgtbl* Pgtbl_Parent, rme_ptr_t Pos,
struct RME_Cap_Pgtbl* Pgtbl_Child, rme_ptr_t Flags)
{
rme_ptr_t* Parent_Table;
rme_ptr_t* Child_Table;
rme_ptr_t X64_Flags;
/* It should at least be readable */
if((Flags&RME_PGTBL_READ)==0)
return RME_ERR_PGT_OPFAIL;
/* Are we trying to map into the kernel space on the top level? */
if(((Pgtbl_Parent->Base_Addr&RME_PGTBL_TOP)!=0)&&(Pos>=256))
return RME_ERR_PGT_OPFAIL;
/* Get the table */
Parent_Table=RME_CAP_GETOBJ(Pgtbl_Parent,rme_ptr_t*);
Child_Table=RME_CAP_GETOBJ(Pgtbl_Child,rme_ptr_t*);
/* Generate the content */
X64_Flags=RME_X64_MMU_ADDR(RME_X64_VA2PA(Child_Table))|RME_X64_PGFLG_RME2NAT(Flags)|RME_X64_MMU_US;
/* Try to map it in - may need to increase some count */
if(RME_COMP_SWAP(&(Parent_Table[Pos]),0,X64_Flags)==0)
return RME_ERR_PGT_OPFAIL;
/* Map complete, increase reference count for both page tables */
RME_FETCH_ADD((rme_ptr_t*)&(RME_X64_PGREG_POS(Child_Table).Parent_Cnt),1);
RME_FETCH_ADD((rme_ptr_t*)&(RME_X64_PGREG_POS(Parent_Table).Child_Cnt),1);
return 0;
}
/* End Function:__RME_Pgtbl_Pgdir_Map ****************************************/
/* Begin Function:__RME_Pgtbl_Pgdir_Unmap *************************************
Description : Unmap a page directory from the page table.
Input : struct RME_Cap_Pgtbl* Pgtbl_Op - The page table to operate on.
rme_ptr_t Pos - The position in the page table.
Output : None.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Pgdir_Unmap(struct RME_Cap_Pgtbl* Pgtbl_Op, rme_ptr_t Pos)
{
rme_ptr_t* Parent_Table;
rme_ptr_t* Child_Table;
rme_ptr_t Temp;
/* Are we trying to unmap the kernel space on the top level? */
if(((Pgtbl_Op->Base_Addr&RME_PGTBL_TOP)!=0)&&(Pos>=256))
return RME_ERR_PGT_OPFAIL;
/* Get the table */
Parent_Table=RME_CAP_GETOBJ(Pgtbl_Op,rme_ptr_t*);
/* Make sure that there is something */
Temp=Parent_Table[Pos];
if(Temp==0)
return RME_ERR_PGT_OPFAIL;
/* Is this a page? We cannot unmap pages like this */
if((RME_PGTBL_SIZEORD(Pgtbl_Op->Size_Num_Order)==RME_PGTBL_SIZE_4K)||((Temp&RME_X64_MMU_PDE_SUP)!=0))
return RME_ERR_PGT_OPFAIL;
Child_Table=(rme_ptr_t*)Temp;
/* Try to unmap it. Use CAS just in case */
if(RME_COMP_SWAP(&(Parent_Table[Pos]),Temp,0)==0)
return RME_ERR_PGT_OPFAIL;
/* Decrease reference count */
RME_FETCH_ADD((rme_ptr_t*)&(RME_X64_PGREG_POS(Child_Table).Parent_Cnt),-1);
RME_FETCH_ADD((rme_ptr_t*)&(RME_X64_PGREG_POS(Parent_Table).Child_Cnt),-1);
return 0;
}
/* End Function:__RME_Pgtbl_Pgdir_Unmap **************************************/
/* Begin Function:__RME_Pgtbl_Lookup ********************************************
Description : Lookup a page entry in a page directory.
Input : struct RME_Cap_Pgtbl* Pgtbl_Op - The page directory to lookup.
rme_ptr_t Pos - The position to look up.
Output : rme_ptr_t* Paddr - The physical address of the page.
rme_ptr_t* Flags - The RME standard flags of the page.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Lookup(struct RME_Cap_Pgtbl* Pgtbl_Op, rme_ptr_t Pos, rme_ptr_t* Paddr, rme_ptr_t* Flags)
{
rme_ptr_t* Table;
rme_ptr_t Temp;
/* Check if the position is within the range of this page table */
if((Pos>>RME_PGTBL_NUMORD(Pgtbl_Op->Size_Num_Order))!=0)
return RME_ERR_PGT_OPFAIL;
/* Get the table */
Table=RME_CAP_GETOBJ(Pgtbl_Op,rme_ptr_t*);
/* Get the position requested - atomic read */
Temp=Table[Pos];
/* Start lookup - is this a terminal page, or? */
if(RME_PGTBL_SIZEORD(Pgtbl_Op->Size_Num_Order)==RME_PGTBL_SIZE_4K)
{
if((Temp&RME_X64_MMU_P)==0)
return RME_ERR_PGT_OPFAIL;
}
else
{
if(((Temp&RME_X64_MMU_P)==0)||((Temp&RME_X64_MMU_PDE_SUP)==0))
return RME_ERR_PGT_OPFAIL;
}
/* This is a page. Return the physical address and flags */
if(Paddr!=0)
*Paddr=RME_X64_MMU_ADDR(Temp);
if(Flags!=0)
*Flags=RME_X64_PGFLG_NAT2RME(Temp);
return 0;
}
/* End Function:__RME_Pgtbl_Lookup *******************************************/
/* Begin Function:__RME_Pgtbl_Walk ********************************************
Description : Walking function for the page table. This function just does page
table lookups. The page table that is being walked must be the top-
level page table. The output values are optional; only pass in pointers
when you need that value.
Walking kernel page tables is prohibited.
Input : struct RME_Cap_Pgtbl* Pgtbl_Op - The page table to walk.
rme_ptr_t Vaddr - The virtual address to look up.
Output : rme_ptr_t* Pgtbl - The pointer to the page table level.
rme_ptr_t* Map_Vaddr - The virtual address that starts mapping.
rme_ptr_t* Paddr - The physical address of the page.
rme_ptr_t* Size_Order - The size order of the page.
rme_ptr_t* Num_Order - The entry order of the page.
rme_ptr_t* Flags - The RME standard flags of the page.
Return : rme_ptr_t - If successful, 0; else RME_ERR_PGT_OPFAIL.
******************************************************************************/
rme_ptr_t __RME_Pgtbl_Walk(struct RME_Cap_Pgtbl* Pgtbl_Op, rme_ptr_t Vaddr, rme_ptr_t* Pgtbl,
rme_ptr_t* Map_Vaddr, rme_ptr_t* Paddr, rme_ptr_t* Size_Order, rme_ptr_t* Num_Order, rme_ptr_t* Flags)
{
rme_ptr_t* Table;
rme_ptr_t Pos;
rme_ptr_t Temp;
rme_ptr_t Size_Cnt;
/* Accumulates the flag information about each level - these bits are ANDed */
rme_ptr_t Flags_Accum;
/* No execute bit - this bit is ORed */
rme_ptr_t No_Execute;
/* Check if this is the top-level page table */
if(((Pgtbl_Op->Base_Addr)&RME_PGTBL_TOP)==0)
return RME_ERR_PGT_OPFAIL;
/* Are we attempting a kernel or non-canonical lookup? If yes, stop immediately */
if(Vaddr>=0x7FFFFFFFFFFFULL)
return RME_ERR_PGT_OPFAIL;
/* Get the table and start lookup */
Table=RME_CAP_GETOBJ(Pgtbl_Op, rme_ptr_t*);
/* Do lookup recursively */
Size_Cnt=RME_PGTBL_SIZE_512G;
Flags_Accum=0xFFF;
No_Execute=0;
while(1)
{
/* Calculate where is the entry - always 0 to 512*/
Pos=(Vaddr>>Size_Cnt)&0x1FF;
/* Atomic read */
Temp=Table[Pos];
/* Find the position of the entry - Is there a page, a directory, or nothing? */
if((Temp&RME_X64_MMU_P)==0)
return RME_ERR_PGT_OPFAIL;
if(((Temp&RME_X64_MMU_PDE_SUP)!=0)||(Size_Cnt==RME_PGTBL_SIZE_4K))
{
/* This is a page - we found it */
if(Pgtbl!=0)
*Pgtbl=(rme_ptr_t)Table;
if(Map_Vaddr!=0)
*Map_Vaddr=RME_ROUND_DOWN(Vaddr,Size_Cnt);
if(Paddr!=0)
*Paddr=RME_X64_MMU_ADDR(Temp);
if(Size_Order!=0)
*Size_Order=Size_Cnt;
if(Num_Order!=0)
*Num_Order=RME_PGTBL_NUM_512;
if(Flags!=0)
*Flags=RME_X64_PGFLG_NAT2RME(No_Execute|(Temp&Flags_Accum));
break;
}
else
{
/* This is a directory, we goto that directory to continue walking */
Flags_Accum&=Temp;
No_Execute|=Temp&RME_X64_MMU_NX;
Table=(rme_ptr_t*)RME_X64_PA2VA(RME_X64_MMU_ADDR(Temp));
}
/* The size order always decreases by 512 */
Size_Cnt-=RME_PGTBL_SIZE_512B;
}
return 0;
}
/* End Function:__RME_Pgtbl_Walk *********************************************/
/* End Of File ***************************************************************/
/* Copyright (C) Evo-Devo Instrum. All rights reserved ***********************/
| 44.581336 | 133 | 0.629429 | [
"object",
"vector",
"model"
] |
53dfab32d31eeed504e70e413eeace66885130fc | 2,313 | h | C | GWToolboxdll/Windows/FactionLeaderboardWindow.h | RiftLurker/GWToolboxpp | b6f66da371619bfc29173991d159fcfc92d42ca5 | [
"MIT"
] | 106 | 2016-09-04T20:28:22.000Z | 2022-03-07T07:26:33.000Z | GWToolboxdll/Windows/FactionLeaderboardWindow.h | RiftLurker/GWToolboxpp | b6f66da371619bfc29173991d159fcfc92d42ca5 | [
"MIT"
] | 542 | 2016-09-04T18:09:57.000Z | 2022-03-26T19:45:35.000Z | GWToolboxdll/Windows/FactionLeaderboardWindow.h | RiftLurker/GWToolboxpp | b6f66da371619bfc29173991d159fcfc92d42ca5 | [
"MIT"
] | 110 | 2016-12-03T17:30:32.000Z | 2022-03-28T18:04:50.000Z | #pragma once
#include <GWCA/Utilities/Hook.h>
#include <GWCA/GameEntities/Map.h>
#include <GWCA/Managers/UIMgr.h>
#include <GWCA/Managers/MapMgr.h>
#include <GuiUtils.h>
#include <ToolboxWindow.h>
class FactionLeaderboardWindow : public ToolboxWindow {
private:
struct LeaderboardEntry {
LeaderboardEntry() {};
LeaderboardEntry(uint32_t m, uint32_t r, uint32_t a, uint32_t f, const wchar_t* n, const wchar_t* t) : map_id(m), rank(r), allegiance(a), faction(f) {
wcscpy(guild_wstr, n); // Copy the string to avoid read errors later.
wcscpy(tag_wstr, t); // Copy the string to avoid read errors later.
map_name[0] = 0;
strcpy(guild_str,GuiUtils::WStringToString(guild_wstr).c_str());
strcpy(tag_str, GuiUtils::WStringToString(tag_wstr).c_str());
guild_wiki_url = guild_wstr;
std::transform(guild_wiki_url.begin(), guild_wiki_url.end(), guild_wiki_url.begin(),
[](wchar_t ch) -> wchar_t {
return ch == ' ' ? L'_' : ch;
});
guild_wiki_url = L"https://wiki.guildwars.com/wiki/Guild:" + guild_wiki_url;
initialised = true;
}
uint32_t map_id=0;
uint32_t rank=0;
uint32_t allegiance=0;
uint32_t faction=0;
wchar_t guild_wstr[32];
wchar_t tag_wstr[5];
char guild_str[128]; // unicode char can be up to 4 bytes
char tag_str[20]; // unicode char can be up to 4 bytes
wchar_t map_name_enc[16];
char map_name[256];
std::wstring guild_wiki_url;
bool initialised = false;
};
FactionLeaderboardWindow() {};
~FactionLeaderboardWindow() {};
public:
static FactionLeaderboardWindow& Instance() {
static FactionLeaderboardWindow instance;
return instance;
}
const char* Name() const override { return "Faction Leaderboard"; }
const char* Icon() const override { return ICON_FA_GLOBE; }
void Initialize() override;
// Draw user interface. Will be called every frame if the element is visible
void Draw(IDirect3DDevice9* pDevice) override;
private:
std::vector<LeaderboardEntry> leaderboard;
std::vector<LeaderboardEntry>::iterator lit;
GW::HookEntry TownAlliance_Entry;
};
| 35.584615 | 158 | 0.642456 | [
"vector",
"transform"
] |
53e548cd90be7e6c7f5d2e82cadc62d36834bdec | 4,654 | h | C | examples/gltfscenerendering/gltfscenerendering.h | nidefawl/Vulkan-Examples-Fork | 2d93474957a6357ddebbe199d2bd79a215f16ee5 | [
"MIT"
] | null | null | null | examples/gltfscenerendering/gltfscenerendering.h | nidefawl/Vulkan-Examples-Fork | 2d93474957a6357ddebbe199d2bd79a215f16ee5 | [
"MIT"
] | null | null | null | examples/gltfscenerendering/gltfscenerendering.h | nidefawl/Vulkan-Examples-Fork | 2d93474957a6357ddebbe199d2bd79a215f16ee5 | [
"MIT"
] | null | null | null | /*
* Vulkan Example - glTF scene rendering
*
* Copyright (C) 2020-2021 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
/*
* This sample builds on the gltfloading sample and renders a more complex scene (Crytek's Sponza)
* It makes use of additional material parameters and adds normal mapping and alpha masked materials
* The biggest difference is in how material information is passed by using per-material pipelines
* See the README.MD in this folder for a tutorial
*/
#define TINYGLTF_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#define TINYGLTF_NO_STB_IMAGE_WRITE
#define TINYGLTF_NO_STB_IMAGE
#define TINYGLTF_NO_EXTERNAL_IMAGE
#ifdef VK_USE_PLATFORM_ANDROID_KHR
#define TINYGLTF_ANDROID_LOAD_FROM_ASSETS
#endif
#include "tiny_gltf.h"
#include "vulkanexamplebase.h"
#define ENABLE_VALIDATION false
// Contains everything required to render a basic glTF scene in Vulkan
// This class is heavily simplified (compared to glTF's feature set) but retains the basic glTF structure
class VulkanglTFScene
{
public:
// The class requires some Vulkan objects so it can create it's own resources
vks::VulkanDevice* vulkanDevice;
VkQueue copyQueue;
// The vertex layout for the samples' model
struct Vertex {
glm::vec3 pos;
glm::vec3 normal;
glm::vec2 uv;
glm::vec3 color;
glm::vec4 tangent;
};
// Single vertex buffer for all primitives
struct {
VkBuffer buffer;
VkDeviceMemory memory;
} vertices;
// Single index buffer for all primitives
struct {
int count;
VkBuffer buffer;
VkDeviceMemory memory;
} indices;
// The following structures roughly represent the glTF scene structure
// To keep things simple, they only contain those properties that are required for this sample
struct Node;
// A primitive contains the data for a single draw call
struct Primitive {
uint32_t firstIndex;
uint32_t indexCount;
int32_t materialIndex;
};
// Contains the node's (optional) geometry and can be made up of an arbitrary number of primitives
struct Mesh {
std::vector<Primitive> primitives;
};
// A node represents an object in the glTF scene graph
struct Node {
Node* parent;
std::vector<Node> children;
Mesh mesh;
glm::mat4 matrix;
std::string name;
bool visible = true;
};
// A glTF material stores information in e.g. the texture that is attached to it and colors
struct Material {
glm::vec4 baseColorFactor = glm::vec4(1.0f);
uint32_t baseColorTextureIndex;
uint32_t normalTextureIndex;
std::string alphaMode = "OPAQUE";
float alphaCutOff;
bool doubleSided = false;
VkDescriptorSet descriptorSet;
VkPipeline pipeline;
};
// Contains the texture for a single glTF image
// Images may be reused by texture objects and are as such separated
struct Image {
vks::Texture2D texture;
};
// A glTF texture stores a reference to the image and a sampler
// In this sample, we are only interested in the image
struct Texture {
int32_t imageIndex;
};
std::vector<Image> images;
std::vector<Texture> textures;
std::vector<Material> materials;
std::vector<Node> nodes;
std::string path;
VulkanglTFScene(vks::VulkanDevice* device, VkQueue copyQueue);
~VulkanglTFScene();
void loadFromFile(const std::string& filename);
void loadImages(tinygltf::Model& input);
void loadTextures(tinygltf::Model& input);
void loadMaterials(tinygltf::Model& input);
void loadNode(const tinygltf::Node& inputNode, const tinygltf::Model& input, VulkanglTFScene::Node* parent, std::vector<uint32_t>& indexBuffer, std::vector<VulkanglTFScene::Vertex>& vertexBuffer);
void drawNode(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout, VulkanglTFScene::Node node);
void draw(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout);
};
class VulkanExample : public VulkanExampleBase
{
public:
VulkanglTFScene* glTFScene;
struct ShaderData {
glm::mat4 projection;
glm::mat4 view;
glm::vec4 lightPos = glm::vec4(0.0f, 2.5f, 0.0f, 1.0f);
glm::vec4 viewPos;
} shaderData;
struct FrameObjects : public VulkanFrameObjects {
vks::Buffer uniformBuffer;
VkDescriptorSet descriptorSet;
};
std::vector<FrameObjects> frameObjects;
VkPipelineLayout pipelineLayout;
struct DescriptorSetLayouts {
VkDescriptorSetLayout uniformbuffers;
VkDescriptorSetLayout images;
} descriptorSetLayouts;
VulkanExample();
~VulkanExample();
virtual void getEnabledFeatures();
void loadAssets();
void createDescriptors();
void createPipelines();
void prepare();
virtual void render();
virtual void OnUpdateUIOverlay(vks::UIOverlay* overlay);
}; | 28.728395 | 197 | 0.759991 | [
"mesh",
"geometry",
"render",
"object",
"vector",
"model"
] |
53efd80df3fbe2e0ff471c2379b727ae9990969f | 7,415 | h | C | dep/include/yse/channel/channelImplementation.h | ChrSacher/MyEngine | 8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8 | [
"Apache-2.0"
] | 2 | 2015-10-27T21:36:59.000Z | 2017-03-17T21:52:19.000Z | dep/include/yse/channel/channelImplementation.h | ChrSacher/MyEngine | 8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8 | [
"Apache-2.0"
] | null | null | null | dep/include/yse/channel/channelImplementation.h | ChrSacher/MyEngine | 8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8 | [
"Apache-2.0"
] | null | null | null | /*
==============================================================================
channelImplementation.h
Created: 30 Jan 2014 4:21:26pm
Author: yvan
==============================================================================
*/
#ifndef CHANNELIMPLEMENTATION_H_INCLUDED
#define CHANNELIMPLEMENTATION_H_INCLUDED
#include <forward_list>
#include "../classes.hpp"
#include "../utils/lfQueue.hpp"
#include "../internal/threadPool.h"
namespace YSE {
namespace CHANNEL {
class output;
/**
This is the implementation side of a channel. It should only be used internally.
*/
class implementationObject : public INTERNAL::threadPoolJob {
public:
//////////////////////////////////////////////////
// Setup and maintenance functions
//////////////////////////////////////////////////
/**
Creates a channel implementation.
@param head A pointer to the interface of this channel.
*/
implementationObject(interfaceObject * head);
/**
Removes the implementation from the threadpool and moves all sounds and subchannels
to its parent (if there is one).
*/
~implementationObject();
/** This function is called from channelManager::setup and creates the buffers
needed for this channel.
*/
void setup();
/** This function resizes some containers to the number of output channels used
by the current device.
@param deep If true, children will also be resized
*/
void resize(bool deep = false);
/** This function is called by channelManager::update (from dsp callback) and verifies
if the channel is ready to be played. It will then be moved from toCreate
to inUse.
*/
Bool readyCheck();
/** Will move all current subchannels and sounds to the parent channel.
This function is called from channelManager::update(), when objectStatus
is CIS_RELEASE. It is called again from the destructor, just in case, but
children should already be moved by then.
*/
void childrenToParent();
void removeInterface();
void doThisWhenReady();
OBJECT_IMPLEMENTATION_STATE getStatus();
void setStatus(OBJECT_IMPLEMENTATION_STATE value);
//////////////////////////////////////////////////////
// Message system functions
//////////////////////////////////////////////////////
/**
This function will be called when the system is instructed to do an update. It looks
for messages in the interface message pipe and forwards them to the parseMessage
function.
*/
void sync();
void parseMessage(const messageObject & message); // < Parse a message, called by sync
/**
Called by an interface object to send a message to the implementation.
*/
inline void sendMessage(const messageObject & message) {
messages.push(message);
}
//////////////////////////////////////////////////////
// Connectors
//////////////////////////////////////////////////////
/**
Attach a subchannel to this channel.
@param subChannel A pointer to the channel that should be linked
to this channel.
*/
Bool connect(CHANNEL::implementationObject * channel);
/**
Attach a sound to this channel.
@param sound A pointer to the sound that should be linked
to this channel.
*/
Bool connect(SOUND::implementationObject * sound);
/**
Remove a subchannel from this channel.
@param channel A pointer to the channel to disconnect
*/
Bool disconnect(CHANNEL::implementationObject * channel);
/**
Remove a sound from this channel.
@param sound A pointer to the sound to disconnect
*/
Bool disconnect(SOUND::implementationObject * sound);
/////////////////////////////////////////////////////
// DSP calculations
/////////////////////////////////////////////////////
/**
This is the threadpool function that calls the dsp for this channel.
Every channel has its own threadPoolJob for running the dsp calculations.
This will scale all sounds nicely over several cpu's as long as you don't
put them all in one channel.
*/
virtual void run();
/**
This is the one that does all the work. It allso calls the dsp function
of all child channels and of all sounds. Effects are also calculated
here, but applied in the buffersToParent function.
*/
void dsp();
/**
Waits until the dsp job is done and recursively calls this function for
all subchannels. If this is not the Master channel, this will copy the
current buffers to the parent channel.
*/
void buffersToParent();
/** dsp utility function to set all output buffers to zero before filling again
*/
void clearBuffers();
/** Creates a ramp to the new volume if needed, to avoid pops. Called by the dsp function.
*/
void adjustVolume();
/**
Attach the premade special effect for 'underwater' simulation to this channel
*/
void attachUnderWaterFX();
/////////////////////////////////////////////////////
// static functions for remove_if
/////////////////////////////////////////////////////
/**
This function is used by the forward_list remove_if function
*/
static bool canBeDeleted(const implementationObject& impl) {
return impl.objectStatus == OBJECT_DELETE;
}
/**
This function is used by the forward_list remove_if function
*/
static bool canBeRemovedFromLoading(const std::atomic<implementationObject*> & impl) {
if (impl.load()->objectStatus == OBJECT_READY
|| impl.load()->objectStatus == OBJECT_RELEASE
|| impl.load()->objectStatus == OBJECT_DELETE) {
return true;
}
return false;
}
private:
std::atomic<interfaceObject *> head; // < The interface connected to this object
std::atomic<OBJECT_IMPLEMENTATION_STATE> objectStatus; // < the status of this object
lfQueue<messageObject> messages;
Flt newVolume;
Flt lastVolume;
CHANNEL::implementationObject * parent;
std::forward_list<CHANNEL::implementationObject*> children;
std::forward_list<SOUND::implementationObject *> sounds;
std::vector<output> outConf;
std::vector<DSP::buffer> out;
Bool userChannel; // channel is created by user and not crucial for the system
Bool allowVirtual;
friend class SOUND::implementationObject;
friend class CHANNEL::interfaceObject;
friend class YSE::REVERB::managerObject;
friend class DEVICE::managerObject;
friend class CHANNEL::managerObject;
};
/**
This is a helper class for calculating the channel and sound volume. Don't use it
anywhere else.
*/
class output {
public:
Flt angle;
Flt initPan;
Flt initGain;
Flt effective;
Flt ratio;
Flt finalGain;
output() : angle(0.f) {}
};
}
}
#endif // CHANNELIMPLEMENTATION_H_INCLUDED
| 31.025105 | 96 | 0.574241 | [
"object",
"vector"
] |
53f932418d6247d5397d6ae9fc430d62c0ac2291 | 36,489 | c | C | main/oled_12_font_symbol.c | an-erd/bleMqttProxy | 32faf163bc42d663ac4ac962a5e65e7e7750801e | [
"MIT"
] | null | null | null | main/oled_12_font_symbol.c | an-erd/bleMqttProxy | 32faf163bc42d663ac4ac962a5e65e7e7750801e | [
"MIT"
] | 31 | 2019-04-18T13:29:56.000Z | 2021-02-12T11:07:59.000Z | main/oled_12_font_symbol.c | an-erd/bleMqttProxy | 32faf163bc42d663ac4ac962a5e65e7e7750801e | [
"MIT"
] | null | null | null | #include "lvgl/lvgl.h"
/*******************************************************************************
* Size: 12 px
* Bpp: 1
* Opts:
******************************************************************************/
#ifndef OLED_12_FONT_SYMBOL
#define OLED_12_FONT_SYMBOL 1
#endif
#if OLED_12_FONT_SYMBOL
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t gylph_bitmap[] = {
/* U+20 " " */
0x0,
/* U+21 "!" */
0xfc, 0x80,
/* U+22 "\"" */
0xfc,
/* U+23 "#" */
0x14, 0x49, 0xf9, 0x42, 0x9f, 0xca, 0x24, 0x48,
/* U+24 "$" */
0x10, 0xe4, 0xd1, 0x40, 0xc1, 0x81, 0x45, 0x13,
0x84,
/* U+25 "%" */
0x60, 0x94, 0x94, 0x68, 0x10, 0x16, 0x29, 0x29,
0x6,
/* U+26 "&" */
0x30, 0x91, 0x23, 0x82, 0xa, 0xa3, 0x26, 0x7e,
/* U+27 "'" */
0xe0,
/* U+28 "(" */
0x29, 0x49, 0x24, 0x91, 0x22,
/* U+29 ")" */
0x89, 0x12, 0x49, 0x25, 0x28,
/* U+2A "*" */
0x21, 0x3e, 0xc5, 0x0,
/* U+2B "+" */
0x20, 0x82, 0x3f, 0x20, 0x82, 0x0,
/* U+2C "," */
0x54,
/* U+2D "-" */
0xe0,
/* U+2E "." */
0x80,
/* U+2F "/" */
0x10, 0x84, 0x42, 0x11, 0x8, 0x44, 0x0,
/* U+30 "0" */
0x74, 0x63, 0x18, 0xc6, 0x3b, 0x70,
/* U+31 "1" */
0x3c, 0x92, 0x49, 0x20,
/* U+32 "2" */
0x74, 0x62, 0x11, 0x11, 0x88, 0xf8,
/* U+33 "3" */
0x74, 0x42, 0x13, 0x4, 0x31, 0x70,
/* U+34 "4" */
0x8, 0x62, 0x8a, 0x4b, 0x2f, 0xc2, 0x8,
/* U+35 "5" */
0xfc, 0x21, 0xe1, 0x86, 0x33, 0x70,
/* U+36 "6" */
0x32, 0x21, 0xe8, 0xc6, 0x39, 0x70,
/* U+37 "7" */
0xfc, 0x10, 0x82, 0x10, 0x43, 0x8, 0x20,
/* U+38 "8" */
0x74, 0x63, 0x17, 0x46, 0x31, 0x70,
/* U+39 "9" */
0x74, 0xe3, 0x18, 0xbc, 0x22, 0x60,
/* U+3A ":" */
0x82,
/* U+3B ";" */
0x87,
/* U+3C "<" */
0x9, 0xb1, 0xc3, 0x84,
/* U+3D "=" */
0xf8, 0x1, 0xf0,
/* U+3E ">" */
0x83, 0x6, 0x7e, 0x40,
/* U+3F "?" */
0x76, 0x42, 0x11, 0x10, 0x80, 0x20,
/* U+40 "@" */
0x1e, 0x8, 0x64, 0xb, 0x39, 0x92, 0x64, 0x99,
0x26, 0x5b, 0x9b, 0x90, 0x6, 0x0, 0x78,
/* U+41 "A" */
0x18, 0x18, 0x18, 0x24, 0x24, 0x64, 0x7e, 0x42,
0xc2,
/* U+42 "B" */
0xfa, 0x18, 0x61, 0xfa, 0x18, 0x61, 0xf8,
/* U+43 "C" */
0x39, 0x18, 0x60, 0x82, 0x8, 0x51, 0x38,
/* U+44 "D" */
0xf2, 0x28, 0x61, 0x86, 0x18, 0x62, 0xf0,
/* U+45 "E" */
0xfc, 0x21, 0xf, 0xc2, 0x10, 0xf8,
/* U+46 "F" */
0xfc, 0x21, 0xf, 0xc2, 0x10, 0x80,
/* U+47 "G" */
0x3c, 0x8e, 0x4, 0x8, 0xf0, 0x60, 0xa1, 0x3c,
/* U+48 "H" */
0x83, 0x6, 0xc, 0x1f, 0xf0, 0x60, 0xc1, 0x82,
/* U+49 "I" */
0xff, 0x80,
/* U+4A "J" */
0x8, 0x42, 0x10, 0x86, 0x31, 0x70,
/* U+4B "K" */
0x8e, 0x29, 0x28, 0xe2, 0x49, 0xa2, 0x84,
/* U+4C "L" */
0x84, 0x21, 0x8, 0x42, 0x10, 0xf8,
/* U+4D "M" */
0xc3, 0xc3, 0xc3, 0xa5, 0xa5, 0xa5, 0x99, 0x99,
0x99,
/* U+4E "N" */
0x83, 0x87, 0x8d, 0x99, 0x33, 0x63, 0xc3, 0x82,
/* U+4F "O" */
0x38, 0x8a, 0xc, 0x18, 0x30, 0x60, 0xa2, 0x38,
/* U+50 "P" */
0xfa, 0x18, 0x61, 0xfa, 0x8, 0x20, 0x80,
/* U+51 "Q" */
0x38, 0x8a, 0xc, 0x18, 0x30, 0x60, 0xa2, 0x3c,
0xc,
/* U+52 "R" */
0xfa, 0x18, 0x61, 0xfa, 0x28, 0xa1, 0x84,
/* U+53 "S" */
0x7a, 0x38, 0x70, 0x30, 0x38, 0x61, 0x78,
/* U+54 "T" */
0xfe, 0x20, 0x40, 0x81, 0x2, 0x4, 0x8, 0x10,
/* U+55 "U" */
0x86, 0x18, 0x61, 0x86, 0x18, 0x73, 0x78,
/* U+56 "V" */
0xc2, 0x85, 0x1a, 0x22, 0x45, 0x8a, 0xc, 0x18,
/* U+57 "W" */
0xc4, 0x53, 0x14, 0xa5, 0x2b, 0x4a, 0x8c, 0xa3,
0x18, 0xc6, 0x31, 0x0,
/* U+58 "X" */
0x42, 0xc8, 0xb0, 0xc1, 0x7, 0xb, 0x32, 0x42,
/* U+59 "Y" */
0xc6, 0x89, 0xb1, 0x42, 0x82, 0x4, 0x8, 0x10,
/* U+5A "Z" */
0xfc, 0x30, 0x84, 0x30, 0x84, 0x30, 0xfc,
/* U+5B "[" */
0xea, 0xaa, 0xaa, 0xc0,
/* U+5C "\\" */
0x82, 0x10, 0xc2, 0x10, 0x42, 0x10, 0x40,
/* U+5D "]" */
0xd5, 0x55, 0x55, 0xc0,
/* U+5E "^" */
0x21, 0x14, 0xa5, 0x0,
/* U+5F "_" */
0xf8,
/* U+60 "`" */
0x4c,
/* U+61 "a" */
0x74, 0x42, 0xf8, 0xc5, 0xe0,
/* U+62 "b" */
0x84, 0x21, 0xe9, 0xc6, 0x31, 0x9f, 0x80,
/* U+63 "c" */
0x76, 0x61, 0x8, 0x65, 0xc0,
/* U+64 "d" */
0x8, 0x42, 0xfc, 0xc6, 0x31, 0xcb, 0xc0,
/* U+65 "e" */
0x73, 0x28, 0xbf, 0x83, 0x27, 0x80,
/* U+66 "f" */
0x34, 0x4f, 0x44, 0x44, 0x44,
/* U+67 "g" */
0x7e, 0x63, 0x18, 0xe5, 0xe1, 0x8b, 0x80,
/* U+68 "h" */
0x84, 0x21, 0xe8, 0xc6, 0x31, 0x8c, 0x40,
/* U+69 "i" */
0xbf, 0x80,
/* U+6A "j" */
0x45, 0x55, 0x57,
/* U+6B "k" */
0x84, 0x21, 0x2b, 0x73, 0x94, 0x94, 0x40,
/* U+6C "l" */
0xff, 0xc0,
/* U+6D "m" */
0xf7, 0x44, 0x62, 0x31, 0x18, 0x8c, 0x46, 0x22,
/* U+6E "n" */
0xf4, 0x63, 0x18, 0xc6, 0x20,
/* U+6F "o" */
0x7b, 0x38, 0x61, 0x87, 0x37, 0x80,
/* U+70 "p" */
0xf4, 0xe3, 0x18, 0xcf, 0xd0, 0x84, 0x0,
/* U+71 "q" */
0x7e, 0x63, 0x18, 0xe5, 0xe1, 0x8, 0x40,
/* U+72 "r" */
0xf2, 0x49, 0x20,
/* U+73 "s" */
0x74, 0x60, 0xe0, 0xc5, 0xc0,
/* U+74 "t" */
0x4b, 0xa4, 0x92, 0x60,
/* U+75 "u" */
0x8c, 0x63, 0x18, 0xc5, 0xe0,
/* U+76 "v" */
0x89, 0x24, 0x94, 0x30, 0xc2, 0x0,
/* U+77 "w" */
0x88, 0xa4, 0x95, 0x4a, 0xa5, 0x51, 0x10, 0x88,
/* U+78 "x" */
0x49, 0x23, 0xc, 0x31, 0x24, 0x80,
/* U+79 "y" */
0x89, 0x24, 0x94, 0x30, 0xc3, 0x8, 0x23, 0x0,
/* U+7A "z" */
0xf8, 0xc4, 0x44, 0x63, 0xe0,
/* U+7B "{" */
0x29, 0x24, 0xa2, 0x49, 0x22,
/* U+7C "|" */
0xff, 0xe0,
/* U+7D "}" */
0x89, 0x24, 0x8a, 0x49, 0x28,
/* U+7E "~" */
0x66, 0xd9, 0xc0,
/* U+B0 "°" */
0xf7, 0x80,
/* U+F001 "" */
0x0, 0x70, 0x3f, 0x1f, 0xf1, 0xfb, 0x1c, 0x31,
0x83, 0x18, 0x31, 0x83, 0x19, 0xf7, 0x9f, 0xf8,
0x47, 0x0,
/* U+F008 "" */
0xbf, 0xde, 0x7, 0xa0, 0x5e, 0x7, 0xbf, 0xde,
0x7, 0xa0, 0x5e, 0x7, 0xbf, 0xd0,
/* U+F00B "" */
0xf7, 0xf7, 0xbf, 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34, 0x38, 0xdf, 0xda,
0xfe, 0x57, 0xf6, 0xbf, 0x8d, 0x1c, 0xd0, 0x61,
0x80, 0x18,
/* U+F03E "" */
0xff, 0xf9, 0xff, 0x9f, 0xf9, 0xef, 0xfc, 0x7d,
0x83, 0xc0, 0x38, 0x3, 0xff, 0xf0,
/* U+F048 "" */
0xc3, 0xc7, 0xcf, 0xdf, 0xff, 0xff, 0xdf, 0xcf,
0xc7, 0xc3,
/* U+F04B "" */
0x0, 0x1c, 0x3, 0xe0, 0x7f, 0xf, 0xf9, 0xff,
0xbf, 0xff, 0xfe, 0xff, 0x9f, 0xc3, 0xe0, 0x70,
0x0, 0x0,
/* U+F04C "" */
0xfb, 0xff, 0x7f, 0xef, 0xfd, 0xff, 0xbf, 0xf7,
0xfe, 0xff, 0xdf, 0xfb, 0xff, 0x7c,
/* U+F04D "" */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xfc,
/* U+F051 "" */
0xc3, 0xe3, 0xf3, 0xfb, 0xff, 0xff, 0xfb, 0xf3,
0xe3, 0xc3,
/* U+F052 "" */
0xc, 0x3, 0xc0, 0x7c, 0x1f, 0xc7, 0xfd, 0xff,
0xbf, 0xf0, 0x0, 0xff, 0xff, 0xff, 0xff, 0x80,
/* U+F053 "" */
0xc, 0x73, 0x9c, 0xe3, 0x87, 0xe, 0x1c, 0x30,
/* U+F054 "" */
0x83, 0x87, 0xe, 0x1c, 0x73, 0x9c, 0xe2, 0x0,
/* U+F067 "" */
0xe, 0x1, 0xc0, 0x38, 0x7, 0xf, 0xff, 0xff,
0xc3, 0x80, 0x70, 0xe, 0x1, 0xc0,
/* U+F068 "" */
0xff, 0xff, 0xfc,
/* U+F06E "" */
0xf, 0x81, 0xc7, 0x1c, 0x1d, 0xc6, 0x7e, 0xfb,
0xf7, 0xdd, 0xdd, 0xc7, 0x1c, 0xf, 0x80,
/* U+F070 "" */
0x0, 0x1, 0xc0, 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"" */
0xff, 0xff, 0x80, 0x1f, 0x78, 0x3e, 0xf0, 0x3d,
0xe0, 0x78, 0x1, 0xff, 0xff, 0x80,
/* U+F243 "" */
0xff, 0xff, 0x80, 0x1f, 0x60, 0x3e, 0xc0, 0x3d,
0x80, 0x78, 0x1, 0xff, 0xff, 0x80,
/* U+F244 "" */
0xff, 0xff, 0x80, 0x1f, 0x0, 0x3e, 0x0, 0x3c,
0x0, 0x78, 0x1, 0xff, 0xff, 0x80,
/* U+F287 "" */
0x0, 0xc0, 0x7, 0x80, 0x10, 0x7, 0x20, 0x6f,
0xff, 0xfc, 0x41, 0x80, 0x40, 0x0, 0xb8, 0x0,
0xf0,
/* U+F293 "" */
0x3e, 0x3b, 0x9c, 0xdb, 0x7c, 0xbf, 0x1f, 0x9f,
0x87, 0xd5, 0xf9, 0x9d, 0xc7, 0xc0,
/* U+F2ED "" */
0xe, 0x1f, 0xfc, 0x0, 0x0, 0x7, 0xfc, 0xd5,
0x9a, 0xb3, 0x56, 0x6a, 0xcd, 0x59, 0xab, 0x3f,
0xe0,
/* U+F304 "" */
0x0, 0x0, 0xe, 0x0, 0xf0, 0x37, 0x7, 0xa0,
0xfc, 0x1f, 0x83, 0xf0, 0x7e, 0xf, 0xc0, 0xf8,
0xf, 0x0, 0x80, 0x0,
/* U+F55A "" */
0xf, 0xfe, 0x3f, 0xfc, 0xfb, 0x3b, 0xf0, 0xff,
0xf3, 0xef, 0xc3, 0xcf, 0xb7, 0x8f, 0xff, 0xf,
0xfe,
/* U+F7C2 "" */
0x1f, 0x9a, 0xbe, 0xaf, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xf8,
/* U+F8A2 "" */
0x0, 0x0, 0x3, 0x30, 0x37, 0x3, 0xff, 0xff,
0xff, 0x70, 0x3, 0x0
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 48, .box_w = 1, .box_h = 1, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1, .adv_w = 49, .box_w = 1, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 3, .adv_w = 61, .box_w = 2, .box_h = 3, .ofs_x = 1, .ofs_y = 7},
{.bitmap_index = 4, .adv_w = 120, .box_w = 7, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 12, .adv_w = 108, .box_w = 6, .box_h = 12, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 21, .adv_w = 141, .box_w = 8, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 30, .adv_w = 119, .box_w = 7, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 38, .adv_w = 33, .box_w = 1, .box_h = 3, .ofs_x = 1, .ofs_y = 7},
{.bitmap_index = 39, .adv_w = 66, .box_w = 3, .box_h = 13, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 44, .adv_w = 67, .box_w = 3, .box_h = 13, .ofs_x = 0, .ofs_y = -3},
{.bitmap_index = 49, .adv_w = 83, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 4},
{.bitmap_index = 53, .adv_w = 109, .box_w = 6, .box_h = 7, .ofs_x = 1, .ofs_y = 1},
{.bitmap_index = 59, .adv_w = 38, .box_w = 2, .box_h = 3, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 60, .adv_w = 53, .box_w = 3, .box_h = 1, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 61, .adv_w = 51, .box_w = 1, .box_h = 1, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 62, .adv_w = 79, .box_w = 5, .box_h = 10, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 69, .adv_w = 108, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 75, .adv_w = 108, .box_w = 3, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 79, .adv_w = 108, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 85, .adv_w = 108, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 91, .adv_w = 108, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 98, .adv_w = 108, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 104, .adv_w = 108, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 110, .adv_w = 108, .box_w = 6, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 117, .adv_w = 108, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 123, .adv_w = 108, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 129, .adv_w = 47, .box_w = 1, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 130, .adv_w = 41, .box_w = 1, .box_h = 8, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 131, .adv_w = 98, .box_w = 5, .box_h = 6, .ofs_x = 1, .ofs_y = 1},
{.bitmap_index = 135, .adv_w = 105, .box_w = 5, .box_h = 4, .ofs_x = 1, .ofs_y = 3},
{.bitmap_index = 138, .adv_w = 100, .box_w = 5, .box_h = 6, .ofs_x = 1, .ofs_y = 1},
{.bitmap_index = 142, .adv_w = 91, .box_w = 5, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 148, .adv_w = 172, .box_w = 10, .box_h = 12, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 163, .adv_w = 125, .box_w = 8, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 172, .adv_w = 120, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 179, .adv_w = 125, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 186, .adv_w = 126, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 193, .adv_w = 109, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 199, .adv_w = 106, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 205, .adv_w = 131, .box_w = 7, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 213, .adv_w = 137, .box_w = 7, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 221, .adv_w = 52, .box_w = 1, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 223, .adv_w = 106, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 229, .adv_w = 120, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 236, .adv_w = 103, .box_w = 5, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 242, .adv_w = 168, .box_w = 8, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 251, .adv_w = 137, .box_w = 7, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 259, .adv_w = 132, .box_w = 7, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 267, .adv_w = 121, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 274, .adv_w = 132, .box_w = 7, .box_h = 10, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 283, .adv_w = 118, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 290, .adv_w = 114, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 297, .adv_w = 115, .box_w = 7, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 305, .adv_w = 125, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 312, .adv_w = 122, .box_w = 7, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 320, .adv_w = 170, .box_w = 10, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 332, .adv_w = 120, .box_w = 7, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 340, .adv_w = 115, .box_w = 7, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 348, .adv_w = 115, .box_w = 6, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 355, .adv_w = 51, .box_w = 2, .box_h = 13, .ofs_x = 1, .ofs_y = -2},
{.bitmap_index = 359, .adv_w = 79, .box_w = 5, .box_h = 10, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 366, .adv_w = 51, .box_w = 2, .box_h = 13, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 370, .adv_w = 80, .box_w = 5, .box_h = 5, .ofs_x = 0, .ofs_y = 5},
{.bitmap_index = 374, .adv_w = 87, .box_w = 5, .box_h = 1, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 375, .adv_w = 59, .box_w = 3, .box_h = 2, .ofs_x = 0, .ofs_y = 8},
{.bitmap_index = 376, .adv_w = 104, .box_w = 5, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 381, .adv_w = 108, .box_w = 5, .box_h = 10, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 388, .adv_w = 101, .box_w = 5, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 393, .adv_w = 108, .box_w = 5, .box_h = 10, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 400, .adv_w = 102, .box_w = 6, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 406, .adv_w = 67, .box_w = 4, .box_h = 10, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 411, .adv_w = 108, .box_w = 5, .box_h = 10, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 418, .adv_w = 106, .box_w = 5, .box_h = 10, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 425, .adv_w = 47, .box_w = 1, .box_h = 9, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 427, .adv_w = 46, .box_w = 2, .box_h = 12, .ofs_x = 0, .ofs_y = -3},
{.bitmap_index = 430, .adv_w = 97, .box_w = 5, .box_h = 10, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 437, .adv_w = 47, .box_w = 1, .box_h = 10, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 439, .adv_w = 168, .box_w = 9, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 447, .adv_w = 106, .box_w = 5, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 452, .adv_w = 110, .box_w = 6, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 458, .adv_w = 108, .box_w = 5, .box_h = 10, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 465, .adv_w = 109, .box_w = 5, .box_h = 10, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 472, .adv_w = 65, .box_w = 3, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 475, .adv_w = 99, .box_w = 5, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 480, .adv_w = 63, .box_w = 3, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 484, .adv_w = 106, .box_w = 5, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 489, .adv_w = 93, .box_w = 6, .box_h = 7, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 495, .adv_w = 144, .box_w = 9, .box_h = 7, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 503, .adv_w = 95, .box_w = 6, .box_h = 7, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 509, .adv_w = 91, .box_w = 6, .box_h = 10, .ofs_x = 0, .ofs_y = -3},
{.bitmap_index = 517, .adv_w = 95, .box_w = 5, .box_h = 7, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 522, .adv_w = 65, .box_w = 3, .box_h = 13, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 527, .adv_w = 47, .box_w = 1, .box_h = 11, .ofs_x = 1, .ofs_y = -2},
{.bitmap_index = 529, .adv_w = 65, .box_w = 3, .box_h = 13, .ofs_x = 0, .ofs_y = -3},
{.bitmap_index = 534, .adv_w = 131, .box_w = 6, .box_h = 3, .ofs_x = 1, .ofs_y = 3},
{.bitmap_index = 537, .adv_w = 72, .box_w = 3, .box_h = 3, .ofs_x = 1, .ofs_y = 6},
{.bitmap_index = 539, .adv_w = 192, .box_w = 12, .box_h = 12, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 557, .adv_w = 192, .box_w = 12, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 571, .adv_w = 192, .box_w = 13, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 589, .adv_w = 192, .box_w = 12, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 603, .adv_w = 132, .box_w = 8, .box_h = 8, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 611, .adv_w = 192, .box_w = 12, .box_h = 12, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 629, .adv_w = 192, .box_w = 12, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 646, .adv_w = 216, .box_w = 14, .box_h = 10, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 664, .adv_w = 192, .box_w = 12, .box_h = 12, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 682, .adv_w = 216, .box_w = 14, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 698, .adv_w = 192, .box_w = 12, .box_h = 13, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 718, .adv_w = 96, .box_w = 6, .box_h = 8, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 724, .adv_w = 144, .box_w = 9, .box_h = 8, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 733, .adv_w = 216, .box_w = 13, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 751, .adv_w = 192, .box_w = 12, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 765, .adv_w = 168, .box_w = 8, .box_h = 10, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 775, .adv_w = 168, .box_w = 11, .box_h = 13, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 793, .adv_w = 168, .box_w = 11, .box_h = 10, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 807, .adv_w = 168, .box_w = 11, .box_h = 10, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 821, .adv_w = 168, .box_w = 8, .box_h = 10, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 831, .adv_w = 168, .box_w = 11, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 847, .adv_w = 120, .box_w = 6, .box_h = 10, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 855, .adv_w = 120, .box_w = 6, .box_h = 10, .ofs_x = 1, .ofs_y = -1},
{.bitmap_index = 863, .adv_w = 168, .box_w = 11, .box_h = 10, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 877, .adv_w = 168, .box_w = 11, .box_h = 2, .ofs_x = 0, .ofs_y = 3},
{.bitmap_index = 880, .adv_w = 216, .box_w = 13, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 895, .adv_w = 240, .box_w = 15, .box_h = 13, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 920, .adv_w = 216, .box_w = 14, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 940, .adv_w = 192, .box_w = 12, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 957, .adv_w = 168, .box_w = 10, .box_h = 7, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 966, .adv_w = 168, .box_w = 10, .box_h = 7, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 975, .adv_w = 240, .box_w = 15, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 992, .adv_w = 192, .box_w = 12, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1006, .adv_w = 192, .box_w = 12, .box_h = 12, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1024, .adv_w = 192, .box_w = 12, .box_h = 13, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1044, .adv_w = 168, .box_w = 11, .box_h = 10, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1058, .adv_w = 168, .box_w = 11, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1074, .adv_w = 168, .box_w = 11, .box_h = 10, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1088, .adv_w = 120, .box_w = 8, .box_h = 12, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1100, .adv_w = 168, .box_w = 10, .box_h = 12, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1115, .adv_w = 168, .box_w = 11, .box_h = 12, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1132, .adv_w = 216, .box_w = 14, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1148, .adv_w = 192, .box_w = 12, .box_h = 13, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1168, .adv_w = 144, .box_w = 9, .box_h = 12, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1182, .adv_w = 240, .box_w = 15, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1203, .adv_w = 240, .box_w = 15, .box_h = 7, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1217, .adv_w = 240, .box_w = 15, .box_h = 7, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1231, .adv_w = 240, .box_w = 15, .box_h = 7, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1245, .adv_w = 240, .box_w = 15, .box_h = 7, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1259, .adv_w = 240, .box_w = 15, .box_h = 7, .ofs_x = 0, .ofs_y = 1},
{.bitmap_index = 1273, .adv_w = 240, .box_w = 15, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1290, .adv_w = 168, .box_w = 9, .box_h = 12, .ofs_x = 1, .ofs_y = -2},
{.bitmap_index = 1304, .adv_w = 168, .box_w = 11, .box_h = 12, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1321, .adv_w = 192, .box_w = 12, .box_h = 13, .ofs_x = 0, .ofs_y = -2},
{.bitmap_index = 1341, .adv_w = 240, .box_w = 15, .box_h = 9, .ofs_x = 0, .ofs_y = 0},
{.bitmap_index = 1358, .adv_w = 144, .box_w = 10, .box_h = 11, .ofs_x = 0, .ofs_y = -1},
{.bitmap_index = 1372, .adv_w = 193, .box_w = 12, .box_h = 8, .ofs_x = 0, .ofs_y = 1}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
static const uint16_t unicode_list_1[] = {
0x0, 0xef51, 0xef58, 0xef5b, 0xef5c, 0xef5d, 0xef61, 0xef63,
0xef65, 0xef69, 0xef6c, 0xef71, 0xef76, 0xef77, 0xef78, 0xef8e,
0xef98, 0xef9b, 0xef9c, 0xef9d, 0xefa1, 0xefa2, 0xefa3, 0xefa4,
0xefb7, 0xefb8, 0xefbe, 0xefc0, 0xefc1, 0xefc4, 0xefc7, 0xefc8,
0xefc9, 0xefcb, 0xefe3, 0xefe5, 0xf014, 0xf015, 0xf017, 0xf037,
0xf03a, 0xf043, 0xf06c, 0xf074, 0xf0ab, 0xf13b, 0xf190, 0xf191,
0xf192, 0xf193, 0xf194, 0xf1d7, 0xf1e3, 0xf23d, 0xf254, 0xf4aa,
0xf712, 0xf7f2
};
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 32, .range_length = 95, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
},
{
.range_start = 176, .range_length = 63475, .glyph_id_start = 96,
.unicode_list = unicode_list_1, .glyph_id_ofs_list = NULL, .list_length = 58, .type = LV_FONT_FMT_TXT_CMAP_SPARSE_TINY
}
};
/*-----------------
* KERNING
*----------------*/
/*Pair left and right glyphs for kerning*/
static const uint8_t kern_pair_glyph_ids[] =
{
1, 53,
3, 3,
3, 8,
3, 34,
3, 66,
3, 68,
3, 69,
3, 70,
3, 72,
3, 78,
3, 79,
3, 80,
3, 81,
3, 82,
3, 84,
3, 88,
8, 3,
8, 8,
8, 34,
8, 66,
8, 68,
8, 69,
8, 70,
8, 72,
8, 78,
8, 79,
8, 80,
8, 81,
8, 82,
8, 84,
8, 88,
9, 55,
9, 56,
9, 58,
13, 3,
13, 8,
15, 3,
15, 8,
16, 16,
34, 3,
34, 8,
34, 32,
34, 36,
34, 40,
34, 48,
34, 50,
34, 53,
34, 54,
34, 55,
34, 56,
34, 58,
34, 80,
34, 85,
34, 86,
34, 87,
34, 88,
34, 90,
34, 91,
35, 53,
35, 55,
35, 58,
36, 10,
36, 53,
36, 62,
36, 94,
37, 13,
37, 15,
37, 34,
37, 53,
37, 55,
37, 57,
37, 58,
37, 59,
38, 53,
38, 68,
38, 69,
38, 70,
38, 71,
38, 72,
38, 80,
38, 82,
38, 86,
38, 87,
38, 88,
38, 90,
39, 13,
39, 15,
39, 34,
39, 43,
39, 53,
39, 66,
39, 68,
39, 69,
39, 70,
39, 72,
39, 80,
39, 82,
39, 83,
39, 86,
39, 87,
39, 90,
41, 34,
41, 53,
41, 57,
41, 58,
42, 34,
42, 53,
42, 57,
42, 58,
43, 34,
44, 14,
44, 36,
44, 40,
44, 48,
44, 50,
44, 68,
44, 69,
44, 70,
44, 72,
44, 78,
44, 79,
44, 80,
44, 81,
44, 82,
44, 86,
44, 87,
44, 88,
44, 90,
45, 3,
45, 8,
45, 34,
45, 36,
45, 40,
45, 48,
45, 50,
45, 53,
45, 54,
45, 55,
45, 56,
45, 58,
45, 86,
45, 87,
45, 88,
45, 90,
46, 34,
46, 53,
46, 57,
46, 58,
47, 34,
47, 53,
47, 57,
47, 58,
48, 13,
48, 15,
48, 34,
48, 53,
48, 55,
48, 57,
48, 58,
48, 59,
49, 13,
49, 15,
49, 34,
49, 43,
49, 57,
49, 59,
49, 66,
49, 68,
49, 69,
49, 70,
49, 72,
49, 80,
49, 82,
49, 85,
49, 87,
49, 90,
50, 53,
50, 55,
50, 56,
50, 58,
51, 53,
51, 55,
51, 58,
53, 1,
53, 13,
53, 14,
53, 15,
53, 34,
53, 36,
53, 40,
53, 43,
53, 48,
53, 50,
53, 52,
53, 53,
53, 55,
53, 56,
53, 58,
53, 66,
53, 68,
53, 69,
53, 70,
53, 72,
53, 78,
53, 79,
53, 80,
53, 81,
53, 82,
53, 83,
53, 84,
53, 86,
53, 87,
53, 88,
53, 89,
53, 90,
53, 91,
54, 34,
55, 10,
55, 13,
55, 14,
55, 15,
55, 34,
55, 36,
55, 40,
55, 48,
55, 50,
55, 62,
55, 66,
55, 68,
55, 69,
55, 70,
55, 72,
55, 80,
55, 82,
55, 83,
55, 86,
55, 87,
55, 90,
55, 94,
56, 10,
56, 13,
56, 14,
56, 15,
56, 34,
56, 53,
56, 62,
56, 66,
56, 68,
56, 69,
56, 70,
56, 72,
56, 80,
56, 82,
56, 83,
56, 86,
56, 94,
57, 14,
57, 36,
57, 40,
57, 48,
57, 50,
57, 55,
57, 68,
57, 69,
57, 70,
57, 72,
57, 80,
57, 82,
57, 86,
57, 87,
57, 90,
58, 7,
58, 10,
58, 11,
58, 13,
58, 14,
58, 15,
58, 34,
58, 36,
58, 40,
58, 43,
58, 48,
58, 50,
58, 52,
58, 53,
58, 54,
58, 55,
58, 56,
58, 57,
58, 58,
58, 62,
58, 66,
58, 68,
58, 69,
58, 70,
58, 71,
58, 72,
58, 78,
58, 79,
58, 80,
58, 81,
58, 82,
58, 83,
58, 84,
58, 85,
58, 86,
58, 87,
58, 89,
58, 90,
58, 91,
58, 94,
59, 34,
59, 36,
59, 40,
59, 48,
59, 50,
59, 68,
59, 69,
59, 70,
59, 72,
59, 80,
59, 82,
59, 86,
59, 87,
59, 88,
59, 90,
60, 43,
60, 54,
66, 3,
66, 8,
66, 87,
66, 90,
67, 3,
67, 8,
67, 87,
67, 89,
67, 90,
67, 91,
68, 3,
68, 8,
70, 3,
70, 8,
70, 87,
70, 90,
71, 3,
71, 8,
71, 10,
71, 62,
71, 68,
71, 69,
71, 70,
71, 72,
71, 82,
71, 94,
73, 3,
73, 8,
76, 68,
76, 69,
76, 70,
76, 72,
76, 82,
78, 3,
78, 8,
79, 3,
79, 8,
80, 3,
80, 8,
80, 87,
80, 89,
80, 90,
80, 91,
81, 3,
81, 8,
81, 87,
81, 89,
81, 90,
81, 91,
83, 3,
83, 8,
83, 13,
83, 15,
83, 66,
83, 68,
83, 69,
83, 70,
83, 71,
83, 72,
83, 80,
83, 82,
83, 85,
83, 87,
83, 88,
83, 90,
85, 80,
87, 3,
87, 8,
87, 13,
87, 15,
87, 66,
87, 68,
87, 69,
87, 70,
87, 71,
87, 72,
87, 80,
87, 82,
88, 13,
88, 15,
89, 68,
89, 69,
89, 70,
89, 72,
89, 80,
89, 82,
90, 3,
90, 8,
90, 13,
90, 15,
90, 66,
90, 68,
90, 69,
90, 70,
90, 71,
90, 72,
90, 80,
90, 82,
91, 68,
91, 69,
91, 70,
91, 72,
91, 80,
91, 82,
92, 43,
92, 54
};
/* Kerning between the respective left and right glyphs
* 4.4 format which needs to scaled with `kern_scale`*/
static const int8_t kern_pair_values[] =
{
-4, -10, -10, -11, -5, -6, -6, -6,
-6, -2, -2, -6, -2, -6, -7, 1,
-10, -10, -11, -5, -6, -6, -6, -6,
-2, -2, -6, -2, -6, -7, 1, 2,
2, 2, -16, -16, -16, -16, -21, -11,
-11, -6, -1, -1, -1, -1, -12, -2,
-8, -6, -9, -1, -2, -1, -5, -3,
-5, 1, -3, -2, -5, -2, -3, -1,
-2, -10, -10, -2, -3, -2, -2, -4,
-2, 2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -22, -22, -16,
-25, 2, -3, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, 2, -3, 2,
-3, 2, -3, 2, -3, -2, -6, -3,
-3, -3, -3, -2, -2, -2, -2, -2,
-2, -3, -2, -2, -2, -4, -6, -4,
-31, -31, 2, -6, -6, -6, -6, -26,
-5, -16, -13, -22, -4, -12, -9, -12,
2, -3, 2, -3, 2, -3, 2, -3,
-10, -10, -2, -3, -2, -2, -4, -2,
-30, -30, -13, -19, -3, -2, -1, -1,
-1, -1, -1, -1, -1, 1, 1, 1,
-4, -3, -2, -3, -7, -2, -4, -4,
-20, -22, -20, -7, -3, -3, -22, -3,
-3, -1, 2, 2, 1, 2, -11, -9,
-9, -9, -9, -10, -10, -9, -10, -9,
-7, -11, -9, -7, -5, -7, -7, -6,
-2, 2, -21, -3, -21, -7, -1, -1,
-1, -1, 2, -4, -4, -4, -4, -4,
-4, -4, -3, -3, -1, -1, 2, 1,
-12, -6, -12, -4, 1, 1, -3, -3,
-3, -3, -3, -3, -3, -2, -2, 1,
-4, -2, -2, -2, -2, 1, -2, -2,
-2, -2, -2, -2, -2, -3, -3, -3,
2, -5, -20, -5, -20, -9, -3, -3,
-9, -3, -3, -1, 2, -9, 2, 2,
1, 2, 2, -7, -6, -6, -6, -2,
-6, -4, -4, -6, -4, -6, -4, -5,
-2, -4, -2, -2, -2, -3, 2, 1,
-2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -3, -3, -3, -2, -2,
-6, -6, -1, -1, -3, -3, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
2, 2, 2, 2, -2, -2, -2, -2,
-2, 2, -10, -10, -2, -2, -2, -2,
-2, -10, -10, -10, -10, -13, -13, -1,
-2, -1, -1, -3, -3, -1, -1, -1,
-1, 2, 2, -12, -12, -4, -2, -2,
-2, 1, -2, -2, -2, 5, 2, 2,
2, -2, 1, 1, -10, -10, -1, -1,
-1, -1, 1, -1, -1, -1, -12, -12,
-2, -2, -2, -2, -2, -2, 1, 1,
-10, -10, -1, -1, -1, -1, 1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-2, -2
};
/*Collect the kern pair's data in one place*/
static const lv_font_fmt_txt_kern_pair_t kern_pairs =
{
.glyph_ids = kern_pair_glyph_ids,
.values = kern_pair_values,
.pair_cnt = 434,
.glyph_ids_size = 0
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
/*Store all the custom data of the font*/
static lv_font_fmt_txt_dsc_t font_dsc = {
.glyph_bitmap = gylph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = &kern_pairs,
.kern_scale = 16,
.cmap_num = 2,
.bpp = 1,
.kern_classes = 0,
.bitmap_format = 0
};
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
lv_font_t oled_12_font_symbol = {
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 14, /*The maximum line height required by the font*/
.base_line = 3, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
.dsc = &font_dsc /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
};
#endif /*#if OLED_12_FONT_SYMBOL*/
| 28.003837 | 126 | 0.47798 | [
"3d"
] |
53fd8e94e47dcdf49576bc2974d0e35a25a50fb2 | 12,375 | h | C | kythe/cxx/indexer/cxx/IndexerFrontendAction.h | bef0/kythe | 2adcb540ae9dbd61879315a5ade8d3716ee3d3d8 | [
"Apache-2.0"
] | null | null | null | kythe/cxx/indexer/cxx/IndexerFrontendAction.h | bef0/kythe | 2adcb540ae9dbd61879315a5ade8d3716ee3d3d8 | [
"Apache-2.0"
] | null | null | null | kythe/cxx/indexer/cxx/IndexerFrontendAction.h | bef0/kythe | 2adcb540ae9dbd61879315a5ade8d3716ee3d3d8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// \file IndexerFrontendAction.h
/// \brief Defines a tool that passes notifications to a `GraphObserver`.
#ifndef KYTHE_CXX_INDEXER_CXX_INDEXER_FRONTEND_ACTION_H_
#define KYTHE_CXX_INDEXER_CXX_INDEXER_FRONTEND_ACTION_H_
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <functional>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include "GraphObserver.h"
#include "IndexerASTHooks.h"
#include "IndexerPPCallbacks.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/Tooling.h"
#include "glog/logging.h"
#include "kythe/cxx/common/kythe_metadata_file.h"
#include "kythe/cxx/extractor/cxx_details.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
namespace kythe {
namespace proto {
class CompilationUnit;
class FileData;
} // namespace proto
class KytheClaimClient;
/// \brief Runs a given tool on a piece of code with a given assumed filename.
/// \returns true on success, false on failure.
bool RunToolOnCode(std::unique_ptr<clang::FrontendAction> tool_action,
llvm::Twine code, const std::string& filename);
// A FrontendAction that extracts information about a translation unit both
// from its AST (using an ASTConsumer) and from preprocessing (with a
// PPCallbacks implementation).
//
// TODO(jdennett): Test/implement/document the rest of this.
//
// TODO(jdennett): Consider moving/renaming this to kythe::ExtractIndexAction.
class IndexerFrontendAction : public clang::ASTFrontendAction {
public:
IndexerFrontendAction(
GraphObserver* GO, const HeaderSearchInfo* Info,
std::function<bool()> ShouldStopIndexing,
std::function<std::unique_ptr<IndexerWorklist>(IndexerASTVisitor*)>
CreateWorklist,
const LibrarySupports* LibrarySupports)
: Observer(CHECK_NOTNULL(GO)),
HeaderConfigValid(Info != nullptr),
Supports(*CHECK_NOTNULL(LibrarySupports)),
ShouldStopIndexing(std::move(ShouldStopIndexing)),
CreateWorklist(std::move(CreateWorklist)) {
if (HeaderConfigValid) {
HeaderConfig = *Info;
}
}
/// \brief Barrel through even if we don't understand part of a program?
/// \param I The behavior to use when an unimplemented entity is encountered.
void setIgnoreUnimplemented(BehaviorOnUnimplemented B) {
IgnoreUnimplemented = B;
}
/// \brief Visit template instantiations?
/// \param T The behavior to use for template instantiations.
void setTemplateMode(BehaviorOnTemplates T) { TemplateMode = T; }
/// \brief Emit all data?
/// \param V Degree of verbosity.
void setVerbosity(Verbosity V) { Verbosity = V; }
/// \brief Emit comments for forward declared classes as documentation?
/// \param B Behavior to use.
void setObjCFwdDeclEmitDocs(BehaviorOnFwdDeclComments B) { ObjCFwdDocs = B; }
/// \brief Emit comments for forward declarations as documentation?
/// \param B Behavior to use.
void setCppFwdDeclEmitDocs(BehaviorOnFwdDeclComments B) { CppFwdDocs = B; }
/// \brief Use this many raw bytes for USRs.
void setUsrByteSize(int S) { UsrByteSize = S; }
private:
std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
clang::CompilerInstance& CI, llvm::StringRef Filename) override {
if (HeaderConfigValid) {
auto& HeaderSearch = CI.getPreprocessor().getHeaderSearchInfo();
auto& FileManager = CI.getFileManager();
std::vector<clang::DirectoryLookup> Lookups;
unsigned CurrentIdx = 0;
for (const auto& Path : HeaderConfig.paths) {
const clang::DirectoryEntry* DirEnt =
FileManager.getDirectory(Path.path);
if (DirEnt != nullptr) {
Lookups.push_back(clang::DirectoryLookup(
DirEnt, Path.characteristic_kind, Path.is_framework));
++CurrentIdx;
} else {
// This can happen if a path was included in the HeaderSearchInfo,
// but no headers were found underneath that path during extraction.
// We'll prune out that path here.
if (CurrentIdx < HeaderConfig.angled_dir_idx) {
--HeaderConfig.angled_dir_idx;
}
if (CurrentIdx < HeaderConfig.system_dir_idx) {
--HeaderConfig.system_dir_idx;
}
}
}
HeaderSearch.ClearFileInfo();
HeaderSearch.SetSearchPaths(Lookups, HeaderConfig.angled_dir_idx,
HeaderConfig.system_dir_idx, false);
HeaderSearch.SetSystemHeaderPrefixes(HeaderConfig.system_prefixes);
}
if (Observer) {
Observer->setSourceManager(&CI.getSourceManager());
Observer->setLangOptions(&CI.getLangOpts());
Observer->setPreprocessor(&CI.getPreprocessor());
}
return llvm::make_unique<IndexerASTConsumer>(
Observer, IgnoreUnimplemented, TemplateMode, Verbosity, ObjCFwdDocs,
CppFwdDocs, Supports, ShouldStopIndexing, CreateWorklist, UsrByteSize);
}
bool BeginSourceFileAction(clang::CompilerInstance& CI) override {
if (Observer) {
CI.getPreprocessor().addPPCallbacks(llvm::make_unique<IndexerPPCallbacks>(
CI.getPreprocessor(), *Observer, Verbosity));
}
CI.getLangOpts().CommentOpts.ParseAllComments = true;
CI.getLangOpts().RetainCommentsFromSystemHeaders = true;
return true;
}
bool usesPreprocessorOnly() const override { return false; }
/// The `GraphObserver` used for reporting information.
GraphObserver* Observer;
/// Whether to die on missing cases or to continue onward.
BehaviorOnUnimplemented IgnoreUnimplemented = BehaviorOnUnimplemented::Abort;
/// Whether to visit template instantiations.
BehaviorOnTemplates TemplateMode = BehaviorOnTemplates::VisitInstantiations;
/// Whether to emit all data.
enum Verbosity Verbosity = kythe::Verbosity::Classic;
/// Should we emit documentation for forward class decls in ObjC?
BehaviorOnFwdDeclComments ObjCFwdDocs = BehaviorOnFwdDeclComments::Emit;
/// Should we emit documentation for forward decls in C++?
BehaviorOnFwdDeclComments CppFwdDocs = BehaviorOnFwdDeclComments::Emit;
/// Configuration information for header search.
HeaderSearchInfo HeaderConfig;
/// Whether to use HeaderConfig.
bool HeaderConfigValid;
/// Library-specific callbacks.
const LibrarySupports& Supports;
/// \return true if indexing should be cancelled.
std::function<bool()> ShouldStopIndexing = [] { return false; };
/// \return a new worklist for the given visitor.
std::function<std::unique_ptr<IndexerWorklist>(IndexerASTVisitor*)>
CreateWorklist;
/// \brief The number of (raw) bytes to use to represent a USR. If 0,
/// no USRs will be recorded.
int UsrByteSize = 0;
};
/// \brief Allows stdin to be replaced with a mapped file.
///
/// `clang::CompilerInstance::InitializeSourceManager` special-cases the path
/// "-" to llvm::MemoryBuffer::getSTDIN() even if "-" has been remapped.
/// This class mutates the frontend input list such that any file input that
/// would trip this logic instead tries to resolve a file named "<stdin>",
/// which is a token used elsewhere in the compiler to refer to standard input.
class StdinAdjustSingleFrontendActionFactory
: public clang::tooling::FrontendActionFactory {
std::unique_ptr<clang::FrontendAction> Action;
public:
/// \param Action The single FrontendAction to run once. Takes ownership.
StdinAdjustSingleFrontendActionFactory(
std::unique_ptr<clang::FrontendAction> Action)
: Action(std::move(Action)) {}
bool runInvocation(
std::shared_ptr<clang::CompilerInvocation> Invocation,
clang::FileManager* Files,
std::shared_ptr<clang::PCHContainerOperations> PCHContainerOps,
clang::DiagnosticConsumer* DiagConsumer) override {
auto& FEOpts = Invocation->getFrontendOpts();
for (auto& Input : FEOpts.Inputs) {
if (Input.isFile() && Input.getFile() == "-") {
Input = clang::FrontendInputFile("<stdin>", Input.getKind(),
Input.isSystem());
}
}
// Disable dependency outputs. The indexer should not write to arbitrary
// files on its host (as dictated by -MD-style flags).
Invocation->getDependencyOutputOpts().OutputFile.clear();
Invocation->getDependencyOutputOpts().HeaderIncludeOutputFile.clear();
Invocation->getDependencyOutputOpts().DOTOutputFile.clear();
Invocation->getDependencyOutputOpts().ModuleDependencyOutputDir.clear();
return clang::tooling::FrontendActionFactory::runInvocation(
Invocation, Files, PCHContainerOps, DiagConsumer);
}
/// Note that FrontendActionFactory::create() specifies that the
/// returned action is owned by the caller.
clang::FrontendAction* create() override { return Action.release(); }
};
/// \brief Options that control how the indexer behaves.
struct IndexerOptions {
/// \brief The directory to normalize paths against. Must be absolute.
std::string EffectiveWorkingDirectory = "/";
/// \brief What to do with template expansions.
BehaviorOnTemplates TemplateBehavior =
BehaviorOnTemplates::VisitInstantiations;
/// \brief What to do when we don't know what to do.
BehaviorOnUnimplemented UnimplementedBehavior =
BehaviorOnUnimplemented::Abort;
/// \brief Whether to emit all data.
enum Verbosity Verbosity = kythe::Verbosity::Classic;
/// \brief Should we emit documentation for forward class decls in ObjC?
BehaviorOnFwdDeclComments ObjCFwdDocs = BehaviorOnFwdDeclComments::Emit;
/// \brief Should we emit documentation for forward decls in C++?
BehaviorOnFwdDeclComments CppFwdDocs = BehaviorOnFwdDeclComments::Emit;
/// \brief Whether to allow access to the raw filesystem.
bool AllowFSAccess = false;
/// \brief Whether to drop data found to be template instantiation
/// independent.
bool DropInstantiationIndependentData = false;
/// \brief A function that is called as the indexer enters and exits various
/// phases of execution (in strict LIFO order).
ProfilingCallback ReportProfileEvent = [](const char*, ProfilingEvent) {};
/// \brief A callback to determine whether to cancel indexing as quickly
/// as possible.
/// \return true if indexing should be cancelled.
std::function<bool()> ShouldStopIndexing = [] { return false; };
/// \brief The number of (raw) bytes to use to represent a USR. If 0,
/// no USRs will be recorded.
int UsrByteSize = 0;
};
/// \brief Indexes `Unit`, reading from `Files` in the assumed and writing
/// entries to `Output`.
/// \param Unit The CompilationUnit to index
/// \param Files A vector of files to read from. May be modified if the Unit
/// does not contain a proper header search table.
/// \param ClaimClient The claim client to use.
/// \param Cache The hash cache to use, or nullptr if none.
/// \param Output The output stream to use.
/// \param Options Configuration settings for this run.
/// \param MetaSupports Metadata support for this run.
/// \param LibrarySupports Library support for this run.
/// \param Worklist A function that generates a new worklist for the given
/// visitor.
/// \return empty if OK; otherwise, an error description.
std::string IndexCompilationUnit(
const proto::CompilationUnit& Unit, std::vector<proto::FileData>& Files,
KytheClaimClient& ClaimClient, HashCache* Cache, KytheCachingOutput& Output,
const IndexerOptions& Options, const MetadataSupports* MetaSupports,
const LibrarySupports* LibrarySupports,
std::function<std::unique_ptr<IndexerWorklist>(IndexerASTVisitor*)>
CreateWorklist);
} // namespace kythe
#endif // KYTHE_CXX_INDEXER_CXX_INDEXER_FRONTEND_ACTION_H_
| 42.235495 | 80 | 0.724606 | [
"vector"
] |
9906a3d6f31d0eda31a7a98bde43906ca9ba3233 | 5,772 | h | C | smtk/extension/vtk/widgets/vtkConeWidget.h | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 40 | 2015-02-21T19:55:54.000Z | 2022-01-06T13:13:05.000Z | smtk/extension/vtk/widgets/vtkConeWidget.h | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 127 | 2015-01-15T20:55:45.000Z | 2021-08-19T17:34:15.000Z | smtk/extension/vtk/widgets/vtkConeWidget.h | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 27 | 2015-03-04T14:17:51.000Z | 2021-12-23T01:05:42.000Z | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#ifndef vtkConeWidget_h
#define vtkConeWidget_h
#include "smtk/extension/vtk/widgets/vtkSMTKWidgetsExtModule.h" // For export macro
#include "vtkAbstractWidget.h"
class vtkConeRepresentation;
/**
* @class vtkConeWidget
* @brief 3D widget for manipulating an infinite cylinder
*
* This 3D widget defines an infinite cylinder that can be
* interactively placed in a scene. The widget is assumed to consist
* of four parts: 1) a cylinder contained in a 2) bounding box, with a
* 3) cylinder axis, which is rooted at a 4) center point in the bounding
* box. (The representation paired with this widget determines the
* actual geometry of the widget.)
*
* To use this widget, you generally pair it with a vtkConeRepresentation
* (or a subclass). Various options are available for controlling how the
* representation appears, and how the widget functions.
*
* @par Event Bindings:
* By default, the widget responds to the following VTK events (i.e., it
* watches the vtkRenderWindowInteractor for these events):
* <pre>
* If the cylinder axis is selected:
* LeftButtonPressEvent - select normal
* LeftButtonReleaseEvent - release (end select) normal
* MouseMoveEvent - orient the normal vector
* If the center point (handle) is selected:
* LeftButtonPressEvent - select handle (if on slider)
* LeftButtonReleaseEvent - release handle (if selected)
* MouseMoveEvent - move the center point (constrained to plane or on the
* axis if CTRL key is pressed)
* If the cylinder is selected:
* LeftButtonPressEvent - select cylinder
* LeftButtonReleaseEvent - release cylinder
* MouseMoveEvent - increase/decrease cylinder radius
* If the outline is selected:
* LeftButtonPressEvent - select outline
* LeftButtonReleaseEvent - release outline
* MouseMoveEvent - move the outline
* If the keypress characters are used
* 'Down/Left' Move cylinder away from viewer
* 'Up/Right' Move cylinder towards viewer
* In all the cases, independent of what is picked, the widget responds to the
* following VTK events:
* MiddleButtonPressEvent - move the cylinder
* MiddleButtonReleaseEvent - release the cylinder
* RightButtonPressEvent - scale the widget's representation
* RightButtonReleaseEvent - stop scaling the widget
* MouseMoveEvent - scale (if right button) or move (if middle button) the widget
* </pre>
*
* @par Event Bindings:
* Note that the event bindings described above can be changed using this
* class's vtkWidgetEventTranslator. This class translates VTK events
* into the vtkConeWidget's widget events:
* <pre>
* vtkWidgetEvent::Select -- some part of the widget has been selected
* vtkWidgetEvent::EndSelect -- the selection process has completed
* vtkWidgetEvent::Move -- a request for widget motion has been invoked
* vtkWidgetEvent::Up and vtkWidgetEvent::Down -- MoveConeAction
* </pre>
*
* @par Event Bindings:
* In turn, when these widget events are processed, the vtkConeWidget
* invokes the following VTK events on itself (which observers can listen for):
* <pre>
* vtkCommand::StartInteractionEvent (on vtkWidgetEvent::Select)
* vtkCommand::EndInteractionEvent (on vtkWidgetEvent::EndSelect)
* vtkCommand::InteractionEvent (on vtkWidgetEvent::Move)
* </pre>
*
*
* @sa
* vtk3DWidget vtkImplicitPlaneWidget
*/
class VTKSMTKWIDGETSEXT_EXPORT vtkConeWidget : public vtkAbstractWidget
{
public:
/**
* Instantiate the object.
*/
static vtkConeWidget* New();
//@{
/**
* Standard vtkObject methods
*/
vtkTypeMacro(vtkConeWidget, vtkAbstractWidget);
void PrintSelf(ostream& os, vtkIndent indent) override;
//@}
vtkConeWidget(const vtkConeWidget&) = delete;
vtkConeWidget& operator=(const vtkConeWidget&) = delete;
/**
* Specify an instance of vtkWidgetRepresentation used to represent this
* widget in the scene. Note that the representation is a subclass of vtkProp
* so it can be added to the renderer independent of the widget.
*/
void SetRepresentation(vtkConeRepresentation* rep);
/// Control widget interactivity, allowing users to interact with the camera or other widgets.
///
/// The camera is unobserved when the widget is disabled.
void SetEnabled(int enabling) override;
/**
* Return the representation as a vtkConeRepresentation.
*/
vtkConeRepresentation* GetConeRepresentation()
{
return reinterpret_cast<vtkConeRepresentation*>(this->WidgetRep);
}
/**
* Create the default widget representation if one is not set.
*/
void CreateDefaultRepresentation() override;
protected:
vtkConeWidget();
~vtkConeWidget() override;
// Manage the state of the widget
int WidgetState;
enum _WidgetState
{
Start = 0,
Active
};
// These methods handle events
static void SelectAction(vtkAbstractWidget*);
static void TranslateAction(vtkAbstractWidget*);
static void ScaleAction(vtkAbstractWidget*);
static void EndSelectAction(vtkAbstractWidget*);
static void MoveAction(vtkAbstractWidget*);
static void MoveConeAction(vtkAbstractWidget*);
/**
* Update the cursor shape based on the interaction state. Returns 1
* if the cursor shape requested is different from the existing one.
*/
int UpdateCursorShape(int interactionState);
};
#endif
| 35.62963 | 96 | 0.720894 | [
"geometry",
"object",
"shape",
"vector",
"3d"
] |
9908473822bb9d08d309eb87b001051a11f264e0 | 146,210 | c | C | Simple-Kernel/startup/memmove.c | moneytech/Simple-Kernel | a8558304774522d8be96b4ebce8625dae9b37457 | [
"BSD-2-Clause-Patent"
] | 1 | 2022-01-27T19:55:02.000Z | 2022-01-27T19:55:02.000Z | Simple-Kernel/startup/memmove.c | moneytech/Simple-Kernel | a8558304774522d8be96b4ebce8625dae9b37457 | [
"BSD-2-Clause-Patent"
] | null | null | null | Simple-Kernel/startup/memmove.c | moneytech/Simple-Kernel | a8558304774522d8be96b4ebce8625dae9b37457 | [
"BSD-2-Clause-Patent"
] | 1 | 2022-01-29T00:13:29.000Z | 2022-01-29T00:13:29.000Z | // Compile with GCC -O3 for best performance
// It pretty much entirely negates the need to write these by hand in asm.
#include "avxmem.h"
// Default (8-bit, 1 byte at a time)
void * memmove (void *dest, const void *src, size_t len)
{
const char *s = (char *)src;
char *d = (char *)dest;
const char *nexts = s + len;
char *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
*d++ = *s++;
}
}
else
{
while (nextd != d)
{
*--nextd = *--nexts;
}
}
return dest;
}
///=============================================================================
/// LICENSING INFORMATION
///=============================================================================
//
// The code above this comment is in the public domain.
// The code below this comment is subject to the custom attribution license found
// here: https://github.com/KNNSpeed/Simple-Kernel/blob/master/LICENSE_KERNEL
//
//==============================================================================
// AVX Memory Functions: AVX Memmove
//==============================================================================
//
// Version 1.45
//
// Author:
// KNNSpeed
//
// Source Code:
// https://github.com/KNNSpeed/Simple-Kernel
//
// Minimum requirement:
// x86_64 CPU with SSE4.1, but AVX2 or later is recommended
//
// This file provides a highly optimized version of memmove.
// Overlapping memory regions are supported.
//
#ifdef __clang__
#define __m128i_u __m128i
#define __m256i_u __m256i
#define __m512i_u __m512i
#endif
#ifdef __AVX512F__
#define BYTE_ALIGNMENT 0x3F // For 64-byte alignment
#elif __AVX__
#define BYTE_ALIGNMENT 0x1F // For 32-byte alignment
#else
#define BYTE_ALIGNMENT 0x0F // For 16-byte alignment
#endif
//
// USAGE INFORMATION:
//
// The "len" argument is "# of x bytes to move," e.g. memmove_512bit_u/a needs
// to know "how many multiples of 512 bit (64 bytes) to move." All functions
// with len follow the same pattern, e.g. memmove_512bit_512B_u/a needs to know
// how many multiples of 512 bytes to move, so a len of 4 tells it to move 2kB.
//
// The "numbytes" argument for functions that use it is just the total
// number of bytes to move.
//
// Some microarchitectural information:
//
// Sources:
// https://www.agner.org/optimize/
// https://software.intel.com/en-us/articles/intel-sdm
// http://blog.stuffedcow.net/2014/01/x86-memory-disambiguation/
//
// It looks as though Haswell and up can do 2 simultaneous aligned loads or 1
// unaligned load in 1 cycle. Alignment means the data is at an address that is
// a multiple of the cache line size, and the CPU most easily loads one cache
// line at a time. All AVX-supporting CPUs have a 64-byte cacheline as of Q4 2018.
// The bottleneck here is stores: only 1 store per cycle can be done (there is
// only 1 store port despite 2 load ports). Unaligned loads/stores that cross
// cache line boundaries typically incur relatively significant cycle penalties,
// though Haswell and up fixed that specifically for unaligned loads.
//
// Unaligned loads on Haswell require both load ports, but, since there is only
// one store port, the store port has to do double-duty for stores that cross
// cache line boundaries. So stores should be contained within cache line sizes
// for best performance. For memmove, this also means there's no point in doing
// 2 separate aligned loads simultaneously if only one can be written at a time.
//
// BUT it turns out that's not the whole story. We can do 2 aligned loads to
// ensure that no cycle is wasted. i.e. instead of this (comma = simultaneously):
// load 1 -> store 1, load 2-> store 2, load 3 -> store 3, load 4 -> store 4 etc.
// we can do this with aligned AVX2 loads:
// load 1, load 2 -> store 1, load 3, load 4 -> store 2, load 5, load 6 -> store 3, etc.
// And this is just per core.
//
// For pure memmove, this provides no real improvement, but loops with many
// iterations that require loading two values, doing math on them, and storing a
// single result can see significant throughput gains. Sandy Bridge could perform
// similarly, but in 2 cycles instead of Haswell's 1 and only for the fewer
// 256-bit AVX calculations it had (Haswell can do any size, AVX2 or otherwise).
//
// Skylake-X, with AVX512, extends Haswell's behavior to include 512-bit values.
//
// If an architecture ever adds 2 store ports, the AVX/(VEX-encoded) SSE
// functions in this file will need to be modified to do 2 loads and 2 stores.
//
//-----------------------------------------------------------------------------
// Individual Functions:
//-----------------------------------------------------------------------------
// 16-bit (2 bytes at a time)
// Len is (# of total bytes/2), so it's "# of 16-bits"
void * memmove_16bit(void *dest, const void *src, size_t len)
{
const uint16_t* s = (uint16_t*)src;
uint16_t* d = (uint16_t*)dest;
const uint16_t *nexts = s + len;
uint16_t *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
*d++ = *s++;
}
}
else
{
while (nextd != d)
{
*--nextd = *--nexts;
}
}
return dest;
}
// 32-bit (4 bytes at a time - 1 pixel in a 32-bit linear frame buffer)
// Len is (# of total bytes/4), so it's "# of 32-bits"
void * memmove_32bit(void *dest, const void *src, size_t len)
{
const uint32_t* s = (uint32_t*)src;
uint32_t* d = (uint32_t*)dest;
const uint32_t *nexts = s + len;
uint32_t *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
*d++ = *s++;
}
}
else
{
while (nextd != d)
{
*--nextd = *--nexts;
}
}
return dest;
}
// 64-bit (8 bytes at a time - 2 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/8), so it's "# of 64-bits"
void * memmove_64bit(void *dest, const void *src, size_t len)
{
const uint64_t* s = (uint64_t*)src;
uint64_t* d = (uint64_t*)dest;
const uint64_t *nexts = s + len;
uint64_t *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
*d++ = *s++;
}
}
else
{
while (nextd != d)
{
*--nextd = *--nexts;
}
}
return dest;
}
//-----------------------------------------------------------------------------
// SSE2 Unaligned:
//-----------------------------------------------------------------------------
// SSE2 (128-bit, 16 bytes at a time - 4 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/16), so it's "# of 128-bits"
void * memmove_128bit_u(void *dest, const void *src, size_t len)
{
const __m128i_u* s = (__m128i_u*)src;
__m128i_u* d = (__m128i_u*)dest;
const __m128i_u *nexts = s + len;
__m128i_u *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm_storeu_si128(d++, _mm_lddqu_si128(s++));
}
}
else
{
while (nextd != d)
{
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts));
}
}
return dest;
}
// 32 bytes at a time
void * memmove_128bit_32B_u(void *dest, const void *src, size_t len)
{
const __m128i_u* s = (__m128i_u*)src;
__m128i_u* d = (__m128i_u*)dest;
const __m128i_u *nexts = s + (len << 1);
__m128i_u *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 1
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 1
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 2
}
}
return dest;
}
// 64 bytes at a time
void * memmove_128bit_64B_u(void *dest, const void *src, size_t len)
{
const __m128i_u* s = (__m128i_u*)src;
__m128i_u* d = (__m128i_u*)dest;
const __m128i_u *nexts = s + (len << 2);
__m128i_u *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 1
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 2
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 3
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 1
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 2
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 3
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 4
}
}
return dest;
}
// 128 bytes at a time
void * memmove_128bit_128B_u(void *dest, const void *src, size_t len)
{
const __m128i_u* s = (__m128i_u*)src;
__m128i_u* d = (__m128i_u*)dest;
const __m128i_u *nexts = s + (len << 3);
__m128i_u *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd)
{
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 1
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 2
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 3
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 4
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 5
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 6
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 7
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 8
}
}
else
{
while (nextd != d)
{
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 1
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 2
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 3
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 4
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 5
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 6
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 7
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 8
}
}
return dest;
}
// For fun: 1 load->store for every xmm register
// 256 bytes
void * memmove_128bit_256B_u(void *dest, const void *src, size_t len)
{
const __m128i_u* s = (__m128i_u*)src;
__m128i_u* d = (__m128i_u*)dest;
const __m128i_u *nexts = s + (len << 4);
__m128i_u *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 1
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 2
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 3
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 4
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 5
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 6
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 7
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 8
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 9
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 10
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 11
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 12
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 13
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 14
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 15
_mm_storeu_si128(d++, _mm_lddqu_si128(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 1
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 2
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 3
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 4
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 5
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 6
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 7
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 8
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 9
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 10
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 11
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 12
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 13
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 14
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 15
_mm_storeu_si128(--nextd, _mm_lddqu_si128(--nexts)); // 16
}
}
return dest;
}
//-----------------------------------------------------------------------------
// AVX+ Unaligned:
//-----------------------------------------------------------------------------
// AVX (256-bit, 32 bytes at a time - 8 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/32), so it's "# of 256-bits"
// Sandybridge and Ryzen and up, Haswell and up for better performance
#ifdef __AVX__
void * memmove_256bit_u(void *dest, const void *src, size_t len)
{
const __m256i_u* s = (__m256i_u*)src;
__m256i_u* d = (__m256i_u*)dest;
const __m256i_u *nexts = s + len;
__m256i_u *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++));
}
}
else
{
while (nextd != d)
{
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts));
}
}
return dest;
}
// 64 bytes at a time
void * memmove_256bit_64B_u(void *dest, const void *src, size_t len)
{
const __m256i_u* s = (__m256i_u*)src;
__m256i_u* d = (__m256i_u*)dest;
const __m256i_u *nexts = s + (len << 1);
__m256i_u *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 1
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 1
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 2
}
}
return dest;
}
// 128 bytes at a time
void * memmove_256bit_128B_u(void *dest, const void *src, size_t len)
{
const __m256i_u* s = (__m256i_u*)src;
__m256i_u* d = (__m256i_u*)dest;
const __m256i_u *nexts = s + (len << 2);
__m256i_u *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 1
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 2
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 3
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 1
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 2
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 3
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 4
}
}
return dest;
}
// 256 bytes at a time
void * memmove_256bit_256B_u(void *dest, const void *src, size_t len)
{
const __m256i_u* s = (__m256i_u*)src;
__m256i_u* d = (__m256i_u*)dest;
const __m256i_u *nexts = s + (len << 3);
__m256i_u *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd)
{
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 1
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 2
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 3
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 4
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 5
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 6
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 7
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 8
}
}
else
{
while (nextd != d)
{
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 1
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 2
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 3
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 4
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 5
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 6
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 7
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 8
}
}
return dest;
}
// For fun:
// 512 bytes at a time, one load->store for every ymm register (there are 16)
void * memmove_256bit_512B_u(void *dest, const void *src, size_t len)
{
const __m256i_u* s = (__m256i_u*)src;
__m256i_u* d = (__m256i_u*)dest;
const __m256i_u *nexts = s + (len << 4);
__m256i_u *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 1
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 2
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 3
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 4
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 5
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 6
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 7
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 8
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 9
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 10
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 11
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 12
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 13
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 14
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 15
_mm256_storeu_si256(d++, _mm256_lddqu_si256(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 1
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 2
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 3
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 4
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 5
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 6
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 7
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 8
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 9
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 10
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 11
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 12
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 13
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 14
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 15
_mm256_storeu_si256(--nextd, _mm256_lddqu_si256(--nexts)); // 16
}
}
return dest;
}
#endif
// AVX-512 (512-bit, 64 bytes at a time - 16 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/64), so it's "# of 512-bits"
// Requires AVX512F
#ifdef __AVX512F__
void * memmove_512bit_u(void *dest, const void *src, size_t len)
{
const __m512i_u* s = (__m512i_u*)src;
__m512i_u* d = (__m512i_u*)dest;
const __m512i_u *nexts = s + len;
__m512i_u *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++));
}
}
else
{
while (nextd != d)
{
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts));
}
}
return dest;
}
// 128 bytes at a time
void * memmove_512bit_128B_u(void *dest, const void *src, size_t len)
{
const __m512i_u* s = (__m512i_u*)src;
__m512i_u* d = (__m512i_u*)dest;
const __m512i_u *nexts = s + (len << 1);
__m512i_u *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 1
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 1
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 2
}
}
return dest;
}
// 256 bytes at a time
void * memmove_512bit_256B_u(void *dest, const void *src, size_t len)
{
const __m512i_u* s = (__m512i_u*)src;
__m512i_u* d = (__m512i_u*)dest;
const __m512i_u *nexts = s + (len << 2);
__m512i_u *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 1
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 2
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 3
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 1
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 2
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 3
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 4
}
}
return dest;
}
// 512 bytes (half a KB!!) at a time
void * memmove_512bit_512B_u(void *dest, const void *src, size_t len)
{
const __m512i_u* s = (__m512i_u*)src;
__m512i_u* d = (__m512i_u*)dest;
const __m512i_u *nexts = s + (len << 3);
__m512i_u *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd)
{
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 1
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 2
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 3
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 4
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 5
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 6
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 7
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 8
}
}
else
{
while (nextd != d)
{
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 1
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 2
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 3
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 4
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 5
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 6
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 7
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 8
}
}
return dest;
}
// Alright I'll admit I got a little carried away...
// 1024 bytes, or 1 kB
void * memmove_512bit_1kB_u(void *dest, const void *src, size_t len)
{
const __m512i_u* s = (__m512i_u*)src;
__m512i_u* d = (__m512i_u*)dest;
const __m512i_u *nexts = s + (len << 4);
__m512i_u *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 1
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 2
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 3
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 4
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 5
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 6
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 7
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 8
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 9
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 10
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 11
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 12
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 13
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 14
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 15
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 1
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 2
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 3
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 4
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 5
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 6
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 7
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 8
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 9
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 10
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 11
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 12
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 13
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 14
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 15
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 16
}
}
return dest;
}
// 2048 bytes, or 2 kB
void * memmove_512bit_2kB_u(void *dest, const void *src, size_t len)
{
const __m512i_u* s = (__m512i_u*)src;
__m512i_u* d = (__m512i_u*)dest;
const __m512i_u *nexts = s + (len << 5);
__m512i_u *nextd = d + (len << 5);
if (d < s)
{
while (d != nextd)
{
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 1
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 2
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 3
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 4
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 5
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 6
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 7
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 8
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 9
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 10
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 11
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 12
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 13
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 14
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 15
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 16
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 17
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 18
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 19
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 20
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 21
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 22
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 23
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 24
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 25
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 26
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 27
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 28
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 29
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 30
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 31
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 32
}
}
else
{
while (nextd != d)
{
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 1
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 2
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 3
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 4
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 5
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 6
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 7
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 8
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 9
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 10
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 11
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 12
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 13
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 14
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 15
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 16
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 17
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 18
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 19
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 20
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 21
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 22
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 23
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 24
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 25
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 26
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 27
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 28
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 29
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 30
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 31
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 32
}
}
return dest;
}
// Y'know what? Here's a whole page.
// 4096 bytes, or 4 kB
void * memmove_512bit_4kB_u(void *dest, const void *src, size_t len)
{
const __m512i_u* s = (__m512i_u*)src;
__m512i_u* d = (__m512i_u*)dest;
const __m512i_u *nexts = s + (len << 6);
__m512i_u *nextd = d + (len << 6);
if (d < s)
{
while (d != nextd)
{
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 1
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 2
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 3
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 4
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 5
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 6
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 7
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 8
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 9
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 10
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 11
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 12
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 13
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 14
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 15
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 16
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 17
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 18
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 19
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 20
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 21
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 22
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 23
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 24
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 25
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 26
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 27
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 28
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 29
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 30
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 31
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 32
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 1
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 2
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 3
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 4
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 5
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 6
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 7
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 8
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 9
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 10
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 11
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 12
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 13
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 14
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 15
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 16
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 17
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 18
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 19
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 20
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 21
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 22
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 23
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 24
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 25
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 26
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 27
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 28
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 29
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 30
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 31
_mm512_storeu_si512(d++, _mm512_loadu_si512(s++)); // 32
}
}
else
{
while (nextd != d)
{
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 1
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 2
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 3
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 4
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 5
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 6
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 7
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 8
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 9
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 10
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 11
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 12
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 13
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 14
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 15
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 16
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 17
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 18
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 19
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 20
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 21
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 22
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 23
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 24
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 25
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 26
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 27
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 28
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 29
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 30
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 31
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 32
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 1
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 2
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 3
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 4
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 5
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 6
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 7
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 8
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 9
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 10
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 11
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 12
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 13
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 14
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 15
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 16
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 17
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 18
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 19
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 20
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 21
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 22
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 23
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 24
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 25
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 26
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 27
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 28
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 29
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 30
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 31
_mm512_storeu_si512(--nextd, _mm512_loadu_si512(--nexts)); // 32
}
}
return dest;
}
#endif
// AVX-1024 support pending existence of the standard. It would be able to fit
// an entire 4 kB page in its registers at one time. Imagine that!
// (AVX-512 maxes at 2 kB, which is why I only used numbers 1-32 above.)
//-----------------------------------------------------------------------------
// SSE2 Aligned:
//-----------------------------------------------------------------------------
// SSE2 (128-bit, 16 bytes at a time - 4 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/16), so it's "# of 128-bits"
void * memmove_128bit_a(void *dest, const void *src, size_t len)
{
const __m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
const __m128i *nexts = s + len;
__m128i *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm_store_si128(d++, _mm_load_si128(s++));
}
}
else
{
while (nextd != d)
{
_mm_store_si128(--nextd, _mm_load_si128(--nexts));
}
}
return dest;
}
// 32 bytes at a time
void * memmove_128bit_32B_a(void *dest, const void *src, size_t len)
{
const __m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
const __m128i *nexts = s + (len << 1);
__m128i *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm_store_si128(d++, _mm_load_si128(s++)); // 1
_mm_store_si128(d++, _mm_load_si128(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 1
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 2
}
}
return dest;
}
// 64 bytes at a time
void * memmove_128bit_64B_a(void *dest, const void *src, size_t len)
{
const __m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
const __m128i *nexts = s + (len << 2);
__m128i *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm_store_si128(d++, _mm_load_si128(s++)); // 1
_mm_store_si128(d++, _mm_load_si128(s++)); // 2
_mm_store_si128(d++, _mm_load_si128(s++)); // 3
_mm_store_si128(d++, _mm_load_si128(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 1
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 2
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 3
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 4
}
}
return dest;
}
// 128 bytes at a time
void * memmove_128bit_128B_a(void *dest, const void *src, size_t len)
{
const __m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
const __m128i *nexts = s + (len << 3);
__m128i *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd)
{
_mm_store_si128(d++, _mm_load_si128(s++)); // 1
_mm_store_si128(d++, _mm_load_si128(s++)); // 2
_mm_store_si128(d++, _mm_load_si128(s++)); // 3
_mm_store_si128(d++, _mm_load_si128(s++)); // 4
_mm_store_si128(d++, _mm_load_si128(s++)); // 5
_mm_store_si128(d++, _mm_load_si128(s++)); // 6
_mm_store_si128(d++, _mm_load_si128(s++)); // 7
_mm_store_si128(d++, _mm_load_si128(s++)); // 8
}
}
else
{
while (nextd != d)
{
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 1
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 2
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 3
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 4
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 5
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 6
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 7
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 8
}
}
return dest;
}
// For fun: 1 load->store for every xmm register (there are 16)
// 256 bytes
void * memmove_128bit_256B_a(void *dest, const void *src, size_t len)
{
const __m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
const __m128i *nexts = s + (len << 4);
__m128i *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm_store_si128(d++, _mm_load_si128(s++)); // 1
_mm_store_si128(d++, _mm_load_si128(s++)); // 2
_mm_store_si128(d++, _mm_load_si128(s++)); // 3
_mm_store_si128(d++, _mm_load_si128(s++)); // 4
_mm_store_si128(d++, _mm_load_si128(s++)); // 5
_mm_store_si128(d++, _mm_load_si128(s++)); // 6
_mm_store_si128(d++, _mm_load_si128(s++)); // 7
_mm_store_si128(d++, _mm_load_si128(s++)); // 8
_mm_store_si128(d++, _mm_load_si128(s++)); // 9
_mm_store_si128(d++, _mm_load_si128(s++)); // 10
_mm_store_si128(d++, _mm_load_si128(s++)); // 11
_mm_store_si128(d++, _mm_load_si128(s++)); // 12
_mm_store_si128(d++, _mm_load_si128(s++)); // 13
_mm_store_si128(d++, _mm_load_si128(s++)); // 14
_mm_store_si128(d++, _mm_load_si128(s++)); // 15
_mm_store_si128(d++, _mm_load_si128(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 1
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 2
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 3
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 4
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 5
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 6
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 7
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 8
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 9
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 10
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 11
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 12
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 13
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 14
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 15
_mm_store_si128(--nextd, _mm_load_si128(--nexts)); // 16
}
}
return dest;
}
//-----------------------------------------------------------------------------
// AVX+ Aligned:
//-----------------------------------------------------------------------------
// AVX (256-bit, 32 bytes at a time - 8 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/32), so it's "# of 256-bits"
// Sandybridge and Ryzen and up
#ifdef __AVX__
void * memmove_256bit_a(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + len;
__m256i *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm256_store_si256(d++, _mm256_load_si256(s++));
}
}
else
{
while (nextd != d)
{
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts));
}
}
return dest;
}
// 64 bytes at a time
void * memmove_256bit_64B_a(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 1);
__m256i *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 1
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 1
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 2
}
}
return dest;
}
// 128 bytes at a time
void * memmove_256bit_128B_a(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 2);
__m256i *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 1
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 2
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 3
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 1
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 2
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 3
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 4
}
}
return dest;
}
// 256 bytes at a time
void * memmove_256bit_256B_a(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 3);
__m256i *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd)
{
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 1
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 2
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 3
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 4
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 5
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 6
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 7
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 8
}
}
else
{
while (nextd != d)
{
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 1
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 2
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 3
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 4
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 5
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 6
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 7
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 8
}
}
return dest;
}
// I just wanted to see what doing one move for every ymm register looks like.
// There are 16 256-bit (ymm) registers.
void * memmove_256bit_512B_a(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 4);
__m256i *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 1
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 2
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 3
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 4
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 5
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 6
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 7
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 8
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 9
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 10
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 11
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 12
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 13
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 14
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 15
_mm256_store_si256(d++, _mm256_load_si256(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 1
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 2
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 3
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 4
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 5
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 6
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 7
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 8
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 9
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 10
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 11
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 12
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 13
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 14
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 15
_mm256_store_si256(--nextd, _mm256_load_si256(--nexts)); // 16
}
}
return dest;
}
#endif
// AVX-512 (512-bit, 64 bytes at a time - 16 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/64), so it's "# of 512-bits"
// Requires AVX512F
#ifdef __AVX512F__
void * memmove_512bit_a(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + len;
__m512i *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm512_store_si512(d++, _mm512_load_si512(s++));
}
}
else
{
while (nextd != d)
{
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts));
}
}
return dest;
}
// 128 bytes at a time
void * memmove_512bit_128B_a(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 1);
__m512i *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 1
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 1
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 2
}
}
return dest;
}
// 256 bytes at a time
void * memmove_512bit_256B_a(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 2);
__m512i *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 1
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 2
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 3
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 1
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 2
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 3
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 4
}
}
return dest;
}
// 512 bytes (half a KB!!) at a time
void * memmove_512bit_512B_a(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 3);
__m512i *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd) // Post-increment: use d then increment
{
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 1
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 2
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 3
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 4
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 5
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 6
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 7
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 8
}
}
else
{
while (nextd != d) // Pre-increment: increment nextd then use
{
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 1
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 2
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 3
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 4
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 5
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 6
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 7
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 8
}
}
return dest;
}
// The functions below I made just for fun to see what doing one move for every
// zmm register looks like. I think the insanity speaks for itself. :)
// 1024 bytes, or 1 kB
void * memmove_512bit_1kB_a(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 4);
__m512i *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 1
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 2
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 3
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 4
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 5
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 6
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 7
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 8
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 9
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 10
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 11
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 12
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 13
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 14
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 15
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 1
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 2
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 3
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 4
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 5
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 6
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 7
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 8
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 9
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 10
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 11
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 12
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 13
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 14
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 15
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 16
}
}
return dest;
}
// 2048 bytes, or 2 kB
// AVX512 has 32x 512-bit registers, so......
void * memmove_512bit_2kB_a(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 5);
__m512i *nextd = d + (len << 5);
if (d < s)
{
while (d != nextd)
{
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 1
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 2
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 3
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 4
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 5
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 6
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 7
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 8
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 9
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 10
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 11
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 12
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 13
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 14
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 15
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 16
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 17
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 18
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 19
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 20
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 21
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 22
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 23
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 24
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 25
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 26
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 27
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 28
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 29
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 30
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 31
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 32
}
}
else
{
while (nextd != d)
{
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 1
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 2
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 3
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 4
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 5
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 6
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 7
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 8
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 9
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 10
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 11
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 12
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 13
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 14
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 15
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 16
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 17
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 18
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 19
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 20
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 21
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 22
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 23
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 24
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 25
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 26
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 27
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 28
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 29
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 30
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 31
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 32
}
}
return dest;
}
// Y'know what? Here's a whole page.
// 4096 bytes, or 4 kB
void * memmove_512bit_4kB_a(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 6);
__m512i *nextd = d + (len << 6);
if (d < s)
{
while (d != nextd)
{
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 1
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 2
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 3
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 4
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 5
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 6
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 7
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 8
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 9
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 10
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 11
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 12
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 13
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 14
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 15
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 16
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 17
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 18
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 19
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 20
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 21
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 22
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 23
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 24
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 25
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 26
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 27
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 28
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 29
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 30
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 31
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 32
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 1
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 2
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 3
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 4
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 5
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 6
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 7
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 8
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 9
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 10
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 11
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 12
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 13
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 14
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 15
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 16
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 17
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 18
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 19
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 20
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 21
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 22
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 23
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 24
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 25
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 26
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 27
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 28
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 29
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 30
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 31
_mm512_store_si512(d++, _mm512_load_si512(s++)); // 32
}
}
else
{
while (nextd != d)
{
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 1
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 2
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 3
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 4
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 5
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 6
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 7
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 8
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 9
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 10
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 11
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 12
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 13
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 14
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 15
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 16
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 17
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 18
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 19
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 20
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 21
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 22
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 23
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 24
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 25
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 26
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 27
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 28
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 29
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 30
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 31
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 32
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 1
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 2
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 3
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 4
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 5
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 6
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 7
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 8
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 9
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 10
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 11
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 12
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 13
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 14
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 15
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 16
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 17
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 18
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 19
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 20
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 21
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 22
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 23
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 24
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 25
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 26
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 27
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 28
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 29
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 30
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 31
_mm512_store_si512(--nextd, _mm512_load_si512(--nexts)); // 32
}
}
return dest;
}
#endif
//-----------------------------------------------------------------------------
// SSE4.1 Streaming:
//-----------------------------------------------------------------------------
// SSE4.1 (128-bit, 16 bytes at a time - 4 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/16), so it's "# of 128-bits"
void * memmove_128bit_as(void *dest, const void *src, size_t len)
{
__m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
__m128i *nexts = s + len;
__m128i *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm_stream_si128(d++, _mm_stream_load_si128(s++));
}
}
else
{
while (nextd != d)
{
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts));
}
}
_mm_sfence();
return dest;
}
// 32 bytes at a time
void * memmove_128bit_32B_as(void *dest, const void *src, size_t len)
{
__m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
__m128i *nexts = s + (len << 1);
__m128i *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 1
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 1
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 2
}
}
_mm_sfence();
return dest;
}
// 64 bytes at a time
void * memmove_128bit_64B_as(void *dest, const void *src, size_t len)
{
__m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
__m128i *nexts = s + (len << 2);
__m128i *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 1
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 2
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 3
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 1
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 2
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 3
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 4
}
}
_mm_sfence();
return dest;
}
// 128 bytes at a time
void * memmove_128bit_128B_as(void *dest, const void *src, size_t len)
{
__m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
__m128i *nexts = s + (len << 3);
__m128i *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd)
{
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 1
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 2
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 3
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 4
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 5
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 6
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 7
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 8
}
}
else
{
while (nextd != d)
{
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 1
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 2
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 3
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 4
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 5
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 6
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 7
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 8
}
}
_mm_sfence();
return dest;
}
// For fun: 1 load->store for every xmm register (there are 16)
// 256 bytes
void * memmove_128bit_256B_as(void *dest, const void *src, size_t len)
{
__m128i* s = (__m128i*)src;
__m128i* d = (__m128i*)dest;
__m128i *nexts = s + (len << 4);
__m128i *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 1
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 2
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 3
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 4
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 5
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 6
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 7
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 8
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 9
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 10
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 11
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 12
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 13
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 14
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 15
_mm_stream_si128(d++, _mm_stream_load_si128(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 1
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 2
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 3
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 4
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 5
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 6
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 7
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 8
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 9
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 10
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 11
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 12
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 13
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 14
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 15
_mm_stream_si128(--nextd, _mm_stream_load_si128(--nexts)); // 16
}
}
_mm_sfence();
return dest;
}
//-----------------------------------------------------------------------------
// AVX2+ Streaming:
//-----------------------------------------------------------------------------
// AVX2 (256-bit, 32 bytes at a time - 8 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/32), so it's "# of 256-bits"
// Haswell and Ryzen and up
#ifdef __AVX2__
void * memmove_256bit_as(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + len;
__m256i *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++));
}
}
else
{
while (nextd != d)
{
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts));
}
}
_mm_sfence();
return dest;
}
// 64 bytes at a time
void * memmove_256bit_64B_as(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 1);
__m256i *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 1
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 1
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 2
}
}
_mm_sfence();
return dest;
}
// 128 bytes at a time
void * memmove_256bit_128B_as(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 2);
__m256i *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 1
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 2
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 3
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 1
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 2
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 3
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 4
}
}
_mm_sfence();
return dest;
}
// 256 bytes at a time
void * memmove_256bit_256B_as(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 3);
__m256i *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd)
{
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 1
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 2
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 3
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 4
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 5
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 6
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 7
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 8
}
}
else
{
while (nextd != d)
{
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 1
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 2
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 3
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 4
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 5
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 6
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 7
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 8
}
}
_mm_sfence();
return dest;
}
// I just wanted to see what doing one move for every ymm register looks like.
// There are 16 256-bit (ymm) registers.
void * memmove_256bit_512B_as(void *dest, const void *src, size_t len)
{
const __m256i* s = (__m256i*)src;
__m256i* d = (__m256i*)dest;
const __m256i *nexts = s + (len << 4);
__m256i *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 1
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 2
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 3
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 4
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 5
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 6
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 7
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 8
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 9
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 10
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 11
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 12
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 13
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 14
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 15
_mm256_stream_si256(d++, _mm256_stream_load_si256(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 1
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 2
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 3
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 4
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 5
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 6
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 7
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 8
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 9
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 10
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 11
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 12
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 13
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 14
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 15
_mm256_stream_si256(--nextd, _mm256_stream_load_si256(--nexts)); // 16
}
}
_mm_sfence();
return dest;
}
#endif
// AVX-512 (512-bit, 64 bytes at a time - 16 pixels in a 32-bit linear frame buffer)
// Len is (# of total bytes/64), so it's "# of 512-bits"
// Requires AVX512F
#ifdef __AVX512F__
void * memmove_512bit_as(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + len;
__m512i *nextd = d + len;
if (d < s)
{
while (d != nextd)
{
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++));
}
}
else
{
while (nextd != d)
{
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts));
}
}
_mm_sfence();
return dest;
}
// 128 bytes at a time
void * memmove_512bit_128B_as(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 1);
__m512i *nextd = d + (len << 1);
if (d < s)
{
while (d != nextd)
{
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 1
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 2
}
}
else
{
while (nextd != d)
{
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 1
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 2
}
}
_mm_sfence();
return dest;
}
// 256 bytes at a time
void * memmove_512bit_256B_as(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 2);
__m512i *nextd = d + (len << 2);
if (d < s)
{
while (d != nextd)
{
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 1
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 2
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 3
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 4
}
}
else
{
while (nextd != d)
{
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 1
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 2
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 3
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 4
}
}
_mm_sfence();
return dest;
}
// 512 bytes (half a KB!!) at a time
void * memmove_512bit_512B_as(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 3);
__m512i *nextd = d + (len << 3);
if (d < s)
{
while (d != nextd) // Post-increment: use d then increment
{
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 1
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 2
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 3
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 4
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 5
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 6
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 7
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 8
}
}
else
{
while (nextd != d) // Pre-increment: increment nextd then use
{
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 1
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 2
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 3
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 4
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 5
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 6
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 7
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 8
}
}
_mm_sfence();
return dest;
}
// The functions below I made just for fun to see what doing one move for every
// zmm register looks like. I think the insanity speaks for itself. :)
// 1024 bytes, or 1 kB
void * memmove_512bit_1kB_as(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 4);
__m512i *nextd = d + (len << 4);
if (d < s)
{
while (d != nextd)
{
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 1
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 2
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 3
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 4
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 5
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 6
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 7
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 8
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 9
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 10
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 11
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 12
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 13
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 14
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 15
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 16
}
}
else
{
while (nextd != d)
{
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 1
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 2
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 3
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 4
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 5
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 6
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 7
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 8
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 9
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 10
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 11
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 12
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 13
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 14
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 15
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 16
}
}
_mm_sfence();
return dest;
}
// 2048 bytes, or 2 kB
// AVX512 has 32x 512-bit registers, so......
void * memmove_512bit_2kB_as(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 5);
__m512i *nextd = d + (len << 5);
if (d < s)
{
while (d != nextd)
{
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 1
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 2
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 3
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 4
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 5
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 6
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 7
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 8
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 9
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 10
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 11
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 12
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 13
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 14
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 15
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 16
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 17
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 18
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 19
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 20
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 21
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 22
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 23
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 24
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 25
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 26
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 27
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 28
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 29
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 30
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 31
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 32
}
}
else
{
while (nextd != d)
{
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 1
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 2
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 3
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 4
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 5
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 6
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 7
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 8
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 9
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 10
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 11
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 12
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 13
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 14
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 15
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 16
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 17
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 18
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 19
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 20
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 21
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 22
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 23
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 24
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 25
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 26
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 27
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 28
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 29
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 30
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 31
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 32
}
}
_mm_sfence();
return dest;
}
// Y'know what? Here's a whole page.
// 4096 bytes, or 4 kB
void * memmove_512bit_4kB_as(void *dest, const void *src, size_t len)
{
const __m512i* s = (__m512i*)src;
__m512i* d = (__m512i*)dest;
const __m512i *nexts = s + (len << 6);
__m512i *nextd = d + (len << 6);
if (d < s)
{
while (d != nextd)
{
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 1
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 2
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 3
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 4
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 5
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 6
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 7
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 8
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 9
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 10
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 11
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 12
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 13
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 14
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 15
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 16
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 17
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 18
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 19
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 20
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 21
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 22
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 23
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 24
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 25
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 26
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 27
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 28
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 29
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 30
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 31
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 32
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 1
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 2
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 3
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 4
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 5
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 6
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 7
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 8
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 9
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 10
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 11
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 12
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 13
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 14
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 15
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 16
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 17
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 18
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 19
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 20
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 21
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 22
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 23
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 24
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 25
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 26
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 27
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 28
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 29
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 30
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 31
_mm512_stream_si512(d++, _mm512_stream_load_si512(s++)); // 32
}
}
else
{
while (nextd != d)
{
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 1
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 2
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 3
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 4
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 5
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 6
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 7
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 8
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 9
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 10
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 11
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 12
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 13
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 14
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 15
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 16
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 17
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 18
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 19
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 20
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 21
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 22
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 23
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 24
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 25
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 26
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 27
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 28
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 29
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 30
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 31
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 32
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 1
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 2
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 3
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 4
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 5
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 6
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 7
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 8
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 9
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 10
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 11
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 12
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 13
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 14
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 15
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 16
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 17
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 18
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 19
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 20
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 21
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 22
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 23
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 24
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 25
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 26
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 27
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 28
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 29
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 30
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 31
_mm512_stream_si512(--nextd, _mm512_stream_load_si512(--nexts)); // 32
}
}
_mm_sfence();
return dest;
}
#endif
//-----------------------------------------------------------------------------
// Dispatch Functions:
//-----------------------------------------------------------------------------
// Move arbitrarily large amounts of data (dest addr < src addr)
void * memmove_large(void *dest, void *src, size_t numbytes)
{
void * returnval = dest; // memmove is supposed to return the destination
size_t offset = 0; // Offset size needs to match the size of a pointer
while(numbytes)
// The biggest sizes will go first for alignment. There's no benefit to using
// aligned loads over unaligned loads here, so all are unaligned.
// NOTE: Each memmove has its own loop so that any one can be used individually.
{
if(numbytes < 2) // 1 byte
{
memmove(dest, src, numbytes);
offset = numbytes & -1;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes = 0;
}
else if(numbytes < 4) // 2 bytes
{
memmove_16bit(dest, src, numbytes >> 1);
offset = numbytes & -2;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 1;
}
else if(numbytes < 8) // 4 bytes
{
memmove_32bit(dest, src, numbytes >> 2);
offset = numbytes & -4;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 3;
}
else if(numbytes < 16) // 8 bytes
{
memmove_64bit(dest, src, numbytes >> 3);
offset = numbytes & -8;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 7;
}
#ifdef __AVX512F__
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_u(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_256bit_u(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_512bit_u(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_512bit_128B_u(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else if(numbytes < 512) // 256 bytes
{
memmove_512bit_256B_u(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
else if(numbytes < 1024) // 512 bytes
{
memmove_512bit_512B_u(dest, src, numbytes >> 9);
offset = numbytes & -512;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 511;
}
else if(numbytes < 2048) // 1024 bytes (1 kB)
{
memmove_512bit_1kB_u(dest, src, numbytes >> 10);
offset = numbytes & -1024;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 1023;
}
else if(numbytes < 4096) // 2048 bytes (2 kB)
{
memmove_512bit_2kB_u(dest, src, numbytes >> 11);
offset = numbytes & -2048;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 2047;
}
else // 4096 bytes (4 kB)
{
memmove_512bit_4kB_u(dest, src, numbytes >> 12);
offset = numbytes & -4096;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 4095;
}
#elif __AVX__
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_u(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_256bit_u(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_256bit_64B_u(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_256bit_128B_u(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else if(numbytes < 512) // 256 bytes
{
memmove_256bit_256B_u(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
else // 512 bytes
{
memmove_256bit_512B_u(dest, src, numbytes >> 9);
offset = numbytes & -512;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 511;
}
#else // SSE2 only
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_u(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_128bit_32B_u(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_128bit_64B_u(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_128bit_128B_u(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else // 256 bytes
{
memmove_128bit_256B_u(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
#endif
}
return returnval;
} // END MEMMOVE LARGE, UNALIGNED
// Move arbitrarily large amounts of data (dest addr < src addr)
// Aligned version
void * memmove_large_a(void *dest, void *src, size_t numbytes)
{
void * returnval = dest; // memmove is supposed to return the destination
size_t offset = 0; // Offset size needs to match the size of a pointer
while(numbytes)
// The biggest sizes will go first for alignment. There's no benefit to using
// aligned loads over unaligned loads here, so all are unaligned.
// NOTE: Each memmove has its own loop so that any one can be used individually.
{
if(numbytes < 2) // 1 byte
{
memmove(dest, src, numbytes);
offset = numbytes & -1;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes = 0;
}
else if(numbytes < 4) // 2 bytes
{
memmove_16bit(dest, src, numbytes >> 1);
offset = numbytes & -2;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 1;
}
else if(numbytes < 8) // 4 bytes
{
memmove_32bit(dest, src, numbytes >> 2);
offset = numbytes & -4;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 3;
}
else if(numbytes < 16) // 8 bytes
{
memmove_64bit(dest, src, numbytes >> 3);
offset = numbytes & -8;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 7;
}
#ifdef __AVX512F__
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_a(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_256bit_a(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_512bit_a(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_512bit_128B_a(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else if(numbytes < 512) // 256 bytes
{
memmove_512bit_256B_a(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
else if(numbytes < 1024) // 512 bytes
{
memmove_512bit_512B_a(dest, src, numbytes >> 9);
offset = numbytes & -512;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 511;
}
else if(numbytes < 2048) // 1024 bytes (1 kB)
{
memmove_512bit_1kB_a(dest, src, numbytes >> 10);
offset = numbytes & -1024;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 1023;
}
else if(numbytes < 4096) // 2048 bytes (2 kB)
{
memmove_512bit_2kB_a(dest, src, numbytes >> 11);
offset = numbytes & -2048;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 2047;
}
else // 4096 bytes (4 kB)
{
memmove_512bit_4kB_a(dest, src, numbytes >> 12);
offset = numbytes & -4096;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 4095;
}
#elif __AVX__
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_a(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_256bit_a(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_256bit_64B_a(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_256bit_128B_a(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else if(numbytes < 512) // 256 bytes
{
memmove_256bit_256B_a(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
else // 512 bytes
{
memmove_256bit_512B_a(dest, src, numbytes >> 9);
offset = numbytes & -512;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 511;
}
#else // SSE2 only
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_a(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_128bit_32B_a(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_128bit_64B_a(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_128bit_128B_a(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else // 256 bytes
{
memmove_128bit_256B_a(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
#endif
}
return returnval;
} // END MEMMOVE LARGE, ALIGNED
// Move arbitrarily large amounts of data (dest addr < src addr)
// Aligned, streaming version
void * memmove_large_as(void *dest, void *src, size_t numbytes)
{
void * returnval = dest; // memmove is supposed to return the destination
size_t offset = 0; // Offset size needs to match the size of a pointer
while(numbytes)
// The biggest sizes will go first for alignment. There's no benefit to using
// aligned loads over unaligned loads here, so all are unaligned.
// NOTE: Each memmove has its own loop so that any one can be used individually.
{
if(numbytes < 2) // 1 byte
{
memmove(dest, src, numbytes);
offset = numbytes & -1;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes = 0;
}
else if(numbytes < 4) // 2 bytes
{
memmove_16bit(dest, src, numbytes >> 1);
offset = numbytes & -2;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 1;
}
else if(numbytes < 8) // 4 bytes
{
memmove_32bit(dest, src, numbytes >> 2);
offset = numbytes & -4;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 3;
}
else if(numbytes < 16) // 8 bytes
{
memmove_64bit(dest, src, numbytes >> 3);
offset = numbytes & -8;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 7;
}
#ifdef __AVX512F__
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_as(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_256bit_as(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_512bit_as(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_512bit_128B_as(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else if(numbytes < 512) // 256 bytes
{
memmove_512bit_256B_as(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
else if(numbytes < 1024) // 512 bytes
{
memmove_512bit_512B_as(dest, src, numbytes >> 9);
offset = numbytes & -512;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 511;
}
else if(numbytes < 2048) // 1024 bytes (1 kB)
{
memmove_512bit_1kB_as(dest, src, numbytes >> 10);
offset = numbytes & -1024;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 1023;
}
else if(numbytes < 4096) // 2048 bytes (2 kB)
{
memmove_512bit_2kB_as(dest, src, numbytes >> 11);
offset = numbytes & -2048;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 2047;
}
else // 4096 bytes (4 kB)
{
memmove_512bit_4kB_as(dest, src, numbytes >> 12);
offset = numbytes & -4096;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 4095;
}
#elif __AVX2__
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_as(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_256bit_as(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_256bit_64B_as(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_256bit_128B_as(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else if(numbytes < 512) // 256 bytes
{
memmove_256bit_256B_as(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
else // 512 bytes
{
memmove_256bit_512B_as(dest, src, numbytes >> 9);
offset = numbytes & -512;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 511;
}
#else // SSE4.1 only
else if(numbytes < 32) // 16 bytes
{
memmove_128bit_as(dest, src, numbytes >> 4);
offset = numbytes & -16;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 15;
}
else if(numbytes < 64) // 32 bytes
{
memmove_128bit_32B_as(dest, src, numbytes >> 5);
offset = numbytes & -32;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 31;
}
else if(numbytes < 128) // 64 bytes
{
memmove_128bit_64B_as(dest, src, numbytes >> 6);
offset = numbytes & -64;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 63;
}
else if(numbytes < 256) // 128 bytes
{
memmove_128bit_128B_as(dest, src, numbytes >> 7);
offset = numbytes & -128;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 127;
}
else // 256 bytes
{
memmove_128bit_256B_as(dest, src, numbytes >> 8);
offset = numbytes & -256;
dest = (char *)dest + offset;
src = (char *)src + offset;
numbytes &= 255;
}
#endif
}
return returnval;
} // END MEMMOVE LARGE, ALIGNED, STREAMING
// Move arbitrarily large amounts of data in reverse order (ends first)
// src addr < dest addr
void * memmove_large_reverse(void *dest, void *src, size_t numbytes)
{
void * returnval = dest; // memmove is supposed to return the destination
size_t offset = 0; // Offset size needs to match the size of a pointer
void * nextdest = (char *)dest + numbytes;
void * nextsrc = (char *)src + numbytes;
while(numbytes)
// Want smallest sizes to go first, at the tail end, so that the biggest sizes
// are aligned later in this operation (AVX_memmove sets the alignment up for
// this to work).
// NOTE: Each memmove has its own loop so that any one can be used individually.
{
if(numbytes & 1) // 1 byte
{
offset = numbytes & 1;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove(nextdest, nextsrc, 1);
numbytes &= -2;
}
else if(numbytes & 2) // 2 bytes
{
offset = numbytes & 3;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_16bit(nextdest, nextsrc, 1);
numbytes &= -4;
}
else if(numbytes & 4) // 4 bytes
{
offset = numbytes & 7;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_32bit(nextdest, nextsrc, 1);
numbytes &= -8;
}
else if(numbytes & 8) // 8 bytes
{
offset = numbytes & 15;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_64bit(nextdest, nextsrc, 1);
numbytes &= -16;
}
#ifdef __AVX512F__
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_u(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_u(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_u(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128) // 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_128B_u(nextdest, nextsrc, 1);
numbytes &= -256;
}
else if(numbytes & 256) // 256 bytes
{
offset = numbytes & 511;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_256B_u(nextdest, nextsrc, 1);
numbytes &= -512;
}
else if(numbytes & 512) // 512 bytes
{
offset = numbytes & 1023;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_512B_u(nextdest, nextsrc, 1);
numbytes &= -1024;
}
else if(numbytes & 1024) // 1024 bytes (1 kB)
{
offset = numbytes & 2047;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_1kB_u(nextdest, nextsrc, 1);
numbytes &= -2048;
}
else if(numbytes & 2048) // 2048 bytes (2 kB)
{
offset = numbytes & 4095;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_2kB_u(nextdest, nextsrc, 1);
numbytes &= -4096;
}
else // 4096 bytes (4 kB)
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_512bit_4kB_u(nextdest, nextsrc, numbytes >> 12);
numbytes = 0;
}
#elif __AVX__
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_u(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_u(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_64B_u(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128) // 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_128B_u(nextdest, nextsrc, 1);
numbytes &= -256;
}
else if(numbytes & 256) // 256 bytes
{
offset = numbytes & 511;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_256B_u(nextdest, nextsrc, 1);
numbytes &= -512;
}
else // 512 bytes
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_256bit_512B_u(nextdest, nextsrc, numbytes >> 9);
numbytes = 0;
}
#else // SSE2 only
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_u(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_32B_u(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_64B_u(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128)// 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_128B_u(nextdest, nextsrc, 1);
numbytes &= -256;
}
else // 256 bytes
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_128bit_256B_u(nextdest, nextsrc, numbytes >> 8);
numbytes = 0;
}
#endif
}
return returnval;
} // END MEMMOVE LARGE REVERSE, UNALIGNED
// Move arbitrarily large amounts of data in reverse order (ends first)
// src addr < dest addr
// Aligned version
void * memmove_large_reverse_a(void *dest, void *src, size_t numbytes)
{
void * returnval = dest; // memmove is supposed to return the destination
size_t offset = 0; // Offset size needs to match the size of a pointer
void * nextdest = (char *)dest + numbytes;
void * nextsrc = (char *)src + numbytes;
while(numbytes)
// Want smallest sizes to go first, at the tail end, so that the biggest sizes
// are aligned later in this operation (AVX_memmove sets the alignment up for
// this to work).
// NOTE: Each memmove has its own loop so that any one can be used individually.
{
if(numbytes & 1) // 1 byte
{
offset = numbytes & 1;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove(nextdest, nextsrc, 1);
numbytes &= -2;
}
else if(numbytes & 2) // 2 bytes
{
offset = numbytes & 3;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_16bit(nextdest, nextsrc, 1);
numbytes &= -4;
}
else if(numbytes & 4) // 4 bytes
{
offset = numbytes & 7;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_32bit(nextdest, nextsrc, 1);
numbytes &= -8;
}
else if(numbytes & 8) // 8 bytes
{
offset = numbytes & 15;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_64bit(nextdest, nextsrc, 1);
numbytes &= -16;
}
#ifdef __AVX512F__
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_a(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_a(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_a(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128) // 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_128B_a(nextdest, nextsrc, 1);
numbytes &= -256;
}
else if(numbytes & 256) // 256 bytes
{
offset = numbytes & 511;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_256B_a(nextdest, nextsrc, 1);
numbytes &= -512;
}
else if(numbytes & 512) // 512 bytes
{
offset = numbytes & 1023;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_512B_a(nextdest, nextsrc, 1);
numbytes &= -1024;
}
else if(numbytes & 1024) // 1024 bytes (1 kB)
{
offset = numbytes & 2047;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_1kB_a(nextdest, nextsrc, 1);
numbytes &= -2048;
}
else if(numbytes & 2048) // 2048 bytes (2 kB)
{
offset = numbytes & 4095;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_2kB_a(nextdest, nextsrc, 1);
numbytes &= -4096;
}
else // 4096 bytes (4 kB)
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_512bit_4kB_a(nextdest, nextsrc, numbytes >> 12);
numbytes = 0;
}
#elif __AVX__
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_a(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_a(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_64B_a(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128) // 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_128B_a(nextdest, nextsrc, 1);
numbytes &= -256;
}
else if(numbytes & 256) // 256 bytes
{
offset = numbytes & 511;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_256B_a(nextdest, nextsrc, 1);
numbytes &= -512;
}
else // 512 bytes
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_256bit_512B_a(nextdest, nextsrc, numbytes >> 9);
numbytes = 0;
}
#else // SSE2 only
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_a(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_32B_a(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_64B_a(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128)// 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_128B_a(nextdest, nextsrc, 1);
numbytes &= -256;
}
else // 256 bytes
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_128bit_256B_a(nextdest, nextsrc, numbytes >> 8);
numbytes = 0;
}
#endif
}
return returnval;
} // END MEMMOVE LARGE REVERSE, ALIGNED
// Move arbitrarily large amounts of data in reverse order (ends first)
// src addr < dest addr
// Aligned, streaming version
void * memmove_large_reverse_as(void *dest, void *src, size_t numbytes)
{
void * returnval = dest; // memmove is supposed to return the destination
size_t offset = 0; // Offset size needs to match the size of a pointer
void * nextdest = (char *)dest + numbytes;
void * nextsrc = (char *)src + numbytes;
while(numbytes)
// Want smallest sizes to go first, at the tail end, so that the biggest sizes
// are aligned later in this operation (AVX_memmove sets the alignment up for
// this to work).
// NOTE: Each memmove has its own loop so that any one can be used individually.
{
if(numbytes & 1) // 1 byte
{
offset = numbytes & 1;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove(nextdest, nextsrc, 1);
numbytes &= -2;
}
else if(numbytes & 2) // 2 bytes
{
offset = numbytes & 3;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_16bit(nextdest, nextsrc, 1);
numbytes &= -4;
}
else if(numbytes & 4) // 4 bytes
{
offset = numbytes & 7;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_32bit(nextdest, nextsrc, 1);
numbytes &= -8;
}
else if(numbytes & 8) // 8 bytes
{
offset = numbytes & 15;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_64bit(nextdest, nextsrc, 1);
numbytes &= -16;
}
#ifdef __AVX512F__
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_as(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_as(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_as(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128) // 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_128B_as(nextdest, nextsrc, 1);
numbytes &= -256;
}
else if(numbytes & 256) // 256 bytes
{
offset = numbytes & 511;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_256B_as(nextdest, nextsrc, 1);
numbytes &= -512;
}
else if(numbytes & 512) // 512 bytes
{
offset = numbytes & 1023;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_512B_as(nextdest, nextsrc, 1);
numbytes &= -1024;
}
else if(numbytes & 1024) // 1024 bytes (1 kB)
{
offset = numbytes & 2047;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_1kB_as(nextdest, nextsrc, 1);
numbytes &= -2048;
}
else if(numbytes & 2048) // 2048 bytes (2 kB)
{
offset = numbytes & 4095;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_512bit_2kB_as(nextdest, nextsrc, 1);
numbytes &= -4096;
}
else // 4096 bytes (4 kB)
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_512bit_4kB_as(nextdest, nextsrc, numbytes >> 12);
numbytes = 0;
}
#elif __AVX2__
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_as(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_as(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_64B_as(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128) // 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_128B_as(nextdest, nextsrc, 1);
numbytes &= -256;
}
else if(numbytes & 256) // 256 bytes
{
offset = numbytes & 511;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_256bit_256B_as(nextdest, nextsrc, 1);
numbytes &= -512;
}
else // 512 bytes
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_256bit_512B_as(nextdest, nextsrc, numbytes >> 9);
numbytes = 0;
}
#else // SSE4.1 only
else if(numbytes & 16) // 16 bytes
{
offset = numbytes & 31;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_as(nextdest, nextsrc, 1);
numbytes &= -32;
}
else if(numbytes & 32) // 32 bytes
{
offset = numbytes & 63;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_32B_as(nextdest, nextsrc, 1);
numbytes &= -64;
}
else if(numbytes & 64) // 64 bytes
{
offset = numbytes & 127;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_64B_as(nextdest, nextsrc, 1);
numbytes &= -128;
}
else if(numbytes & 128)// 128 bytes
{
offset = numbytes & 255;
nextdest = (char *)nextdest - offset;
nextsrc = (char *)nextsrc - offset;
memmove_128bit_128B_as(nextdest, nextsrc, 1);
numbytes &= -256;
}
else // 256 bytes
{
offset = numbytes;
nextdest = (char *)nextdest - offset; // These should match initial src/dest
nextsrc = (char *)nextsrc - offset;
memmove_128bit_256B_as(nextdest, nextsrc, numbytes >> 8);
numbytes = 0;
}
#endif
}
return returnval;
} // END MEMMOVE LARGE REVERSE, ALIGNED, STREAMING
//-----------------------------------------------------------------------------
// Main Function:
//-----------------------------------------------------------------------------
// General-purpose function to call
void * AVX_memmove(void *dest, void *src, size_t numbytes)
{
void * returnval = dest;
if((char*)src == (char*)dest)
{
return returnval;
}
if(
( ((uintptr_t)src & BYTE_ALIGNMENT) == 0 )
&&
( ((uintptr_t)dest & BYTE_ALIGNMENT) == 0 )
) // Check alignment
{
if((char *)dest < (char *)src)
{
// This is the fastest case: src and dest are both cache line aligned.
if(numbytes > CACHESIZELIMIT)
{
memmove_large_as(dest, src, numbytes);
}
else
{
memmove_large_a(dest, src, numbytes); // Even if numbytes is small this'll work
}
}
else // src < dest
{ // Need to move ends first
if(numbytes > CACHESIZELIMIT)
{
memmove_large_reverse_as(dest, src, numbytes);
}
else
{
memmove_large_reverse_a(dest, src, numbytes);
}
}
}
else // Unaligned
{
size_t reverse_alignment = ((uintptr_t)dest & BYTE_ALIGNMENT);
size_t numbytes_to_align = (BYTE_ALIGNMENT + 1) - reverse_alignment;
if((char *)dest < (char *)src)
{
void * destoffset = (char*)dest + numbytes_to_align;
void * srcoffset = (char*)src + numbytes_to_align;
if(numbytes > numbytes_to_align)
{
// Get to an aligned position.
// This may be a little slower, but since it'll be mostly scalar operations
// alignment doesn't matter. Worst case it uses two vector functions, and
// this process only needs to be done once per call if dest is unaligned.
memmove_large(dest, src, numbytes_to_align);
// Now this should be faster since stores are aligned.
memmove_large(destoffset, srcoffset, numbytes - numbytes_to_align); // NOTE: Can't use streaming due to potential src misalignment
// On Haswell and up, cross cache line loads have a negligible penalty.
// Thus this will be slower on Sandy & Ivy Bridge, though Ivy Bridge will
// fare a little better (~2x, maybe?). Ryzen should generally fall somewhere
// inbetween Sandy Bridge and Haswell/Skylake on that front.
// NOTE: These are just rough theoretical estimates.
}
else // Small size
{
memmove_large(dest, src, numbytes);
}
}
else // src < dest
{
if(numbytes > reverse_alignment)
{
size_t better_aligned_bytes = numbytes - reverse_alignment;
void * destoffset = (char*)dest + better_aligned_bytes;
void * srcoffset = (char*)src + better_aligned_bytes;
// Move remainder
memmove_large_reverse(destoffset, srcoffset, reverse_alignment);
// Move bulk, up to lowest alignment line
memmove_large_reverse(dest, src, better_aligned_bytes);
}
else // Small size
{
memmove_large_reverse(dest, src, numbytes);
}
}
}
return returnval;
}
// AVX-1024+ support pending existence of the standard.
| 35.809454 | 138 | 0.615799 | [
"vector"
] |
9912604fbccb5a757dc9fd1d6ffe5e7b4ab52bd0 | 3,764 | h | C | cpp/open3d/pipelines/color_map/ColorMapUtils.h | leomariga/Open3D | d197339fcd29ad0803a182ef8953d89e563f94d7 | [
"MIT"
] | 3,673 | 2019-04-06T05:35:43.000Z | 2021-07-27T14:53:14.000Z | cpp/open3d/pipelines/color_map/ColorMapUtils.h | leomariga/Open3D | d197339fcd29ad0803a182ef8953d89e563f94d7 | [
"MIT"
] | 2,904 | 2019-04-06T06:51:22.000Z | 2021-07-27T13:49:54.000Z | cpp/open3d/pipelines/color_map/ColorMapUtils.h | leomariga/Open3D | d197339fcd29ad0803a182ef8953d89e563f94d7 | [
"MIT"
] | 1,127 | 2019-04-06T09:39:17.000Z | 2021-07-27T03:06:49.000Z | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018-2021 www.open3d.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------------------------------------------------------
#pragma once
#include <memory>
#include <vector>
#include "open3d/camera/PinholeCameraTrajectory.h"
#include "open3d/geometry/Image.h"
#include "open3d/geometry/RGBDImage.h"
#include "open3d/geometry/TriangleMesh.h"
#include "open3d/pipelines/color_map/ImageWarpingField.h"
#include "open3d/utility/Eigen.h"
#include "open3d/utility/Optional.h"
namespace open3d {
namespace pipelines {
namespace color_map {
std::tuple<std::vector<geometry::Image>,
std::vector<geometry::Image>,
std::vector<geometry::Image>,
std::vector<geometry::Image>,
std::vector<geometry::Image>>
CreateUtilImagesFromRGBD(const std::vector<geometry::RGBDImage>& images_rgbd);
std::vector<geometry::Image> CreateDepthBoundaryMasks(
const std::vector<geometry::Image>& images_depth,
double depth_threshold_for_discontinuity_check,
int half_dilation_kernel_size_for_discontinuity_map);
std::tuple<std::vector<std::vector<int>>, std::vector<std::vector<int>>>
CreateVertexAndImageVisibility(
const geometry::TriangleMesh& mesh,
const std::vector<geometry::Image>& images_depth,
const std::vector<geometry::Image>& images_mask,
const camera::PinholeCameraTrajectory& camera_trajectory,
double maximum_allowable_depth,
double depth_threshold_for_visibility_check);
void SetProxyIntensityForVertex(
const geometry::TriangleMesh& mesh,
const std::vector<geometry::Image>& images_gray,
const utility::optional<std::vector<ImageWarpingField>>& warping_fields,
const camera::PinholeCameraTrajectory& camera_trajectory,
const std::vector<std::vector<int>>& visibility_vertex_to_image,
std::vector<double>& proxy_intensity,
int image_boundary_margin);
void SetGeometryColorAverage(
geometry::TriangleMesh& mesh,
const std::vector<geometry::Image>& images_color,
const utility::optional<std::vector<ImageWarpingField>>& warping_fields,
const camera::PinholeCameraTrajectory& camera_trajectory,
const std::vector<std::vector<int>>& visibility_vertex_to_image,
int image_boundary_margin = 10,
int invisible_vertex_color_knn = 3);
} // namespace color_map
} // namespace pipelines
} // namespace open3d
| 43.767442 | 80 | 0.680659 | [
"mesh",
"geometry",
"vector"
] |
3eb648884fbdd64f2a4d42ec13989786b6010767 | 1,563 | h | C | NetworkConfiguration/AdamOptimizer.h | lkrizan/ECF_deep_learning | 1395688d6b8a3f4a19139c40754d27a2bd6523df | [
"MIT"
] | 1 | 2018-08-20T16:46:06.000Z | 2018-08-20T16:46:06.000Z | NetworkConfiguration/AdamOptimizer.h | lkrizan/ECF_deep_learning | 1395688d6b8a3f4a19139c40754d27a2bd6523df | [
"MIT"
] | null | null | null | NetworkConfiguration/AdamOptimizer.h | lkrizan/ECF_deep_learning | 1395688d6b8a3f4a19139c40754d27a2bd6523df | [
"MIT"
] | null | null | null | #ifndef AdamOptimizer_h
#define AdamOptimizer_h
#include "GradientDescentOptimizer.h"
#include <common/Common.h>
#define CURR_ITER "curr_iter"
#define FIRST_MOMENT_ESTIMATE "_s"
#define SECOND_MOMENT_ESTIMATE "_r"
namespace NetworkConfiguration {
class AdamOptimizer : public GradientDescentOptimizer
{
std::vector<std::pair<std::string, tensorflow::Tensor>> m_GradientMomentum;
std::vector<std::string> m_FetchList;
// exponential decay rates for moment estimates (and their 1 - rho variant)
tensorflow::Output m_Rho1;
tensorflow::Output m_Rho1Inv;
tensorflow::Output m_Rho2;
tensorflow::Output m_Rho2Inv;
// placeholder for current timestep
tensorflow::Output m_Iteration;
// small constant used for numerical stabilization
tensorflow::Output m_Delta;
void applyGradient(const std::string & name, const tensorflow::Input & variable, const tensorflow::Input & gradient, const Shape & variableShape, const std::string & layerName) override;
protected:
std::vector<std::pair<std::string, tensorflow::Tensor>> doGetFeedList() override;
public:
AdamOptimizer(tensorflow::Scope & scope, float startLearningRate, float endLearningRate, unsigned int numSteps, float weightDecay, float rho1 = 0.9, float rho2 = 0.999);
AdamOptimizer(const OptimizerParams & params) : AdamOptimizer(params.scope_, params.initialLearningRate_, params.finalLearningRate_, params.numSteps_, params.weightDecay_) {};
void setFeedList(std::vector<tensorflow::Tensor> & tensors) override;
std::vector<std::string> getFetchList() override;
};
}
#endif
| 37.214286 | 188 | 0.777991 | [
"shape",
"vector"
] |
3eb7edec4f8c80dff5701bfd4880011f2be84898 | 15,846 | h | C | src/stub/tfweaponbase.h | ramirez-tf2/Rafmod2021 | fa4a159971d0688923116eca984bbbc3e2b6f620 | [
"BSD-2-Clause"
] | null | null | null | src/stub/tfweaponbase.h | ramirez-tf2/Rafmod2021 | fa4a159971d0688923116eca984bbbc3e2b6f620 | [
"BSD-2-Clause"
] | null | null | null | src/stub/tfweaponbase.h | ramirez-tf2/Rafmod2021 | fa4a159971d0688923116eca984bbbc3e2b6f620 | [
"BSD-2-Clause"
] | null | null | null | #ifndef _INCLUDE_SIGSEGV_STUB_TFWEAPONBASE_H_
#define _INCLUDE_SIGSEGV_STUB_TFWEAPONBASE_H_
#include "stub/tfplayer.h"
#include "stub/entities.h"
typedef enum {
EMPTY,
SINGLE,
SINGLE_NPC,
WPN_DOUBLE,
DOUBLE_NPC,
BURST,
RELOAD,
RELOAD_NPC,
MELEE_MISS,
MELEE_HIT,
MELEE_HIT_WORLD,
SPECIAL1,
SPECIAL2,
SPECIAL3,
TAUNT,
DEPLOY,
} WeaponSound_t;
class CBaseCombatWeapon : public CEconEntity
{
public:
CBaseCombatCharacter *GetOwner() const { return this->m_hOwner; }
bool IsMeleeWeapon() const { return ft_IsMeleeWeapon(this); }
int GetMaxClip1() const { return vt_GetMaxClip1 (this); }
int GetMaxClip2() const { return vt_GetMaxClip2 (this); }
bool HasAmmo() { return vt_HasAmmo (this); }
void Equip(CBaseCombatCharacter *pOwner) { vt_Equip (this, pOwner); }
void Drop(const Vector& vecVelocity) { vt_Drop (this, vecVelocity); }
const char *GetViewModel(int viewmodelindex = 0) const { return vt_GetViewModel (this, viewmodelindex); }
const char *GetWorldModel() const { return vt_GetWorldModel(this); }
void SetViewModel() { vt_SetViewModel (this); }
void PrimaryAttack() { vt_PrimaryAttack (this); }
void SecondaryAttack() { vt_SecondaryAttack (this); }
//void CanPerformPrimaryAttack() { vt_CanPerformPrimaryAttack (this); }
void CanPerformSecondaryAttack() { vt_CanPerformSecondaryAttack (this); }
char const *GetShootSound(int type) { return vt_GetShootSound (this, type); }
int GetPrimaryAmmoType() { return vt_GetPrimaryAmmoType (this); }
void SetSubType(int type) { vt_SetSubType (this, type); }
DECL_SENDPROP(float, m_flNextPrimaryAttack);
DECL_SENDPROP(float, m_flNextSecondaryAttack);
DECL_SENDPROP(float, m_flTimeWeaponIdle);
DECL_SENDPROP(int, m_iState);
DECL_SENDPROP(int, m_iPrimaryAmmoType);
DECL_SENDPROP(int, m_iSecondaryAmmoType);
DECL_SENDPROP(int, m_iClip1);
DECL_SENDPROP(int, m_iClip2);
DECL_SENDPROP(int, m_iViewModelIndex);
DECL_SENDPROP(int, m_nViewModelIndex);
DECL_SENDPROP(int, m_iWorldModelIndex);
DECL_SENDPROP(bool, m_bFlipViewModel);
DECL_DATAMAP(bool, m_bReloadsSingly);
DECL_DATAMAP(bool, m_bInReload);
private:
DECL_SENDPROP(CHandle<CBaseCombatCharacter>, m_hOwner);
static MemberFuncThunk<const CBaseCombatWeapon *, bool> ft_IsMeleeWeapon;
static MemberVFuncThunk<const CBaseCombatWeapon *, int> vt_GetMaxClip1;
static MemberVFuncThunk<const CBaseCombatWeapon *, int> vt_GetMaxClip2;
static MemberVFuncThunk< CBaseCombatWeapon *, bool> vt_HasAmmo;
static MemberVFuncThunk< CBaseCombatWeapon *, void, CBaseCombatCharacter *> vt_Equip;
static MemberVFuncThunk< CBaseCombatWeapon *, void, const Vector&> vt_Drop;
static MemberVFuncThunk<const CBaseCombatWeapon *, const char *, int> vt_GetViewModel;
static MemberVFuncThunk<const CBaseCombatWeapon *, const char *> vt_GetWorldModel;
static MemberVFuncThunk< CBaseCombatWeapon *, void> vt_SetViewModel;
static MemberVFuncThunk< CBaseCombatWeapon *, void> vt_PrimaryAttack;
static MemberVFuncThunk< CBaseCombatWeapon *, void> vt_SecondaryAttack;
//static MemberVFuncThunk< CBaseCombatWeapon *, bool> vt_CanPerformPrimaryAttack;
static MemberVFuncThunk< CBaseCombatWeapon *, bool> vt_CanPerformSecondaryAttack;
static MemberVFuncThunk< CBaseCombatWeapon *, char const *, int> vt_GetShootSound;
static MemberVFuncThunk< CBaseCombatWeapon *, int> vt_GetPrimaryAmmoType;
static MemberVFuncThunk< CBaseCombatWeapon *, void, int> vt_SetSubType;
};
class CTFWeaponBase : public CBaseCombatWeapon, public IHasGenericMeter
{
public:
CTFPlayer *GetTFPlayerOwner() const { return ft_GetTFPlayerOwner(this); }
bool IsSilentKiller() { return ft_IsSilentKiller(this); }
float Energy_GetMaxEnergy() { return ft_Energy_GetMaxEnergy(this); }
int GetWeaponID() const { return vt_GetWeaponID (this); }
int GetPenetrateType() const { return vt_GetPenetrateType(this); }
void GetProjectileFireSetup(CTFPlayer *player, Vector vecOffset, Vector *vecSrc, QAngle *angForward, bool bHitTeammaates, float flEndDist) { vt_GetProjectileFireSetup (this, player, vecOffset, vecSrc, angForward, bHitTeammaates, flEndDist); }
bool ShouldRemoveInvisibilityOnPrimaryAttack() const { return vt_ShouldRemoveInvisibilityOnPrimaryAttack(this); }
bool IsEnergyWeapon() const { return vt_IsEnergyWeapon(this); }
float Energy_GetShotCost() const { return vt_Energy_GetShotCost(this); }
DECL_SENDPROP(float, m_flLastFireTime);
DECL_SENDPROP(float, m_flEffectBarRegenTime);
DECL_SENDPROP(float, m_flEnergy);
DECL_SENDPROP(CHandle<CTFWearable>, m_hExtraWearable);
DECL_SENDPROP(CHandle<CTFWearable>, m_hExtraWearableViewModel);
DECL_SENDPROP(bool, m_bBeingRepurposedForTaunt);
private:
static MemberFuncThunk<const CTFWeaponBase *, CTFPlayer *> ft_GetTFPlayerOwner;
static MemberFuncThunk<CTFWeaponBase *, bool> ft_IsSilentKiller;
static MemberFuncThunk<CTFWeaponBase *, float> ft_Energy_GetMaxEnergy;
static MemberVFuncThunk<const CTFWeaponBase *, int> vt_GetWeaponID;
static MemberVFuncThunk<const CTFWeaponBase *, int> vt_GetPenetrateType;
static MemberVFuncThunk<CTFWeaponBase *, void, CTFPlayer *, Vector , Vector *, QAngle *, bool , float > vt_GetProjectileFireSetup;
static MemberVFuncThunk<const CTFWeaponBase *, bool> vt_ShouldRemoveInvisibilityOnPrimaryAttack;
static MemberVFuncThunk<const CTFWeaponBase *, bool> vt_IsEnergyWeapon;
static MemberVFuncThunk<const CTFWeaponBase *, float> vt_Energy_GetShotCost;
};
class CTFWeaponBaseGun : public CTFWeaponBase {
public:
void UpdatePunchAngles(CTFPlayer *pPlayer) { ft_UpdatePunchAngles(this, pPlayer); }
float GetProjectileGravity() {return vt_GetProjectileGravity(this);}
float GetProjectileSpeed() {return vt_GetProjectileSpeed(this);}
int GetWeaponProjectileType() const {return vt_GetWeaponProjectileType(this);}
float GetProjectileDamage() { return vt_GetProjectileDamage(this); }
void ModifyProjectile(CBaseAnimating * anim) { return vt_ModifyProjectile(this, anim); }
void RemoveProjectileAmmo(CTFPlayer *pPlayer) { vt_RemoveProjectileAmmo(this, pPlayer); }
void DoFireEffects() { vt_DoFireEffects (this); }
bool ShouldPlayFireAnim() { return vt_ShouldPlayFireAnim (this); }
private:
static MemberVFuncThunk<CTFWeaponBaseGun *, float> vt_GetProjectileGravity;
static MemberVFuncThunk<CTFWeaponBaseGun *, float> vt_GetProjectileSpeed;
static MemberVFuncThunk<const CTFWeaponBaseGun *, int> vt_GetWeaponProjectileType;
static MemberVFuncThunk<CTFWeaponBaseGun *, float> vt_GetProjectileDamage;
static MemberVFuncThunk<CTFWeaponBaseGun *, void, CBaseAnimating *> vt_ModifyProjectile;
static MemberFuncThunk<CTFWeaponBaseGun *, void, CTFPlayer *> ft_UpdatePunchAngles;
static MemberVFuncThunk<CTFWeaponBaseGun *, void, CTFPlayer *> vt_RemoveProjectileAmmo;
static MemberVFuncThunk<CTFWeaponBaseGun *, void> vt_DoFireEffects;
static MemberVFuncThunk<CTFWeaponBaseGun *, bool> vt_ShouldPlayFireAnim;
};
class CTFPipebombLauncher : public CTFWeaponBaseGun {};
class CTFGrenadeLauncher : public CTFWeaponBaseGun {};
class CTFSpellBook : public CTFWeaponBaseGun {
public:
void RollNewSpell(int tier) { ft_RollNewSpell(this, tier); }
public:
DECL_SENDPROP(int, m_iSelectedSpellIndex);
DECL_SENDPROP(int, m_iSpellCharges);
private:
static MemberFuncThunk<CTFSpellBook *, void, int> ft_RollNewSpell;
};
class CTFCompoundBow : public CTFPipebombLauncher
{
public:
/* these 4 vfuncs really ought to be in a separate ITFChargeUpWeapon stub
* class, but reliably determining these vtable indexes at runtime is hard,
* plus all calls would have to do an rtti_cast from the derived type to
* ITFChargeUpWeapon before calling the thunk; incidentally, this means that
* ITFChargeUpWeapon would need to be a template class with a parameter
* telling it what the derived class is, so that it knows what source ptr
* type to pass to rtti_cast... what a mess */
// bool CanCharge() { return vt_CanCharge (this); }
// float GetChargeBeginTime() { return vt_GetChargeBeginTime(this); }
float GetChargeMaxTime() { return vt_GetChargeMaxTime (this); }
float GetCurrentCharge() { return vt_GetCurrentCharge (this); }
private:
// static MemberVFuncThunk<CTFCompoundBow *, bool> vt_CanCharge;
// static MemberVFuncThunk<CTFCompoundBow *, float> vt_GetChargeBeginTime;
static MemberVFuncThunk<CTFCompoundBow *, float> vt_GetChargeMaxTime;
static MemberVFuncThunk<CTFCompoundBow *, float> vt_GetCurrentCharge;
};
class CTFMinigun : public CTFWeaponBaseGun
{
public:
enum MinigunState_t : int32_t
{
AC_STATE_IDLE = 0,
AC_STATE_STARTFIRING = 1,
AC_STATE_FIRING = 2,
AC_STATE_SPINNING = 3,
AC_STATE_DRYFIRE = 4,
};
DECL_SENDPROP(MinigunState_t, m_iWeaponState);
};
class CTFSniperRifle : public CTFWeaponBaseGun
{
public:
void ExplosiveHeadShot(CTFPlayer *attacker, CTFPlayer *victim) { ft_ExplosiveHeadShot(this, attacker, victim); }
void ApplyChargeSpeedModifications(float &value) { ft_ApplyChargeSpeedModifications(this, value); }
float SniperRifleChargeRateMod() { return vt_SniperRifleChargeRateMod(this); }
DECL_SENDPROP(float, m_flChargedDamage);
private:
static MemberFuncThunk<CTFSniperRifle *, void, CTFPlayer *, CTFPlayer *> ft_ExplosiveHeadShot;
static MemberFuncThunk<CTFSniperRifle *, void, float &> ft_ApplyChargeSpeedModifications;
static MemberVFuncThunk<CTFSniperRifle *, float> vt_SniperRifleChargeRateMod;
};
class CTFSniperRifleClassic : public CTFSniperRifle {};
class CTFSniperRifleDecap : public CTFSniperRifle
{
public:
int GetCount() { return ft_GetCount(this); }
private:
static MemberFuncThunk<CTFSniperRifleDecap *, int> ft_GetCount;
};
class CTFWeaponBaseMelee : public CTFWeaponBase
{
public:
DECL_EXTRACT(float, m_flSmackTime);
int GetSwingRange() { return vt_GetSwingRange(this); }
bool DoSwingTrace(trace_t& tr) { return vt_DoSwingTrace (this, tr); }
private:
static MemberVFuncThunk<CTFWeaponBaseMelee *, int> vt_GetSwingRange;
static MemberVFuncThunk<CTFWeaponBaseMelee *, bool, trace_t&> vt_DoSwingTrace;
};
class CTFKnife : public CTFWeaponBaseMelee
{
public:
bool CanPerformBackstabAgainstTarget(CTFPlayer *player) { return ft_CanPerformBackstabAgainstTarget(this, player); }
bool IsBehindAndFacingTarget(CTFPlayer *player) { return ft_IsBehindAndFacingTarget (this, player); }
private:
static MemberFuncThunk<CTFKnife *, bool, CTFPlayer *> ft_CanPerformBackstabAgainstTarget;
static MemberFuncThunk<CTFKnife *, bool, CTFPlayer *> ft_IsBehindAndFacingTarget;
};
class CTFBottle : public CTFWeaponBaseMelee
{
public:
DECL_SENDPROP(bool, m_bBroken);
};
class CTFBonesaw : public CTFWeaponBaseMelee {};
class CTFWrench : public CTFWeaponBaseMelee {};
class CTFRobotArm : public CTFWrench
{
public:
/* this is a hacky mess for now */
int GetPunchNumber() const { return *reinterpret_cast<int *>((uintptr_t)&this->m_hRobotArm + 0x04); }
float GetLastPunchTime() const { return *reinterpret_cast<float *>((uintptr_t)&this->m_hRobotArm + 0x08); }
bool ShouldInflictComboDamage() const { return *reinterpret_cast<bool *>((uintptr_t)&this->m_hRobotArm + 0x0c); }
bool ShouldImpartMaxForce() const { return *reinterpret_cast<bool *>((uintptr_t)&this->m_hRobotArm + 0x0d); }
// 20151007a:
// CTFRobotArm +0x800 CHandle<CTFWearableRobotArm> m_hRobotArm
// CTFRobotArm +0x804 int m_iPunchNumber
// CTFRobotArm +0x808 float m_flTimeLastPunch
// CTFRobotArm +0x80c bool m_bComboPunch
// CTFRobotArm +0x80d bool m_bMaxForce
private:
DECL_SENDPROP(CHandle<CTFWearableRobotArm>, m_hRobotArm);
};
class CTFBuffItem : public CTFWeaponBaseMelee {};
class CTFDecapitationMeleeWeaponBase : public CTFWeaponBaseMelee {};
class CTFSword : public CTFDecapitationMeleeWeaponBase
{
public:
float GetSwordSpeedMod() { return ft_GetSwordSpeedMod(this); }
int GetSwordHealthMod() { return ft_GetSwordHealthMod(this); }
private:
static MemberFuncThunk<CTFSword *, float> ft_GetSwordSpeedMod;
static MemberFuncThunk<CTFSword *, int> ft_GetSwordHealthMod;
};
class CTFLunchBox : public CTFWeaponBase {};
class CTFLunchBox_Drink : public CTFLunchBox {};
class CWeaponMedigun : public CTFWeaponBase
{
public:
CBaseEntity *GetHealTarget() const { return this->m_hHealingTarget; }
float GetHealRate() { return vt_GetHealRate(this); }
float GetCharge() const { return this->m_flChargeLevel; }
void SetCharge(float charge) { this->m_flChargeLevel = charge; }
private:
static MemberVFuncThunk<CWeaponMedigun *, float> vt_GetHealRate;
DECL_SENDPROP(CHandle<CBaseEntity>, m_hHealingTarget);
DECL_SENDPROP(float, m_flChargeLevel);
};
class CTFFlameThrower : public CTFWeaponBaseGun
{
public:
Vector GetVisualMuzzlePos() { return ft_GetMuzzlePosHelper(this, true); }
Vector GetFlameOriginPos() { return ft_GetMuzzlePosHelper(this, false); }
float GetDeflectionRadius() { return ft_GetDeflectionRadius(this); }
DECL_SENDPROP(int, m_iWeaponState);
private:
static MemberFuncThunk<CTFFlameThrower *, Vector, bool> ft_GetMuzzlePosHelper;
static MemberFuncThunk<CTFFlameThrower *, float> ft_GetDeflectionRadius;
};
class CTFWeaponBuilder : public CTFWeaponBase {
public:
DECL_SENDPROP(int, m_iObjectType);
DECL_SENDPROP(int, m_iObjectMode);
DECL_SENDPROP_RW(bool[4], m_aBuildableObjectTypes);
};
class CTFWeaponSapper : public CTFWeaponBuilder {};
class CTFWeaponInvis : public CTFWeaponBase {};
class CBaseViewModel : public CBaseAnimating
{
public:
CBaseCombatWeapon *GetWeapon() const { return this->m_hWeapon; }
private:
DECL_SENDPROP(int, m_nViewModelIndex);
DECL_SENDPROP(CHandle<CBaseEntity>, m_hOwner);
DECL_SENDPROP(CHandle<CBaseCombatWeapon>, m_hWeapon);
};
class CTFViewModel : public CBaseViewModel {};
inline CBaseCombatWeapon *ToBaseCombatWeapon(CBaseEntity *pEntity)
{
if (pEntity == nullptr) return nullptr;
return pEntity->MyCombatWeaponPointer();
}
bool WeaponID_IsSniperRifle(int id);
bool WeaponID_IsSniperRifleOrBow(int id);
int GetWeaponId(const char *name);
const char *WeaponIdToAlias(int weapon_id);
float CalculateProjectileSpeed(CTFWeaponBaseGun *weapon);
inline CEconEntity *GetEconEntityAtLoadoutSlot(CTFPlayer *player, int slot) {
CEconEntity *entity = nullptr;
CTFPlayerSharedUtils::GetEconItemViewByLoadoutSlot(player, slot, &entity);
return entity;
}
const char *TranslateWeaponEntForClass_improved(const char *name, int classnum);
#endif
| 41.7 | 251 | 0.71324 | [
"vector"
] |
3ebf8530284eed401dc986c152b328cc01f99e89 | 1,118 | h | C | src/Include/GPGOMEA/Evolution/NSGA2GenerationHandler.h | NickTUD/GP-GOMEA | f6e150a417855355f520f27db4cfb0b2a9003000 | [
"Apache-2.0"
] | null | null | null | src/Include/GPGOMEA/Evolution/NSGA2GenerationHandler.h | NickTUD/GP-GOMEA | f6e150a417855355f520f27db4cfb0b2a9003000 | [
"Apache-2.0"
] | null | null | null | src/Include/GPGOMEA/Evolution/NSGA2GenerationHandler.h | NickTUD/GP-GOMEA | f6e150a417855355f520f27db4cfb0b2a9003000 | [
"Apache-2.0"
] | null | null | null | #ifndef NSGA2GENERATIONHANDLER_H
#define NSGA2GENERATIONHANDLER_H
#include "GPGOMEA/Evolution/GenerationHandler.h"
#include "GPGOMEA/Genotype/Node.h"
#include "GPGOMEA/Utils/ConfigurationOptions.h"
#include "GPGOMEA/Selection/TournamentSelection.h"
#include "GPGOMEA/Variation/SubtreeVariator.h"
#include "GPGOMEA/Semantics/SemanticBackpropagator.h"
#include "GPGOMEA/Semantics/SemanticLibrary.h"
#include <armadillo>
#include <vector>
#include <unordered_map>
class NSGA2GenerationHandler : public GenerationHandler {
public:
NSGA2GenerationHandler(ConfigurationOptions * conf, TreeInitializer * tree_initializer, Fitness * fitness, SemanticLibrary * semlib = NULL, SemanticBackpropagator * semback = NULL) :
GenerationHandler(conf, tree_initializer, fitness, semlib, semback) {}; // inherit same constructor
virtual void PerformGeneration(std::vector<Node *> & population) override;
std::vector<std::vector<Node*>> FastNonDominatedSorting(std::vector<Node*> & population);
void ComputeCrowndingDistance(std::vector<Node *> & front);
private:
};
#endif /* GENERATIONHANDLER_H */
| 32.882353 | 187 | 0.779964 | [
"vector"
] |
3ec287087af030802629deae590ba20592c8cb94 | 802 | h | C | include/convert_cast.h | jvstech/jvs-netlib | 80374521bc67135397e01d38b90ae65fa39adb10 | [
"MIT"
] | null | null | null | include/convert_cast.h | jvstech/jvs-netlib | 80374521bc67135397e01d38b90ae65fa39adb10 | [
"MIT"
] | null | null | null | include/convert_cast.h | jvstech/jvs-netlib | 80374521bc67135397e01d38b90ae65fa39adb10 | [
"MIT"
] | null | null | null | //!
//! @file convert_cast.h
//!
//! Defines a callable object for defining and providing custom type
//! conversions.
//!
#if !defined(JVS_CONVERT_CAST_H_)
#define JVS_CONVERT_CAST_H_
namespace jvs
{
//!
//! @struct ConvertCast
//!
//! Default implementation of a type conversion provider. This is meant to be
//! specialized by users to provide completely custom type conversion via the
//! convert_to function.
//!
template <typename FromType, typename ToType>
struct ConvertCast
{
ToType operator()(const FromType& value) const
{
return reinterpret_cast<ToType>(value);
}
};
template <typename ToType, typename FromType>
inline static auto convert_to(const FromType& value)
{
return ConvertCast<FromType, ToType>{}(value);
}
} // namespace jvs
#endif // !JVS_CONVERT_CAST_H_
| 20.05 | 77 | 0.730673 | [
"object"
] |
3ec6bf61899e340c49a0878dee3fae349200a136 | 46,220 | c | C | sw/solutions/instaspin_foc/src/proj_lab11b.c | Hao878/Toaero_ESC | 8afc32b54145ea5618d7497a758a2672b18c1acc | [
"MIT"
] | 3 | 2021-01-21T12:42:10.000Z | 2022-02-10T00:14:01.000Z | sw/solutions/instaspin_foc/src/proj_lab11b.c | Hao878/Toaero_ESC | 8afc32b54145ea5618d7497a758a2672b18c1acc | [
"MIT"
] | null | null | null | sw/solutions/instaspin_foc/src/proj_lab11b.c | Hao878/Toaero_ESC | 8afc32b54145ea5618d7497a758a2672b18c1acc | [
"MIT"
] | 3 | 2018-12-28T17:16:05.000Z | 2020-02-01T05:42:56.000Z | /* --COPYRIGHT--,BSD
* Copyright (c) 2015, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* --/COPYRIGHT--*/
//! \file solutions/instaspin_foc/src/proj_lab011b.c
//! \brief Vibration Compensation Example
//!
//! (C) Copyright 2015, Texas Instruments, Inc.
//! \defgroup PROJ_LAB11B PROJ_LAB11B
//@{
//! \defgroup PROJ_LAB11B_OVERVIEW Project Overview
//!
//! Vibration Compensation Example
//!
// **************************************************************************
// the includes
// system includes
#include <math.h>
#include "main.h"
#include "sw/modules/vib_comp/src/32b/vib_comp.h"
#ifdef FLASH
#pragma CODE_SECTION(mainISR,"ramfuncs");
#pragma CODE_SECTION(runSetTrigger,"ramfuncs");
#pragma CODE_SECTION(runFieldWeakening,"ramfuncs");
#pragma CODE_SECTION(runCurrentReconstruction,"ramfuncs");
#pragma CODE_SECTION(angleDelayComp,"ramfuncs");
#pragma CODE_SECTION(getAbsElecAngle,"ramfuncs");
#pragma CODE_SECTION(getAbsMechAngle,"ramfuncs");
#endif
// Include header files used in the main function
// **************************************************************************
// the defines
// **************************************************************************
// the globals
CLARKE_Handle clarkeHandle_I; //!< the handle for the current Clarke transform
CLARKE_Obj clarke_I; //!< the current Clarke transform object
CLARKE_Handle clarkeHandle_V; //!< the handle for the voltage Clarke transform
CLARKE_Obj clarke_V; //!< the voltage Clarke transform object
CPU_USAGE_Handle cpu_usageHandle;
CPU_USAGE_Obj cpu_usage;
EST_Handle estHandle; //!< the handle for the estimator
FW_Handle fwHandle;
FW_Obj fw;
PID_Obj pid[3]; //!< three handles for PID controllers 0 - Speed, 1 - Id, 2 - Iq
PID_Handle pidHandle[3]; //!< three objects for PID controllers 0 - Speed, 1 - Id, 2 - Iq
uint16_t pidCntSpeed; //!< count variable to decimate the execution of the speed PID controller
IPARK_Handle iparkHandle; //!< the handle for the inverse Park transform
IPARK_Obj ipark; //!< the inverse Park transform object
FILTER_FO_Handle filterHandle[6]; //!< the handles for the 3-current and 3-voltage filters for offset calculation
FILTER_FO_Obj filter[6]; //!< the 3-current and 3-voltage filters for offset calculation
SVGENCURRENT_Obj svgencurrent;
SVGENCURRENT_Handle svgencurrentHandle;
SVGEN_Handle svgenHandle; //!< the handle for the space vector generator
SVGEN_Obj svgen; //!< the space vector generator object
TRAJ_Handle trajHandle_Id; //!< the handle for the id reference trajectory
TRAJ_Obj traj_Id; //!< the id reference trajectory object
TRAJ_Handle trajHandle_spd; //!< the handle for the speed reference trajectory
TRAJ_Obj traj_spd; //!< the speed reference trajectory object
#ifdef CSM_ENABLE
#pragma DATA_SECTION(halHandle,"rom_accessed_data");
#endif
HAL_Handle halHandle; //!< the handle for the hardware abstraction layer (HAL)
HAL_PwmData_t gPwmData = {_IQ(0.0), _IQ(0.0), _IQ(0.0)}; //!< contains the three pwm values -1.0 - 0%, 1.0 - 100%
HAL_AdcData_t gAdcData; //!< contains three current values, three voltage values and one DC buss value
MATH_vec3 gOffsets_I_pu = {_IQ(0.0), _IQ(0.0), _IQ(0.0)}; //!< contains the offsets for the current feedback
MATH_vec3 gOffsets_V_pu = {_IQ(0.0), _IQ(0.0), _IQ(0.0)}; //!< contains the offsets for the voltage feedback
MATH_vec2 gIdq_ref_pu = {_IQ(0.0), _IQ(0.0)}; //!< contains the Id and Iq references
MATH_vec2 gVdq_out_pu = {_IQ(0.0), _IQ(0.0)}; //!< contains the output Vd and Vq from the current controllers
MATH_vec2 gIdq_pu = {_IQ(0.0), _IQ(0.0)}; //!< contains the Id and Iq measured values
#ifdef CSM_ENABLE
#pragma DATA_SECTION(gUserParams,"rom_accessed_data");
#endif
USER_Params gUserParams;
volatile MOTOR_Vars_t gMotorVars = MOTOR_Vars_INIT; //!< the global motor variables that are defined in main.h and used for display in the debugger's watch window
#ifdef FLASH
// Used for running BackGround in flash, and ISR in RAM
extern uint16_t *RamfuncsLoadStart, *RamfuncsLoadEnd, *RamfuncsRunStart;
#ifdef CSM_ENABLE
extern uint16_t *econst_start, *econst_end, *econst_ram_load;
extern uint16_t *switch_start, *switch_end, *switch_ram_load;
#endif
#endif
MATH_vec3 gIavg = {_IQ(0.0), _IQ(0.0), _IQ(0.0)};
uint16_t gIavg_shift = 1;
MATH_vec3 gPwmData_prev = {_IQ(0.0), _IQ(0.0), _IQ(0.0)};
#ifdef DRV8301_SPI
// Watch window interface to the 8301 SPI
DRV_SPI_8301_Vars_t gDrvSpi8301Vars;
#endif
#ifdef DRV8305_SPI
// Watch window interface to the 8305 SPI
DRV_SPI_8305_Vars_t gDrvSpi8305Vars;
#endif
_iq gFlux_pu_to_Wb_sf;
_iq gFlux_pu_to_VpHz_sf;
_iq gTorque_Ls_Id_Iq_pu_to_Nm_sf;
_iq gTorque_Flux_Iq_pu_to_Nm_sf;
_iq gSpeed_krpm_to_pu_sf = _IQ((float_t)USER_MOTOR_NUM_POLE_PAIRS * 1000.0 / (USER_IQ_FULL_SCALE_FREQ_Hz * 60.0));
_iq gSpeed_hz_to_krpm_sf = _IQ(60.0 / (float_t)USER_MOTOR_NUM_POLE_PAIRS / 1000.0);
_iq gIs_Max_squared_pu = _IQ((USER_MOTOR_MAX_CURRENT * USER_MOTOR_MAX_CURRENT) / (USER_IQ_FULL_SCALE_CURRENT_A * USER_IQ_FULL_SCALE_CURRENT_A));
float_t gCpuUsagePercentageMin = 0.0;
float_t gCpuUsagePercentageAvg = 0.0;
float_t gCpuUsagePercentageMax = 0.0;
uint32_t gOffsetCalcCount = 0;
uint16_t gTrjCnt = 0;
volatile bool gFlag_enableRsOnLine = false;
volatile bool gFlag_updateRs = false;
volatile _iq gRsOnLineFreq_Hz = _IQ(0.2);
volatile _iq gRsOnLineId_mag_A = _IQ(0.5);
volatile _iq gRsOnLinePole_Hz = _IQ(0.2);
VIB_COMP_Handle vib_compHandle;
#ifdef F2802xF
#pragma DATA_SECTION(vib_comp_reserved,"vib_buf_data");
#endif
_iq vib_comp_reserved[400]; //<! this buffer is required to reserve memory used by the vibration compensation module
#ifdef F2802xF
#pragma DATA_SECTION(gSpeed_fbk_out,"ebss_extension");
#endif
_iq gSpeed_fbk_out[360]; //<! this buffer is used to store the output of the speed controller vs mechanical angle
uint16_t gSpeed_array_index = 0; //<! index used for gSpeed_fbk_out[] buffer
_iq gSpeed_max_pu = _IQ(0.0); //<! variable used to store the maximum speed for speed variation calculation
_iq gSpeed_min_pu = _IQ(1.0); //<! variable used to store the minimum speed for speed variation calculation
_iq gSpeed_delta_krpm = _IQ(0.0); //<! variable used to store the speed variation calculation
volatile bool gFlag_speedStatsReset = false; //<! this flag is used to reset the speed variation calculation
_iq gAbsAngle_elec_pu = _IQ(0.0); //<! variable used for electrical angle from _IQ(0.0) to _IQ(1.0)
_iq gAbsAngle_mech_pu = _IQ(0.0); //<! variable used for mechanical angle from _IQ(0.0) to _IQ(1.0)
_iq gAngle_mech_poles = _IQ(0.0); //<! variable used for mechanical angle from _IQ(0.0) to _IQ(USER_MOTOR_NUM_POLE_PAIRS)
_iq gAngle_z1_pu = _IQ(0.0); //<! variable used for electrical angle in previous sample
volatile _iq gAlpha = _IQ(0.99); //<! learning rate of the vibration compensation module from _IQ(0.0) to _IQ(1.0)
volatile int16_t gAdvIndexDelta = 10; //<! phase advance of the vibration compensation module from 0 to 360
volatile bool gFlag_enableOutput = false; //<! flag that enables the output from the vibration compensation module to the Iq reference
volatile bool gFlag_enableUpdates = true; //<! flag that enables learning of the load, and storing the load profile internally in the vibration compensation module
volatile bool gFlag_resetVibComp = false; //<! flag that resets the learned load curve
// **************************************************************************
// the functions
void main(void)
{
// Only used if running from FLASH
// Note that the variable FLASH is defined by the project
#ifdef FLASH
// Copy time critical code and Flash setup code to RAM
// The RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart
// symbols are created by the linker. Refer to the linker files.
memCopy((uint16_t *)&RamfuncsLoadStart,(uint16_t *)&RamfuncsLoadEnd,(uint16_t *)&RamfuncsRunStart);
#ifdef CSM_ENABLE
//copy .econst to unsecure RAM
if(*econst_end - *econst_start)
{
memCopy((uint16_t *)&econst_start,(uint16_t *)&econst_end,(uint16_t *)&econst_ram_load);
}
//copy .switch ot unsecure RAM
if(*switch_end - *switch_start)
{
memCopy((uint16_t *)&switch_start,(uint16_t *)&switch_end,(uint16_t *)&switch_ram_load);
}
#endif
#endif
// initialize the hardware abstraction layer
halHandle = HAL_init(&hal,sizeof(hal));
// check for errors in user parameters
USER_checkForErrors(&gUserParams);
// store user parameter error in global variable
gMotorVars.UserErrorCode = USER_getErrorCode(&gUserParams);
// do not allow code execution if there is a user parameter error
if(gMotorVars.UserErrorCode != USER_ErrorCode_NoError)
{
for(;;)
{
gMotorVars.Flag_enableSys = false;
}
}
// initialize the Clarke modules
clarkeHandle_I = CLARKE_init(&clarke_I,sizeof(clarke_I));
clarkeHandle_V = CLARKE_init(&clarke_V,sizeof(clarke_V));
// initialize the estimator
estHandle = EST_init((void *)USER_EST_HANDLE_ADDRESS, 0x200);
// initialize the user parameters
USER_setParams(&gUserParams);
// set the hardware abstraction layer parameters
HAL_setParams(halHandle,&gUserParams);
#ifdef FAST_ROM_V1p6
{
CTRL_Handle ctrlHandle = CTRL_init((void *)USER_CTRL_HANDLE_ADDRESS, 0x200);
CTRL_Obj *obj = (CTRL_Obj *)ctrlHandle;
obj->estHandle = estHandle;
// initialize the estimator through the controller
CTRL_setParams(ctrlHandle,&gUserParams);
CTRL_setUserMotorParams(ctrlHandle);
CTRL_setupEstIdleState(ctrlHandle);
}
#else
{
// initialize the estimator
EST_setEstParams(estHandle,&gUserParams);
EST_setupEstIdleState(estHandle);
}
#endif
// disable Rs recalculation by default
gMotorVars.Flag_enableRsRecalc = false;
EST_setFlag_enableRsRecalc(estHandle,false);
// configure RsOnLine
EST_setFlag_enableRsOnLine(estHandle,gFlag_enableRsOnLine);
EST_setFlag_updateRs(estHandle,gFlag_updateRs);
EST_setRsOnLineAngleDelta_pu(estHandle,_IQmpy(gRsOnLineFreq_Hz, _IQ(1.0/USER_ISR_FREQ_Hz)));
EST_setRsOnLineId_mag_pu(estHandle,_IQmpy(gRsOnLineId_mag_A, _IQ(1.0/USER_IQ_FULL_SCALE_CURRENT_A)));
// Calculate coefficients for all filters
{
_iq b0 = _IQmpy(gRsOnLinePole_Hz, _IQ(1.0/USER_ISR_FREQ_Hz));
_iq a1 = b0 - _IQ(1.0);
EST_setRsOnLineFilterParams(estHandle,EST_RsOnLineFilterType_Current,b0,a1,_IQ(0.0),b0,a1,_IQ(0.0));
EST_setRsOnLineFilterParams(estHandle,EST_RsOnLineFilterType_Voltage,b0,a1,_IQ(0.0),b0,a1,_IQ(0.0));
}
// set the number of current sensors
setupClarke_I(clarkeHandle_I,USER_NUM_CURRENT_SENSORS);
// set the number of voltage sensors
setupClarke_V(clarkeHandle_V,USER_NUM_VOLTAGE_SENSORS);
// set the pre-determined current and voltage feeback offset values
gOffsets_I_pu.value[0] = _IQ(I_A_offset);
gOffsets_I_pu.value[1] = _IQ(I_B_offset);
gOffsets_I_pu.value[2] = _IQ(I_C_offset);
gOffsets_V_pu.value[0] = _IQ(V_A_offset);
gOffsets_V_pu.value[1] = _IQ(V_B_offset);
gOffsets_V_pu.value[2] = _IQ(V_C_offset);
// initialize the PID controllers
{
_iq maxCurrent_pu = _IQ(USER_MOTOR_MAX_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A);
_iq maxVoltage_pu = _IQ(USER_MAX_VS_MAG_PU * USER_VD_SF);
float_t fullScaleCurrent = USER_IQ_FULL_SCALE_CURRENT_A;
float_t fullScaleVoltage = USER_IQ_FULL_SCALE_VOLTAGE_V;
float_t IsrPeriod_sec = 1.0 / USER_ISR_FREQ_Hz;
float_t Ls_d = USER_MOTOR_Ls_d;
float_t Ls_q = USER_MOTOR_Ls_q;
float_t Rs = USER_MOTOR_Rs;
float_t RoverLs_d = Rs/Ls_d;
float_t RoverLs_q = Rs/Ls_q;
_iq Kp_Id = _IQ((0.25*Ls_d*fullScaleCurrent)/(IsrPeriod_sec*fullScaleVoltage));
_iq Ki_Id = _IQ(RoverLs_d*IsrPeriod_sec);
_iq Kp_Iq = _IQ((0.25*Ls_q*fullScaleCurrent)/(IsrPeriod_sec*fullScaleVoltage));
_iq Ki_Iq = _IQ(RoverLs_q*IsrPeriod_sec);
pidHandle[0] = PID_init(&pid[0],sizeof(pid[0]));
pidHandle[1] = PID_init(&pid[1],sizeof(pid[1]));
pidHandle[2] = PID_init(&pid[2],sizeof(pid[2]));
PID_setGains(pidHandle[0],_IQ(3.0),_IQ(0.03),_IQ(0.0));
PID_setMinMax(pidHandle[0],-maxCurrent_pu,maxCurrent_pu);
PID_setUi(pidHandle[0],_IQ(0.0));
pidCntSpeed = 0;
PID_setGains(pidHandle[1],Kp_Id,Ki_Id,_IQ(0.0));
PID_setMinMax(pidHandle[1],-maxVoltage_pu,maxVoltage_pu);
PID_setUi(pidHandle[1],_IQ(0.0));
PID_setGains(pidHandle[2],Kp_Iq,Ki_Iq,_IQ(0.0));
PID_setMinMax(pidHandle[2],_IQ(0.0),_IQ(0.0));
PID_setUi(pidHandle[2],_IQ(0.0));
}
{
uint16_t cnt;
// initialize the handle for vibration compensation
vib_compHandle = VIB_COMP_init(&vib_comp_reserved, VIB_COMP_getSizeOfObject());
VIB_COMP_setParams(vib_compHandle, gAlpha, gAdvIndexDelta);
VIB_COMP_reset(vib_compHandle);
for(cnt=0;cnt<360;cnt++)
{
gSpeed_fbk_out[cnt] = _IQ(0.0);
}
}
// initialize the speed reference in kilo RPM where base speed is USER_IQ_FULL_SCALE_FREQ_Hz
gMotorVars.SpeedRef_krpm = _IQmpy(_IQ(10.0), gSpeed_hz_to_krpm_sf);
// initialize the inverse Park module
iparkHandle = IPARK_init(&ipark,sizeof(ipark));
// initialize and configure offsets using filters
{
uint16_t cnt = 0;
_iq b0 = _IQ(gUserParams.offsetPole_rps/(float_t)gUserParams.ctrlFreq_Hz);
_iq a1 = (b0 - _IQ(1.0));
_iq b1 = _IQ(0.0);
for(cnt=0;cnt<6;cnt++)
{
filterHandle[cnt] = FILTER_FO_init(&filter[cnt],sizeof(filter[0]));
FILTER_FO_setDenCoeffs(filterHandle[cnt],a1);
FILTER_FO_setNumCoeffs(filterHandle[cnt],b0,b1);
FILTER_FO_setInitialConditions(filterHandle[cnt],_IQ(0.0),_IQ(0.0));
}
gMotorVars.Flag_enableOffsetcalc = false;
}
// initialize the space vector generator module
svgenHandle = SVGEN_init(&svgen,sizeof(svgen));
// Initialize and setup the 100% SVM generator
svgencurrentHandle = SVGENCURRENT_init(&svgencurrent,sizeof(svgencurrent));
// setup svgen current
{
float_t minWidth_microseconds = 2.0;
uint16_t minWidth_counts = (uint16_t)(minWidth_microseconds * USER_SYSTEM_FREQ_MHz);
float_t fdutyLimit = 0.5-(2.0*minWidth_microseconds*USER_PWM_FREQ_kHz*0.001);
_iq dutyLimit = _IQ(fdutyLimit);
SVGENCURRENT_setMinWidth(svgencurrentHandle, minWidth_counts);
SVGENCURRENT_setIgnoreShunt(svgencurrentHandle, use_all);
SVGENCURRENT_setMode(svgencurrentHandle,all_phase_measurable);
SVGENCURRENT_setVlimit(svgencurrentHandle,dutyLimit);
}
// initialize the speed reference trajectory
trajHandle_spd = TRAJ_init(&traj_spd,sizeof(traj_spd));
// configure the speed reference trajectory
TRAJ_setTargetValue(trajHandle_spd,_IQ(0.0));
TRAJ_setIntValue(trajHandle_spd,_IQ(0.0));
TRAJ_setMinValue(trajHandle_spd,_IQ(-1.0));
TRAJ_setMaxValue(trajHandle_spd,_IQ(1.0));
TRAJ_setMaxDelta(trajHandle_spd,_IQ(USER_MAX_ACCEL_Hzps / USER_IQ_FULL_SCALE_FREQ_Hz / USER_ISR_FREQ_Hz));
// initialize the Id reference trajectory
trajHandle_Id = TRAJ_init(&traj_Id,sizeof(traj_Id));
if(USER_MOTOR_TYPE == MOTOR_Type_Pm)
{
// configure the Id reference trajectory
TRAJ_setTargetValue(trajHandle_Id,_IQ(0.0));
TRAJ_setIntValue(trajHandle_Id,_IQ(0.0));
TRAJ_setMinValue(trajHandle_Id,_IQ(-USER_MOTOR_MAX_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A));
TRAJ_setMaxValue(trajHandle_Id,_IQ(USER_MOTOR_MAX_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A));
TRAJ_setMaxDelta(trajHandle_Id,_IQ(USER_MOTOR_RES_EST_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A / USER_ISR_FREQ_Hz));
// Initialize field weakening
fwHandle = FW_init(&fw,sizeof(fw));
FW_setFlag_enableFw(fwHandle, false); // Disable field weakening
FW_clearCounter(fwHandle); // Clear field weakening counter
FW_setNumIsrTicksPerFwTick(fwHandle, FW_NUM_ISR_TICKS_PER_CTRL_TICK); // Set the number of ISR per field weakening ticks
FW_setDeltas(fwHandle, FW_INC_DELTA, FW_DEC_DELTA); // Set the deltas of field weakening
FW_setOutput(fwHandle, _IQ(0.0)); // Set initial output of field weakening to zero
FW_setMinMax(fwHandle,_IQ(USER_MAX_NEGATIVE_ID_REF_CURRENT_A/USER_IQ_FULL_SCALE_CURRENT_A),_IQ(0.0)); // Set the field weakening controller limits
}
else
{
// configure the Id reference trajectory
TRAJ_setTargetValue(trajHandle_Id,_IQ(0.0));
TRAJ_setIntValue(trajHandle_Id,_IQ(0.0));
TRAJ_setMinValue(trajHandle_Id,_IQ(0.0));
TRAJ_setMaxValue(trajHandle_Id,_IQ(USER_MOTOR_MAGNETIZING_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A));
TRAJ_setMaxDelta(trajHandle_Id,_IQ(USER_MOTOR_MAGNETIZING_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A / USER_ISR_FREQ_Hz));
}
// initialize the CPU usage module
cpu_usageHandle = CPU_USAGE_init(&cpu_usage,sizeof(cpu_usage));
CPU_USAGE_setParams(cpu_usageHandle,
HAL_getTimerPeriod(halHandle,1), // timer period, cnts
(uint32_t)USER_ISR_FREQ_Hz); // average over 1 second of ISRs
// setup faults
HAL_setupFaults(halHandle);
// initialize the interrupt vector table
HAL_initIntVectorTable(halHandle);
// enable the ADC interrupts
HAL_enableAdcInts(halHandle);
// enable global interrupts
HAL_enableGlobalInts(halHandle);
// enable debug interrupts
HAL_enableDebugInt(halHandle);
// disable the PWM
HAL_disablePwm(halHandle);
// compute scaling factors for flux and torque calculations
gFlux_pu_to_Wb_sf = USER_computeFlux_pu_to_Wb_sf();
gFlux_pu_to_VpHz_sf = USER_computeFlux_pu_to_VpHz_sf();
gTorque_Ls_Id_Iq_pu_to_Nm_sf = USER_computeTorque_Ls_Id_Iq_pu_to_Nm_sf();
gTorque_Flux_Iq_pu_to_Nm_sf = USER_computeTorque_Flux_Iq_pu_to_Nm_sf();
// enable the system by default
gMotorVars.Flag_enableSys = true;
#ifdef DRV8301_SPI
// turn on the DRV8301 if present
HAL_enableDrv(halHandle);
// initialize the DRV8301 interface
HAL_setupDrvSpi(halHandle,&gDrvSpi8301Vars);
#endif
#ifdef DRV8305_SPI
// turn on the DRV8305 if present
HAL_enableDrv(halHandle);
// initialize the DRV8305 interface
HAL_setupDrvSpi(halHandle,&gDrvSpi8305Vars);
#endif
// Begin the background loop
for(;;)
{
// Waiting for enable system flag to be set
while(!(gMotorVars.Flag_enableSys));
// loop while the enable system flag is true
while(gMotorVars.Flag_enableSys)
{
if(gMotorVars.Flag_Run_Identify)
{
// disable Rs recalculation
EST_setFlag_enableRsRecalc(estHandle,false);
// update estimator state
EST_updateState(estHandle,0);
#ifdef FAST_ROM_V1p6
// call this function to fix 1p6
softwareUpdate1p6(estHandle);
#endif
// enable the PWM
HAL_enablePwm(halHandle);
// set trajectory target for speed reference
TRAJ_setTargetValue(trajHandle_spd,_IQmpy(gMotorVars.SpeedRef_krpm, gSpeed_krpm_to_pu_sf));
if(USER_MOTOR_TYPE == MOTOR_Type_Pm)
{
// set trajectory target for Id reference
TRAJ_setTargetValue(trajHandle_Id,gIdq_ref_pu.value[0]);
}
else
{
if(gMotorVars.Flag_enablePowerWarp)
{
_iq Id_target_pw_pu = EST_runPowerWarp(estHandle,TRAJ_getIntValue(trajHandle_Id),gIdq_pu.value[1]);
TRAJ_setTargetValue(trajHandle_Id,Id_target_pw_pu);
TRAJ_setMinValue(trajHandle_Id,_IQ(USER_MOTOR_MAGNETIZING_CURRENT * 0.3 / USER_IQ_FULL_SCALE_CURRENT_A));
TRAJ_setMaxDelta(trajHandle_Id,_IQ(USER_MOTOR_MAGNETIZING_CURRENT * 0.3 / USER_IQ_FULL_SCALE_CURRENT_A / USER_ISR_FREQ_Hz));
}
else
{
// set trajectory target for Id reference
TRAJ_setTargetValue(trajHandle_Id,_IQ(USER_MOTOR_MAGNETIZING_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A));
TRAJ_setMinValue(trajHandle_Id,_IQ(0.0));
TRAJ_setMaxDelta(trajHandle_Id,_IQ(USER_MOTOR_MAGNETIZING_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A / USER_ISR_FREQ_Hz));
}
}
}
else if(gMotorVars.Flag_enableRsRecalc)
{
// set angle to zero
EST_setAngle_pu(estHandle,_IQ(0.0));
// enable or disable Rs recalculation
EST_setFlag_enableRsRecalc(estHandle,true);
// update estimator state
EST_updateState(estHandle,0);
#ifdef FAST_ROM_V1p6
// call this function to fix 1p6
softwareUpdate1p6(estHandle);
#endif
// enable the PWM
HAL_enablePwm(halHandle);
// set trajectory target for speed reference
TRAJ_setTargetValue(trajHandle_spd,_IQ(0.0));
// set trajectory target for Id reference
TRAJ_setTargetValue(trajHandle_Id,_IQ(USER_MOTOR_RES_EST_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A));
// if done with Rs recalculation, disable flag
if(EST_getState(estHandle) == EST_State_OnLine) gMotorVars.Flag_enableRsRecalc = false;
}
else
{
// set estimator to Idle
EST_setIdle(estHandle);
// disable the PWM
if(!gMotorVars.Flag_enableOffsetcalc) HAL_disablePwm(halHandle);
// clear the speed reference trajectory
TRAJ_setTargetValue(trajHandle_spd,_IQ(0.0));
TRAJ_setIntValue(trajHandle_spd,_IQ(0.0));
// clear the Id reference trajectory
TRAJ_setTargetValue(trajHandle_Id,_IQ(0.0));
TRAJ_setIntValue(trajHandle_Id,_IQ(0.0));
// configure trajectory Id defaults depending on motor type
if(USER_MOTOR_TYPE == MOTOR_Type_Pm)
{
TRAJ_setMinValue(trajHandle_Id,_IQ(-USER_MOTOR_MAX_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A));
TRAJ_setMaxDelta(trajHandle_Id,_IQ(USER_MOTOR_RES_EST_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A / USER_ISR_FREQ_Hz));
}
else
{
TRAJ_setMinValue(trajHandle_Id,_IQ(0.0));
TRAJ_setMaxDelta(trajHandle_Id,_IQ(USER_MOTOR_MAGNETIZING_CURRENT / USER_IQ_FULL_SCALE_CURRENT_A / USER_ISR_FREQ_Hz));
}
// clear integral outputs
PID_setUi(pidHandle[0],_IQ(0.0));
PID_setUi(pidHandle[1],_IQ(0.0));
PID_setUi(pidHandle[2],_IQ(0.0));
// clear Id and Iq references
gIdq_ref_pu.value[0] = _IQ(0.0);
gIdq_ref_pu.value[1] = _IQ(0.0);
// disable RsOnLine flags
gFlag_enableRsOnLine = false;
gFlag_updateRs = false;
// disable PowerWarp flag
gMotorVars.Flag_enablePowerWarp = false;
}
// update the global variables
updateGlobalVariables(estHandle);
// set field weakening enable flag depending on user's input
FW_setFlag_enableFw(fwHandle,gMotorVars.Flag_enableFieldWeakening);
// set the speed acceleration
TRAJ_setMaxDelta(trajHandle_spd,_IQmpy(MAX_ACCEL_KRPMPS_SF,gMotorVars.MaxAccel_krpmps));
// update CPU usage
updateCPUusage();
// enable/disable the forced angle
EST_setFlag_enableForceAngle(estHandle,gMotorVars.Flag_enableForceAngle);
// enable or disable RsOnLine
EST_setFlag_enableRsOnLine(estHandle,gFlag_enableRsOnLine);
// set slow rotating frequency for RsOnLine
EST_setRsOnLineAngleDelta_pu(estHandle,_IQmpy(gRsOnLineFreq_Hz, _IQ(1.0/USER_ISR_FREQ_Hz)));
// set current amplitude for RsOnLine
EST_setRsOnLineId_mag_pu(estHandle,_IQmpy(gRsOnLineId_mag_A, _IQ(1.0/USER_IQ_FULL_SCALE_CURRENT_A)));
// set flag that updates Rs from RsOnLine value
EST_setFlag_updateRs(estHandle,gFlag_updateRs);
// clear Id for RsOnLine if disabled
if(!gFlag_enableRsOnLine) EST_setRsOnLineId_pu(estHandle,_IQ(0.0));
#ifdef DRV8301_SPI
HAL_writeDrvData(halHandle,&gDrvSpi8301Vars);
HAL_readDrvData(halHandle,&gDrvSpi8301Vars);
#endif
#ifdef DRV8305_SPI
HAL_writeDrvData(halHandle,&gDrvSpi8305Vars);
HAL_readDrvData(halHandle,&gDrvSpi8305Vars);
#endif
VIB_COMP_setAlpha(vib_compHandle, gAlpha);
VIB_COMP_setAdvIndexDelta(vib_compHandle, gAdvIndexDelta);
VIB_COMP_setFlag_enableOutput(vib_compHandle, gFlag_enableOutput);
VIB_COMP_setFlag_enableUpdates(vib_compHandle, gFlag_enableUpdates);
if(gFlag_resetVibComp)
{
gFlag_resetVibComp = false;
VIB_COMP_reset(vib_compHandle);
}
if(gFlag_speedStatsReset)
{
gFlag_speedStatsReset = false;
gSpeed_max_pu = _IQ(0.0);
gSpeed_min_pu = _IQ(1.0);
}
} // end of while(gFlag_enableSys) loop
// disable the PWM
HAL_disablePwm(halHandle);
gMotorVars.Flag_Run_Identify = false;
} // end of for(;;) loop
} // end of main() function
//! \brief The main ISR that implements the motor control.
interrupt void mainISR(void)
{
_iq angle_pu = _IQ(0.0);
_iq speed_pu = _IQ(0.0);
_iq oneOverDcBus;
MATH_vec2 Iab_pu;
MATH_vec2 Vab_pu;
MATH_vec2 phasor;
uint32_t timer1Cnt;
// read the timer 1 value and update the CPU usage module
timer1Cnt = HAL_readTimerCnt(halHandle,1);
CPU_USAGE_updateCnts(cpu_usageHandle,timer1Cnt);
// acknowledge the ADC interrupt
HAL_acqAdcInt(halHandle,ADC_IntNumber_1);
// convert the ADC data
HAL_readAdcDataWithOffsets(halHandle,&gAdcData);
// remove offsets
gAdcData.I.value[0] = gAdcData.I.value[0] - gOffsets_I_pu.value[0];
gAdcData.I.value[1] = gAdcData.I.value[1] - gOffsets_I_pu.value[1];
gAdcData.I.value[2] = gAdcData.I.value[2] - gOffsets_I_pu.value[2];
gAdcData.V.value[0] = gAdcData.V.value[0] - gOffsets_V_pu.value[0];
gAdcData.V.value[1] = gAdcData.V.value[1] - gOffsets_V_pu.value[1];
gAdcData.V.value[2] = gAdcData.V.value[2] - gOffsets_V_pu.value[2];
// run the current reconstruction algorithm
runCurrentReconstruction();
// run Clarke transform on current
CLARKE_run(clarkeHandle_I,&gAdcData.I,&Iab_pu);
// run Clarke transform on voltage
CLARKE_run(clarkeHandle_V,&gAdcData.V,&Vab_pu);
// run a trajectory for Id reference, so the reference changes with a ramp instead of a step
TRAJ_run(trajHandle_Id);
// run the estimator
EST_run(estHandle,
&Iab_pu,
&Vab_pu,
gAdcData.dcBus,
TRAJ_getIntValue(trajHandle_spd));
// generate the motor electrical angle
angle_pu = EST_getAngle_pu(estHandle);
speed_pu = EST_getFm_pu(estHandle);
// calculate absolute electrical angle
gAbsAngle_elec_pu = getAbsElecAngle(angle_pu);
// calculate absolute mechanical angle
gAbsAngle_mech_pu = getAbsMechAngle(&gAngle_mech_poles, &gAngle_z1_pu, gAbsAngle_elec_pu);
// get Idq from estimator to avoid sin and cos
EST_getIdq_pu(estHandle,&gIdq_pu);
// run the appropriate controller
if((gMotorVars.Flag_Run_Identify) || (gMotorVars.Flag_enableRsRecalc))
{
_iq refValue;
_iq fbackValue;
_iq outMax_pu;
// when appropriate, run the PID speed controller
if((pidCntSpeed++ >= USER_NUM_CTRL_TICKS_PER_SPEED_TICK) && (!gMotorVars.Flag_enableRsRecalc))
{
// calculate Id reference squared
_iq Id_ref_squared_pu = _IQmpy(PID_getRefValue(pidHandle[1]),PID_getRefValue(pidHandle[1]));
// Take into consideration that Iq^2+Id^2 = Is^2
_iq Iq_Max_pu = _IQsqrt(gIs_Max_squared_pu - Id_ref_squared_pu);
// clear counter
pidCntSpeed = 0;
// Set new min and max for the speed controller output
PID_setMinMax(pidHandle[0], -Iq_Max_pu, Iq_Max_pu);
// run speed controller
PID_run_spd(pidHandle[0],TRAJ_getIntValue(trajHandle_spd),speed_pu,&(gIdq_ref_pu.value[1]));
if(speed_pu > gSpeed_max_pu)
{
gSpeed_max_pu = speed_pu;
}
if(speed_pu < gSpeed_min_pu)
{
gSpeed_min_pu = speed_pu;
}
}
// get the reference value from the trajectory module
refValue = TRAJ_getIntValue(trajHandle_Id) + EST_getRsOnLineId_pu(estHandle);
// get the feedback value
fbackValue = gIdq_pu.value[0];
// run the Id PID controller
PID_run(pidHandle[1],refValue,fbackValue,&(gVdq_out_pu.value[0]));
// set Iq reference to zero when doing Rs recalculation
if(gMotorVars.Flag_enableRsRecalc) gIdq_ref_pu.value[1] = _IQ(0.0);
// get the Iq reference value plus vibration compensation
refValue = gIdq_ref_pu.value[1] + VIB_COMP_run(vib_compHandle, gAbsAngle_mech_pu, gIdq_pu.value[1]);
gSpeed_fbk_out[VIB_COMP_getIndex(vib_compHandle)] = gIdq_ref_pu.value[1];
// get the feedback value
fbackValue = gIdq_pu.value[1];
// calculate Iq controller limits, and run Iq controller
_iq max_vs = _IQmpy(_IQ(USER_MAX_VS_MAG_PU),EST_getDcBus_pu(estHandle));
outMax_pu = _IQsqrt(_IQmpy(max_vs,max_vs) - _IQmpy(gVdq_out_pu.value[0],gVdq_out_pu.value[0]));
PID_setMinMax(pidHandle[2],-outMax_pu,outMax_pu);
PID_run(pidHandle[2],refValue,fbackValue,&(gVdq_out_pu.value[1]));
// compensate angle for PWM delay
angle_pu = angleDelayComp(speed_pu, angle_pu);
// compute the sin/cos phasor
phasor.value[0] = _IQcosPU(angle_pu);
phasor.value[1] = _IQsinPU(angle_pu);
// set the phasor in the inverse Park transform
IPARK_setPhasor(iparkHandle,&phasor);
// run the inverse Park module
IPARK_run(iparkHandle,&gVdq_out_pu,&Vab_pu);
// run the space Vector Generator (SVGEN) module
oneOverDcBus = EST_getOneOverDcBus_pu(estHandle);
Vab_pu.value[0] = _IQmpy(Vab_pu.value[0],oneOverDcBus);
Vab_pu.value[1] = _IQmpy(Vab_pu.value[1],oneOverDcBus);
SVGEN_run(svgenHandle,&Vab_pu,&(gPwmData.Tabc));
// run the PWM compensation and current ignore algorithm
SVGENCURRENT_compPwmData(svgencurrentHandle,&(gPwmData.Tabc),&gPwmData_prev);
gTrjCnt++;
}
else if(gMotorVars.Flag_enableOffsetcalc == true)
{
runOffsetsCalculation();
}
else
{
// disable the PWM
HAL_disablePwm(halHandle);
// Set the PWMs to 50% duty cycle
gPwmData.Tabc.value[0] = _IQ(0.0);
gPwmData.Tabc.value[1] = _IQ(0.0);
gPwmData.Tabc.value[2] = _IQ(0.0);
}
// write the PWM compare values
HAL_writePwmData(halHandle,&gPwmData);
if(gTrjCnt >= gUserParams.numCtrlTicksPerTrajTick)
{
// clear counter
gTrjCnt = 0;
// run a trajectory for speed reference, so the reference changes with a ramp instead of a step
TRAJ_run(trajHandle_spd);
}
// run function to set next trigger
if(!gMotorVars.Flag_enableRsRecalc) runSetTrigger();
// run field weakening
if(USER_MOTOR_TYPE == MOTOR_Type_Pm) runFieldWeakening();
// read the timer 1 value and update the CPU usage module
timer1Cnt = HAL_readTimerCnt(halHandle,1);
CPU_USAGE_updateCnts(cpu_usageHandle,timer1Cnt);
// run the CPU usage module
CPU_USAGE_run(cpu_usageHandle);
return;
} // end of mainISR() function
_iq angleDelayComp(const _iq fm_pu, const _iq angleUncomp_pu)
{
_iq angleDelta_pu = _IQmpy(fm_pu,_IQ(USER_IQ_FULL_SCALE_FREQ_Hz/(USER_PWM_FREQ_kHz*1000.0)));
_iq angleCompFactor = _IQ(1.0 + (float_t)USER_NUM_PWM_TICKS_PER_ISR_TICK * 0.5);
_iq angleDeltaComp_pu = _IQmpy(angleDelta_pu, angleCompFactor);
uint32_t angleMask = ((uint32_t)0xFFFFFFFF >> (32 - GLOBAL_Q));
_iq angleComp_pu;
_iq angleTmp_pu;
// increment the angle
angleTmp_pu = angleUncomp_pu + angleDeltaComp_pu;
// mask the angle for wrap around
// note: must account for the sign of the angle
angleComp_pu = _IQabs(angleTmp_pu) & angleMask;
// account for sign
if(angleTmp_pu < _IQ(0.0))
{
angleComp_pu = -angleComp_pu;
}
return(angleComp_pu);
} // end of angleDelayComp() function
void runCurrentReconstruction(void)
{
SVGENCURRENT_MeasureShunt_e measurableShuntThisCycle = SVGENCURRENT_getMode(svgencurrentHandle);
// run the current reconstruction algorithm
SVGENCURRENT_RunRegenCurrent(svgencurrentHandle, (MATH_vec3 *)(gAdcData.I.value));
gIavg.value[0] += (gAdcData.I.value[0] - gIavg.value[0])>>gIavg_shift;
gIavg.value[1] += (gAdcData.I.value[1] - gIavg.value[1])>>gIavg_shift;
gIavg.value[2] += (gAdcData.I.value[2] - gIavg.value[2])>>gIavg_shift;
if(measurableShuntThisCycle > two_phase_measurable)
{
gAdcData.I.value[0] = gIavg.value[0];
gAdcData.I.value[1] = gIavg.value[1];
gAdcData.I.value[2] = gIavg.value[2];
}
return;
} // end of runCurrentReconstruction() function
void runSetTrigger(void)
{
SVGENCURRENT_IgnoreShunt_e ignoreShuntNextCycle = SVGENCURRENT_getIgnoreShunt(svgencurrentHandle);
SVGENCURRENT_VmidShunt_e midVolShunt = SVGENCURRENT_getVmid(svgencurrentHandle);
// Set trigger point in the middle of the low side pulse
HAL_setTrigger(halHandle,ignoreShuntNextCycle,midVolShunt);
return;
} // end of runSetTrigger() function
void runFieldWeakening(void)
{
if(FW_getFlag_enableFw(fwHandle) == true)
{
FW_incCounter(fwHandle);
if(FW_getCounter(fwHandle) > FW_getNumIsrTicksPerFwTick(fwHandle))
{
_iq refValue;
_iq fbackValue;
FW_clearCounter(fwHandle);
refValue = gMotorVars.VsRef;
fbackValue =_IQmpy(gMotorVars.Vs,EST_getOneOverDcBus_pu(estHandle));
FW_run(fwHandle, refValue, fbackValue, &(gIdq_ref_pu.value[0]));
gMotorVars.IdRef_A = _IQmpy(gIdq_ref_pu.value[0], _IQ(USER_IQ_FULL_SCALE_CURRENT_A));
}
}
else
{
gIdq_ref_pu.value[0] = _IQmpy(gMotorVars.IdRef_A, _IQ(1.0/USER_IQ_FULL_SCALE_CURRENT_A));
}
return;
} // end of runFieldWeakening() function
void runOffsetsCalculation(void)
{
uint16_t cnt;
// enable the PWM
HAL_enablePwm(halHandle);
for(cnt=0;cnt<3;cnt++)
{
// Set the PWMs to 50% duty cycle
gPwmData.Tabc.value[cnt] = _IQ(0.0);
// reset offsets used
gOffsets_I_pu.value[cnt] = _IQ(0.0);
gOffsets_V_pu.value[cnt] = _IQ(0.0);
// run offset estimation
FILTER_FO_run(filterHandle[cnt],gAdcData.I.value[cnt]);
FILTER_FO_run(filterHandle[cnt+3],gAdcData.V.value[cnt]);
}
if(gOffsetCalcCount++ >= gUserParams.ctrlWaitTime[CTRL_State_OffLine])
{
gMotorVars.Flag_enableOffsetcalc = false;
gOffsetCalcCount = 0;
for(cnt=0;cnt<3;cnt++)
{
// get calculated offsets from filter
gOffsets_I_pu.value[cnt] = FILTER_FO_get_y1(filterHandle[cnt]);
gOffsets_V_pu.value[cnt] = FILTER_FO_get_y1(filterHandle[cnt+3]);
// clear filters
FILTER_FO_setInitialConditions(filterHandle[cnt],_IQ(0.0),_IQ(0.0));
FILTER_FO_setInitialConditions(filterHandle[cnt+3],_IQ(0.0),_IQ(0.0));
}
}
return;
} // end of runOffsetsCalculation() function
void softwareUpdate1p6(EST_Handle handle)
{
float_t fullScaleInductance = USER_IQ_FULL_SCALE_VOLTAGE_V/(USER_IQ_FULL_SCALE_CURRENT_A*USER_VOLTAGE_FILTER_POLE_rps);
float_t Ls_coarse_max = _IQ30toF(EST_getLs_coarse_max_pu(handle));
int_least8_t lShift = ceil(log(USER_MOTOR_Ls_d/(Ls_coarse_max*fullScaleInductance))/log(2.0));
uint_least8_t Ls_qFmt = 30 - lShift;
float_t L_max = fullScaleInductance * pow(2.0,lShift);
_iq Ls_d_pu = _IQ30(USER_MOTOR_Ls_d / L_max);
_iq Ls_q_pu = _IQ30(USER_MOTOR_Ls_q / L_max);
// store the results
EST_setLs_d_pu(handle,Ls_d_pu);
EST_setLs_q_pu(handle,Ls_q_pu);
EST_setLs_qFmt(handle,Ls_qFmt);
return;
} // end of softwareUpdate1p6() function
//! \brief Setup the Clarke transform for either 2 or 3 sensors.
//! \param[in] handle The clarke (CLARKE) handle
//! \param[in] numCurrentSensors The number of current sensors
void setupClarke_I(CLARKE_Handle handle,const uint_least8_t numCurrentSensors)
{
_iq alpha_sf,beta_sf;
// initialize the Clarke transform module for current
if(numCurrentSensors == 3)
{
alpha_sf = _IQ(MATH_ONE_OVER_THREE);
beta_sf = _IQ(MATH_ONE_OVER_SQRT_THREE);
}
else if(numCurrentSensors == 2)
{
alpha_sf = _IQ(1.0);
beta_sf = _IQ(MATH_ONE_OVER_SQRT_THREE);
}
else
{
alpha_sf = _IQ(0.0);
beta_sf = _IQ(0.0);
}
// set the parameters
CLARKE_setScaleFactors(handle,alpha_sf,beta_sf);
CLARKE_setNumSensors(handle,numCurrentSensors);
return;
} // end of setupClarke_I() function
//! \brief Setup the Clarke transform for either 2 or 3 sensors.
//! \param[in] handle The clarke (CLARKE) handle
//! \param[in] numVoltageSensors The number of voltage sensors
void setupClarke_V(CLARKE_Handle handle,const uint_least8_t numVoltageSensors)
{
_iq alpha_sf,beta_sf;
// initialize the Clarke transform module for voltage
if(numVoltageSensors == 3)
{
alpha_sf = _IQ(MATH_ONE_OVER_THREE);
beta_sf = _IQ(MATH_ONE_OVER_SQRT_THREE);
}
else
{
alpha_sf = _IQ(0.0);
beta_sf = _IQ(0.0);
}
// set the parameters
CLARKE_setScaleFactors(handle,alpha_sf,beta_sf);
CLARKE_setNumSensors(handle,numVoltageSensors);
return;
} // end of setupClarke_V() function
//! \brief Update the global variables (gMotorVars).
//! \param[in] handle The estimator (EST) handle
void updateGlobalVariables(EST_Handle handle)
{
// get the speed estimate
gMotorVars.Speed_krpm = EST_getSpeed_krpm(handle);
// get the torque estimate
{
_iq Flux_pu = EST_getFlux_pu(handle);
_iq Id_pu = PID_getFbackValue(pidHandle[1]);
_iq Iq_pu = PID_getFbackValue(pidHandle[2]);
_iq Ld_minus_Lq_pu = _IQ30toIQ(EST_getLs_d_pu(handle)-EST_getLs_q_pu(handle));
_iq Torque_Flux_Iq_Nm = _IQmpy(_IQmpy(Flux_pu,Iq_pu),gTorque_Flux_Iq_pu_to_Nm_sf);
_iq Torque_Ls_Id_Iq_Nm = _IQmpy(_IQmpy(_IQmpy(Ld_minus_Lq_pu,Id_pu),Iq_pu),gTorque_Ls_Id_Iq_pu_to_Nm_sf);
_iq Torque_Nm = Torque_Flux_Iq_Nm + Torque_Ls_Id_Iq_Nm;
gMotorVars.Torque_Nm = Torque_Nm;
}
// get the magnetizing current
gMotorVars.MagnCurr_A = EST_getIdRated(handle);
// get the rotor resistance
gMotorVars.Rr_Ohm = EST_getRr_Ohm(handle);
// get the stator resistance
gMotorVars.Rs_Ohm = EST_getRs_Ohm(handle);
// get the online stator resistance
gMotorVars.RsOnLine_Ohm = EST_getRsOnLine_Ohm(handle);
// get the stator inductance in the direct coordinate direction
gMotorVars.Lsd_H = EST_getLs_d_H(handle);
// get the stator inductance in the quadrature coordinate direction
gMotorVars.Lsq_H = EST_getLs_q_H(handle);
// get the flux in V/Hz in floating point
gMotorVars.Flux_VpHz = EST_getFlux_VpHz(handle);
// get the flux in Wb in fixed point
gMotorVars.Flux_Wb = _IQmpy(EST_getFlux_pu(handle),gFlux_pu_to_Wb_sf);
// get the estimator state
gMotorVars.EstState = EST_getState(handle);
// Get the DC buss voltage
gMotorVars.VdcBus_kV = _IQmpy(gAdcData.dcBus,_IQ(USER_IQ_FULL_SCALE_VOLTAGE_V/1000.0));
// read Vd and Vq vectors per units
gMotorVars.Vd = gVdq_out_pu.value[0];
gMotorVars.Vq = gVdq_out_pu.value[1];
// calculate vector Vs in per units
gMotorVars.Vs = _IQsqrt(_IQmpy(gMotorVars.Vd, gMotorVars.Vd) + _IQmpy(gMotorVars.Vq, gMotorVars.Vq));
// read Id and Iq vectors in amps
gMotorVars.Id_A = _IQmpy(gIdq_pu.value[0], _IQ(USER_IQ_FULL_SCALE_CURRENT_A));
gMotorVars.Iq_A = _IQmpy(gIdq_pu.value[1], _IQ(USER_IQ_FULL_SCALE_CURRENT_A));
// calculate vector Is in amps
gMotorVars.Is_A = _IQsqrt(_IQmpy(gMotorVars.Id_A, gMotorVars.Id_A) + _IQmpy(gMotorVars.Iq_A, gMotorVars.Iq_A));
// calculate maximum speed variation
gSpeed_delta_krpm = _IQmpy(gSpeed_max_pu - gSpeed_min_pu, _IQ(USER_IQ_FULL_SCALE_FREQ_Hz * 60.0 / (float_t)USER_MOTOR_NUM_POLE_PAIRS / 1000.0));
return;
} // end of updateGlobalVariables() function
void updateCPUusage(void)
{
uint32_t minDeltaCntObserved = CPU_USAGE_getMinDeltaCntObserved(cpu_usageHandle);
uint32_t avgDeltaCntObserved = CPU_USAGE_getAvgDeltaCntObserved(cpu_usageHandle);
uint32_t maxDeltaCntObserved = CPU_USAGE_getMaxDeltaCntObserved(cpu_usageHandle);
uint16_t pwmPeriod = HAL_readPwmPeriod(halHandle,PWM_Number_1);
float_t cpu_usage_den = (float_t)pwmPeriod * (float_t)USER_NUM_PWM_TICKS_PER_ISR_TICK * 2.0;
// calculate the minimum cpu usage percentage
gCpuUsagePercentageMin = (float_t)minDeltaCntObserved / cpu_usage_den * 100.0;
// calculate the average cpu usage percentage
gCpuUsagePercentageAvg = (float_t)avgDeltaCntObserved / cpu_usage_den * 100.0;
// calculate the maximum cpu usage percentage
gCpuUsagePercentageMax = (float_t)maxDeltaCntObserved / cpu_usage_den * 100.0;
return;
} // end of updateCPUusage() function
//! \brief Calculates the absolute electrical angle
//! \param[in] angle_pu The electrical angle from _IQ(0.0) to _IQ(1.0) when running CW and from _IQ(-1.0) to _IQ(0.0) when running CCW
//! \return The electrical angle from _IQ(0.0) to _IQ(1.0) regardless of direction of rotation (CW or CCW)
_iq getAbsElecAngle(const _iq angle_pu)
{
_iq angle_abs_pu;;
// make angle possitive only
if(angle_pu < _IQ(0.0))
{
angle_abs_pu = angle_pu + _IQ(1.0);
}
else
{
angle_abs_pu = angle_pu;
}
return(angle_abs_pu);
} // end of getAbsElecAngle() function
//! \brief Calculates mechanical angle from electrical angle
//! \param[in] pAngle_mech_poles The mechanical angle from _IQ(-USER_MOTOR_NUM_POLE_PAIRS) to _IQ(USER_MOTOR_NUM_POLE_PAIRS)
//! \param[in] angle_pu The electrical angle from _IQ(0.0) to _IQ(1.0)
//! \return The mechanical angle from _IQ(0.0) to _IQ(1.0)
_iq getAbsMechAngle(_iq *pAngle_mech_poles, _iq *pAngle_z1_pu, const _iq angle_pu)
{
_iq angle_elec_delta_pu = _IQ(0.0); // electrical angle delta, angle*z^0 - angle*z^-1
_iq tmp_mech_pu = _IQ(0.0); // temporary value for intermediate calculations
_iq angle_mech_out = _IQ(0.0); // temporary mechanical angle used to store the value to be returned by the function
// calculate angle delta
angle_elec_delta_pu = angle_pu - *pAngle_z1_pu;
// calculate new mechanical angle
tmp_mech_pu = *pAngle_mech_poles + angle_elec_delta_pu;
// take care of delta calculations when electrical angle wraps around from _IQ(1.0) to _IQ(0.0) or from _IQ(0.0) to _IQ(1.0)
if(angle_elec_delta_pu < _IQ(-0.5))
{
tmp_mech_pu = tmp_mech_pu + _IQ(1.0);
}
else if(angle_elec_delta_pu > _IQ(0.5))
{
tmp_mech_pu = tmp_mech_pu - _IQ(1.0);
}
// take care of wrap around of the mechanical angle, so that angle_mech_poles stays within _IQ(-USER_MOTOR_NUM_POLE_PAIRS) to _IQ(USER_MOTOR_NUM_POLE_PAIRS)
if(tmp_mech_pu >= _IQ(USER_MOTOR_NUM_POLE_PAIRS))
{
tmp_mech_pu = tmp_mech_pu - _IQ(USER_MOTOR_NUM_POLE_PAIRS);
}
else if(tmp_mech_pu <= _IQ(-USER_MOTOR_NUM_POLE_PAIRS))
{
tmp_mech_pu = tmp_mech_pu + _IQ(USER_MOTOR_NUM_POLE_PAIRS);
}
// store value in angle_mech_poles
*pAngle_mech_poles = tmp_mech_pu;
// scale the mechanical angle so that final output is from _IQ(-1.0) to _IQ(1.0)
tmp_mech_pu = _IQmpy(tmp_mech_pu, _IQ(1.0/USER_MOTOR_NUM_POLE_PAIRS));
// make the final mechanical angle a positive only values from _IQ(0.0) to _IQ(1.0)
if(tmp_mech_pu < _IQ(0.0))
{
angle_mech_out = tmp_mech_pu + _IQ(1.0);
}
else
{
angle_mech_out = tmp_mech_pu;
}
// store the angle so next time this function is called we have the angle from the previous sample
*pAngle_z1_pu = angle_pu;
// returned the calculated mechanical angle from _IQ(0.0) to _IQ(1.0)
return(angle_mech_out);
} // end of getAbsMechAngle() function
//@} //defgroup
// end of file
| 35.526518 | 167 | 0.699567 | [
"object",
"vector",
"transform"
] |
3ec9280ca66ef4f4eb030e904a4474ab64714005 | 3,326 | h | C | src/starkware/commitment_scheme/merkle/merkle.h | ChihChengLiang/ethSTARK | 032eda9f83d419eb2eaeef79d446fb77ecc3f019 | [
"Apache-2.0"
] | 123 | 2020-06-28T18:35:32.000Z | 2022-03-15T08:48:28.000Z | src/starkware/commitment_scheme/merkle/merkle.h | ChihChengLiang/ethSTARK | 032eda9f83d419eb2eaeef79d446fb77ecc3f019 | [
"Apache-2.0"
] | 3 | 2020-06-29T16:45:26.000Z | 2020-08-09T08:42:17.000Z | src/starkware/commitment_scheme/merkle/merkle.h | ChihChengLiang/ethSTARK | 032eda9f83d419eb2eaeef79d446fb77ecc3f019 | [
"Apache-2.0"
] | 21 | 2020-06-29T17:00:47.000Z | 2022-03-08T22:10:15.000Z | #ifndef STARKWARE_COMMITMENT_SCHEME_MERKLE_MERKLE_H_
#define STARKWARE_COMMITMENT_SCHEME_MERKLE_MERKLE_H_
#include <array>
#include <cassert>
#include <cstring>
#include <map>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "glog/logging.h"
#include "third_party/gsl/gsl-lite.hpp"
#include "starkware/channel/prover_channel.h"
#include "starkware/channel/verifier_channel.h"
namespace starkware {
/*
Merkle Tree.
*/
class MerkleTree {
public:
explicit MerkleTree(uint64_t data_length) : data_length_(data_length), nodes_(2 * data_length) {
ASSERT_RELEASE(IsPowerOfTwo(data_length), "Data length is not a power of 2.");
VLOG(3) << "Constructing a Merkle tree for data length = " << data_length;
// We use an array that has one extra cell we never use at the beginning, to make indexing
// nicer.
}
/*
Adds data to the tree. The start_index argument is used so that data may be fed
into the tree in any order, and by different threads.
start_index + data.size() has to be smaller than the data length declared at construction.
*/
void AddData(gsl::span<const Blake2s160> data, uint64_t start_index);
/*
Retrieves the root of the tree.
This entails computing the inner-nodes' hashes, however, some of the inner nodes' hashes may
already be known, in which case it will be more efficient to start the computation at the
minimal depth (depth = distance from the root) where at least one node is unknown. The minimal
depth assumed to be completely correct is specified by min_depth_assumed_correct argument.
For example, in a tree with 16 leaves, if the immediate parents of all the leaves were already
computed because they were entered in pairs, using AddData(), the most efficient way to
compute the root will be calling GetRoot(3). This is because depth 4 nodes are simply the leaves
- which were explicitly fed into the tree, and we assume depth-3 nodes were computed implicitly,
since the leaves were fed in pairs. Similarly, calling GetRoot(0) causes no hash operations to
be performed, and simply returns the root stored from the last time it was computed.
*/
Blake2s160 GetRoot(size_t min_depth_assumed_correct);
/*
Generates and sends to the channel minimal consistency proof between the Merkle tree root
and the values in the queried indices.
The proof does not include the values of those indices, nor the Merkle root.
*/
void GenerateDecommitment(const std::set<uint64_t>& queries, ProverChannel* channel) const;
/*
Given a Merkle root, and claimed values of a subset of its leaves (data_to_verify),
reads and verifies a proof of consistency from the channel (generated by an invocation of
GenerateDecommitment()). 'total_data_length' is the total number of leaves in the Merkle tree.
*/
static bool VerifyDecommitment(
const std::map<uint64_t, Blake2s160>& data_to_verify, uint64_t total_data_length,
const Blake2s160& merkle_root, VerifierChannel* channel);
uint64_t GetDataLength() const;
private:
const uint64_t data_length_;
std::vector<Blake2s160> nodes_;
void SendDecommitmentNode(uint64_t node_index, ProverChannel* channel) const;
};
} // namespace starkware
#endif // STARKWARE_COMMITMENT_SCHEME_MERKLE_MERKLE_H_
| 39.595238 | 100 | 0.75466 | [
"vector"
] |
3ec98319ffcb0d6c42fbee6d4b16c2ef6065dd90 | 16,036 | h | C | mdschism/avtMDSCHISMFileFormatImpl.h | schism-dev/schism_visit_plugin | 51c4b8c840d401b98ad6094c91ca2e7b9e01b513 | [
"Apache-2.0"
] | 1 | 2021-09-05T17:10:02.000Z | 2021-09-05T17:10:02.000Z | mdschism/avtMDSCHISMFileFormatImpl.h | schism-dev/schism_visit_plugin | 51c4b8c840d401b98ad6094c91ca2e7b9e01b513 | [
"Apache-2.0"
] | 1 | 2021-08-03T03:38:48.000Z | 2021-08-03T03:38:48.000Z | mdschism/avtMDSCHISMFileFormatImpl.h | schism-dev/schism_visit_plugin | 51c4b8c840d401b98ad6094c91ca2e7b9e01b513 | [
"Apache-2.0"
] | null | null | null | #ifndef AVTMDSCHISMFILEFORMATIMPL_H
#define AVTMDSCHISMFILEFORMATIMPL_H
#include <vector>
#include <map>
#include <vtkUnstructuredGrid.h>
// has to put mpi.h before any netcdf.h include to avoid redefining of mpi_comm,... such as.
#ifdef PARALLEL
#include <mpi.h>
#endif
//#include "SCHISMFile10.h"
#include "MDSCHISMOutput.h"
#include "MeshProvider10.h"
#include "MDSCHISMMeshProvider.h"
#include "FileFormatFavorInterface.h"
class avtMDSCHISMFileFormatImpl : public FileFormatFavorInterface
{
public:
avtMDSCHISMFileFormatImpl();
virtual ~avtMDSCHISMFileFormatImpl();
static FileFormatFavorInterface * create();
//
// This is used to return unconvention data -- ranging from material
// information to information about block connectivity.
//
// virtual void *GetAuxiliaryData(const char *var, int timestep,
// const char *type, void *args,
// DestructorFunction &);
//
//
// If you know the times and cycle numbers, overload this function.
// Otherwise, VisIt will make up some reasonable ones for you.
//
// virtual void GetCycles(std::vector<int> &);
void GetTimes(std::vector<double> & a_times);
int GetNTimesteps(const std::string& a_filename);
//void ActivateTimestep(const std::string& a_filename);
const char *GetType(void) { return "MDUGrid"; };
void FreeUpResources(void);
vtkDataSet *GetMesh(int a_timeState,
int a_domainID,
avtMDSCHISMFileFormat * a_avtFile,
const char * a_meshName);
vtkDataArray *GetVar(int a_timeState,
int a_domainID,
const char * a_varName);
vtkDataArray *GetVectorVar(int a_timeState,
int a_domainID,
const char * a_varName);
void PopulateDatabaseMetaData(avtDatabaseMetaData * a_metaData,
const std::string a_datafile,
int a_timeState);
void BroadcastGlobalInfo(avtDatabaseMetaData *metadata);
//both return just first data file and mesh provider
MDSchismOutput * get_a_data_file();
MDSCHISMMeshProvider * get_a_mesh_provider();
int num_domain();
bool SCHISMVarIs3D(SCHISMVar10* a_varPtr) const;
bool SCHISMVarIsVector(SCHISMVar10* a_varPtr) const;
void set_var_name_label_map(const std::map<std::string, std::string> a_map);
void set_var_mesh_map(const std::map<std::string, std::string> a_map);
void set_var_horizontal_center_map(const std::map<std::string, std::string> a_map);
void set_var_vertical_center_map(const std::map<std::string, std::string> a_map);
protected:
void Initialize(std::string a_data_file);
//private:
void PopulateStateMetaData(avtDatabaseMetaData * a_metaData,
int a_timeState);
void addFaceCenterData(avtDatabaseMetaData * a_metaData,
SCHISMVar10 * a_varPtr,
const std::string & a_varName,
const std::string & a_varLabel,
const avtCentering & a_center);
void addNodeCenterData(avtDatabaseMetaData * a_metaData,
SCHISMVar10 * a_varPtr,
const std::string & a_varName,
const std::string & a_varLabel,
const avtCentering & a_center);
void addSideCenterData(avtDatabaseMetaData * a_metaData,
SCHISMVar10 * a_varPtr,
const std::string & a_varName,
const std::string & a_varLabel,
const avtCentering & a_center);
void create2DUnstructuredMesh( vtkUnstructuredGrid *a_uGrid,
long *a_meshEle,
const int &a_domainID,
const int &a_timeState);
void create2DUnstructuredMeshNoDryWet( vtkUnstructuredGrid *a_uGrid,
long *a_meshEle,
const int &a_domainID,
const int &a_timeState);
void create3DUnstructuredMesh(vtkUnstructuredGrid *a_uGrid,
long *a_meshEle,
long *a_2DPointto3DPoints,
const int &a_domainID,
const int &a_timeState);
void createLayerMesh(vtkUnstructuredGrid *a_uGrid,
long *a_meshEle,
long *a_2DPointto3DPoints,
const int &a_domainID,
const int &a_timeState);
void create2DPointMesh( vtkUnstructuredGrid *a_uGrid,
long *a_meshEle,
const int &a_domainID,
const int &a_timeState);
void create3DPointMesh( vtkUnstructuredGrid *a_uGrid,
long *a_meshEle,
const int &a_domainID,
const int &a_timeState);
void create3DPointFaceMesh( vtkUnstructuredGrid *a_uGrid,
long *a_meshEle,
const int &a_domainID,
const int &a_timeState);
vtkDataArray* getLayer(const int& a_domain);
vtkDataArray* getLevel(const string& a_level_name,const int& a_domain);
vtkDataArray* getBottom(const string& a_bottom_name,const int& a_domain);
void PopulateVarMap();
void getTime();
void getMeshDimensions(const int& a_dominID, MeshProvider10 * a_meshProviderPtr);
//void loadMeshCoordinates(MeshProvider10 * a_meshProviderPtr);
void updateMeshZCoordinates(vtkPoints * a_pointSet,
const int a_timeState,
const int a_domainID,
const char * a_meshName);
// void retrieve1DArray(float * a_valBuff,
// SCHISMFile10 * a_selfeFilePtr,
// const std::string & a_varToken,
// const int & a_numVar) const;
//void retrieve1DArray(int * a_valBuff,
//SCHISMFile10 * a_selfeFilePtr,
//const std::string & a_varToken,
//const int & a_numVar) const;
void loadAndCacheZ(const int& a_timeState,float * a_cache);
void loadAndCacheZSide(const int& a_timeState,float * a_cache);
void loadAndCacheZEle(const int& a_timeState,float * a_cache);
void getSingleLayerVar(float * a_valBuff,
SCHISMFile10* a_selfeOutPtr,
const int& a_timeState,
const std::string& a_varname) const;
void depthAverage(float * a_averageState,
float * a_layeredState,
long * a_nodeDataStart,
const int & a_timeState,
const int & a_domain,
const std::string & a_horizontal_center,
const std::string & a_vertical_center
) ;
void vectorDepthAverage(float * a_averageState,
float * a_layeredState,
long * a_nodeDataStart,
const int & a_timeState,
const int & a_domain,
const int & a_ncomps,
const std::string & a_horizontal_center,
const std::string & a_vertical_center
) ;
void validTopBottomNode(int & a_validTopNodeNum,
int & a_validBottomNodeNum,
long * a_validTopNode,
long * a_validBottomNode,
const int & a_layerID,
long* a_faceNodePtr,
int * a_kbp_node) const;
void insertTriangle3DCell(vtkUnstructuredGrid * a_uGrid,
const int & a_validTopNodeNum,
const int & a_validBottomNodeNum,
long * a_validTopNode,
long * a_validBottomNode,
long * a_faceNodePtr,
long * a_2DPointto3DPoints,
int * a_kbp_node,
const long & a_Cell,
const int & a_layerID,
const int & a_numLayers);
void insertQuad3DCell(vtkUnstructuredGrid * a_uGrid,
const int & a_validTopNodeNum,
const int & a_validBottomNodeNum,
long * a_validTopNode,
long * a_validBottomNode,
long * a_faceNodePtr,
long * a_2DPointto3DPoints,
int * a_kbp_node,
const long & a_Cell,
const int & a_layerID,
const int & a_numLayers);
bool fourPointsCoplanar(double p1[3],
double p2[3],
double p3[3],
double p4[3]);
void prepare_average(int * & a_kbp,
int * & a_mapper,
float * & a_zPtr,
const int & a_timeState,
const int & a_domainID,
const std::string & a_horizontal_center,
const std::string & a_vertical_center);
void load_node_dry_wet(const int & a_time,const int & a_domain);
void load_side_dry_wet(const int & a_time,const int & a_domain);
void load_ele_dry_wet(const int & a_time,const int & a_domain);
void load_bottom(const int & a_time,const int & a_domainID);
//broadcast string map from rank 0 to all other ranks
void broadCastStringMap(std::map<std::string, std::string>& m_map,int myrank);
int load_per_proc_file(const std::string& a_path,int & num_node,int & num_side,int & num_ele) const;
void count_node_side_num_domain(const std::string& a_path, const int& num_proc);
vtkDataArray* get_ele_global_id(const int& a_domain);
vtkDataArray* get_node_global_id(const int& a_domain);
vtkDataArray* get_node_depth(const int& a_domain);
private:
bool m_initialized;
bool m_mesh_is_static;
std::string m_data_file;
// path where m_data_file is under
std::string m_data_file_path;
std::string m_plugin_name;
std::map<int,MDSchismOutput*> m_data_files;
// element centered data use mesh from other file
std::map<int,MDSCHISMMeshProvider*> m_external_mesh_providers;
std::vector<int> m_domain_list;
// a number of token of saved vars and attributes
std::string m_data_description;
std::string m_mesh_var;
std::string m_var_label_att;
std::string m_var_location_att;
// name for meshes
std::string m_mesh_3d;
std::string m_layer_mesh;
std::string m_mesh_2d;
std::string m_mesh_2d_no_wet_dry;
std::string m_side_center_point_3d_mesh;
std::string m_side_center_point_2d_mesh;
// vertical side-faces center points, 3d flux data uses it
std::string m_face_center_point_3d_mesh;
// dimension size of single layer of 2D Mesh
std::map<int,long> m_num_mesh_nodes;
std::map<int,long> m_num_mesh_edges;
std::map<int,long> m_num_mesh_faces;
std::map<int,long> m_total_valid_3D_point;
std::map<int,long> m_total_valid_3D_side;
std::map<int,long> m_total_valid_3D_ele;
std::map<int, std::map<long, int>> m_3d_node_to_2d_node;
// number of time step
std::string m_dim_time;
long m_num_time_step;
float * m_time_ptr;
std::string m_time;
//coordinates and depth
std::string m_node_depth;
std::string m_node_depth_label;
std::string m_node_surface;
std::string m_node_surface_label;
std::string m_layerSCoord;
std::string m_dim_layers;
std::string m_dim_var_component;
// this is number of level in schsim
int m_num_layers;
float * m_node_x_ptr;
float * m_node_y_ptr;
float * m_node_z_ptr;
// this is kbp read from mesh provider, always node center
//int * m_kbp00;
std::map<int,int *> m_kbp_node;
std::map<int,int > m_kbp_node_time;
bool m_kbp_node_filled;
std::map<int,int *> m_kbp_ele;
std::map<int,int > m_kbp_ele_time;
std::map<int, int*> m_kbp_prism;
std::map<int, int> m_kbp_prism_time;
bool m_kbp_ele_filled;
std::map<int,int *> m_kbp_side;
std::map<int,int> m_kbp_side_time;
bool m_kbp_side_filled;
int m_cache_kbp_id;
// this is the kbp read from data file itself
// it is different from m_kbp00 for element/prism centered data
int * m_kbp_data;
int m_dry_wet_flag; // 0: dry cell/ele/side filled with last wetting val, 1: junk
std::map<int,int*> m_node_dry_wet;
std::map<int,int*> m_ele_dry_wet;
std::map<int,int*> m_side_dry_wet;
std::map<int,int> m_node_dry_wet_cached_time;
std::map<int,int> m_side_dry_wet_cached_time;
std::map<int,int> m_ele_dry_wet_cached_time;
int m_number_domain;
std::string m_surface_state_suffix;
std::string m_bottom_state_suffix;
std::string m_depth_average_suffix;
//map convert netcdf centering into avt centering
std::map<std::string, avtCentering> m_center_map;
//map convert var label into netcdf varname token
std::map<std::string, std::string> m_var_name_label_map;
//map convert var label into netcdf varname token
std::map<std::string, std::string> m_var_vertical_center_map;
//map convert var label into netcdf varname token
std::map<std::string, std::string> m_var_horizontal_center_map;
// maping var label to its mesh name
std::map<std::string,std::string> m_var_mesh_map;
// caching SCHISM var (not visit labeled var) dim 3D/2D only
std::map<std::string,int> m_var_dim;
// norminal num data per layer for different centering, node,side,element
std::map<std::string,int> m_nominal_size_per_layer;
// dry state
float m_dry_surface;
std::string m_data_center;
//half or full level, only meaningfull for 3d data
std::string m_level_center;
int m_rank;
//debug var del after done
int m_tri_wedge;
int m_tri_pyramid;
int m_tri_tetra;
int m_quad_hexhedron;
int m_quad_wedge;
int m_quad_pyramid;
//store num of domain a side/node resides to figure out inter-facial node/side and mark them as ghost
std::vector<int> m_side_num_domain;
std::vector<int> m_node_num_domain;
int m_global_num_node;
int m_global_num_side;
int m_global_num_ele;
};
#endif
| 38.828087 | 113 | 0.554877 | [
"mesh",
"vector",
"3d"
] |
3ed46a52d32c9a6e5f6a4a7c0e2f12d3a05401dc | 25,246 | h | C | ThirdParty/LaunchDarkly/include/ldapi.h | Mohawk-Valley-Interactive/launchdarkly-client-ue4-plugin | 183f856266e97537c3af9f519dd61b0a1cdc7c73 | [
"Apache-2.0"
] | 1 | 2021-02-05T22:57:39.000Z | 2021-02-05T22:57:39.000Z | ThirdParty/LaunchDarkly/include/ldapi.h | Mohawk-Valley-Interactive/launchdarkly-client-ue4-plugin | 183f856266e97537c3af9f519dd61b0a1cdc7c73 | [
"Apache-2.0"
] | null | null | null | ThirdParty/LaunchDarkly/include/ldapi.h | Mohawk-Valley-Interactive/launchdarkly-client-ue4-plugin | 183f856266e97537c3af9f519dd61b0a1cdc7c73 | [
"Apache-2.0"
] | 1 | 2020-04-16T17:33:33.000Z | 2020-04-16T17:33:33.000Z | /*!
* @file ldapi.h
* @brief Public API. Include this for every public operation.
*/
#ifndef C_CLIENT_LDIAPI_H
#define C_CLIENT_LDIAPI_H
/** @brief The current SDK version string. This value adheres to semantic
* versioning and is included in the HTTP user agent sent to LaunchDarkly. */
#define LD_SDK_VERSION "1.7.4"
/** @brief Used to ensure only intended symbols are exported in the binaries */
#ifdef DOXYGEN_SHOULD_SKIP_THIS
#define LD_EXPORT(x) x
#else
#ifdef _WIN32
#define LD_EXPORT(x) __declspec(dllexport) x
#else
#define LD_EXPORT(x) __attribute__((visibility("default"))) x
#endif
#endif
#ifdef __cplusplus
#include <string>
extern "C" {
#endif
#include <stdbool.h>
#include "uthash.h"
/** @brief The name of the primary environment for use with
* `LDClientGetForMobileKey` */
#define LDPrimaryEnvironmentName "default"
/** @brief The log levels compatible with the logging interface */
enum ld_log_level {
LD_LOG_FATAL = 0,
LD_LOG_CRITICAL,
LD_LOG_ERROR,
LD_LOG_WARNING,
LD_LOG_INFO,
LD_LOG_DEBUG,
LD_LOG_TRACE
};
/** @brief Current status of the client */
typedef enum {
LDStatusInitializing = 0,
LDStatusInitialized,
LDStatusFailed,
LDStatusShuttingdown,
LDStatusShutdown
} LDStatus;
/** @brief JSON equivalent types used by `LDNode`. */
typedef enum {
LDNodeNone = 0,
LDNodeString,
LDNodeNumber,
LDNodeBool,
LDNodeHash,
LDNodeArray,
} LDNodeType;
/** @brief A Node node will have a type, one of string, number, bool, hash,
* or array. The corresponding union field, s, n, b, h, or a will be set. */
typedef struct LDNode_i {
union {
/** @brief Key when object. */
char *key;
/** @brief Key when array. */
unsigned int idx;
};
/** @brief Node type. */
LDNodeType type;
/** @brief Node value. */
union {
bool b;
char *s;
double n;
struct LDNode_i *h;
struct LDNode_i *a;
};
/** @brief Hash handle used for hash tables. */
UT_hash_handle hh;
/** @brief Internal version tracking. */
int version;
/** @brief Internal variation tracking. */
int variation;
/** @brief Internal version tracking. */
int flagversion;
/** @brief Internal track timing. */
double track;
/** @brief Internal evaluation reason. */
struct LDNode_i* reason;
#ifdef __cplusplus
struct LDNode_i *lookup(const std::string &key);
struct LDNode_i *index(unsigned int idx);
#endif
} LDNode;
/** @brief To use detail variations you must provide a pointer to an
* `LDVariationDetails` struct that will be filled by the evaluation function.
*
* The contents of `LDVariationDetails` must be freed with
* `LDFreeDetailContents` when they are no longer needed. */
typedef struct {
int variationIndex;
struct LDNode_i* reason;
} LDVariationDetails;
/** @brief Opaque configuration object */
typedef struct LDConfig_i LDConfig;
/** @brief Opaque user object **/
typedef struct LDUser_i LDUser;
/** @brief Opaque client object **/
struct LDClient_i;
/** @brief Creates a new default configuration. `mobileKey` is required.
*
* The configuration object is intended to be modified until it is passed to
* `LDClientInit`, at which point it should no longer be modified. */
LD_EXPORT(LDConfig *) LDConfigNew(const char *const mobileKey);
/** @brief Marks all user attributes private. */
LD_EXPORT(void) LDConfigSetAllAttributesPrivate(LDConfig *const config,
const bool allprivate);
/** @brief Sets the interval in milliseconds between polls for flag updates
* when your app is in the background. */
LD_EXPORT(void) LDConfigSetBackgroundPollingIntervalMillis(
LDConfig *const config, const int millis);
/** @brief Sets the interval in milliseconds between polls for flag updates
* when your app is in the background. */
LD_EXPORT(void) LDConfigSetAppURI(LDConfig *const config,
const char *const uri);
/** @brief Sets the timeout in milliseconds when connecting to LaunchDarkly. */
LD_EXPORT(void) LDConfigSetConnectionTimeoutMillies(LDConfig *const config,
const int millis);
/** @brief Enable or disable background updating */
LD_EXPORT(void) LDConfigSetDisableBackgroundUpdating(LDConfig *const config,
const bool disable);
/** @brief Sets the max number of events to queue before sending them to
* LaunchDarkly. */
LD_EXPORT(void) LDConfigSetEventsCapacity(LDConfig *const config,
const int capacity);
/** @brief Sets the maximum amount of time in milliseconds to wait in between
* sending analytics events to LaunchDarkly. */
LD_EXPORT(void) LDConfigSetEventsFlushIntervalMillis(LDConfig *const config,
const int millis);
/** @brief Set the events uri for sending analytics to LaunchDarkly. You
* probably don't need to set this unless instructed by LaunchDarkly. */
LD_EXPORT(void) LDConfigSetEventsURI(LDConfig *const config,
const char *const uri);
/** @brief Sets the key for authenticating with LaunchDarkly. This is required
* unless you're using the client in offline mode. */
LD_EXPORT(void) LDConfigSetMobileKey(LDConfig *const config,
const char *const key);
/** @brief Configures the client for offline mode. In offline mode, no
* external network connections are made. */
LD_EXPORT(void) LDConfigSetOffline(LDConfig *const config, const bool offline);
/** @brief Enables or disables real-time streaming flag updates.
*
* Default: `true`. When set to `false`, an efficient caching polling
* mechanism is used. We do not recommend disabling `streaming` unless you
* have been instructed to do so by LaunchDarkly support. */
LD_EXPORT(void) LDConfigSetStreaming(LDConfig *const config,
const bool streaming);
/** @brief Only relevant when `streaming` is disabled (set to `false`). Sets
* the interval between feature flag updates. */
LD_EXPORT(void) LDConfigSetPollingIntervalMillis(LDConfig *const config,
const int millis);
/** @brief Set the stream uri for connecting to the flag update stream. You
* probably don't need to set this unless instructed by LaunchDarkly. */
LD_EXPORT(void) LDConfigSetStreamURI(LDConfig *const config,
const char *const uri);
/** @brief Set the proxy server used for connecting to LaunchDarkly.
*
* By default no proxy is used. The URI string should be of the form
* `socks5://127.0.0.1:9050`. You may read more about how this SDK handles
* proxy servers by reading the [libcurl](https://curl.haxx.se) documentation
* on the subject [here](https://ec.haxx.se/libcurl-proxies.html). */
LD_EXPORT(void) LDConfigSetProxyURI(LDConfig *const config,
const char *const uri);
/** @brief Set whether to verify the authenticity of the peer's certificate on
* network requests.
*
* By default peer verification is enabled. You may read more about what this
* means by reading the [libcurl](https://curl.haxx.se) documentation on the
* subject [here](https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html).
*/
LD_EXPORT(void) LDConfigSetVerifyPeer(LDConfig *const config,
const bool enabled);
/** @brief Determines whether the `REPORT` or `GET` verb is used for calls to
* LaunchDarkly. Do not use unless advised by LaunchDarkly. */
LD_EXPORT(void) LDConfigSetUseReport(LDConfig *const config, const bool report);
/** @brief Decide whether the client should fetch feature flag evaluation
* explanations from LaunchDarkly. */
LD_EXPORT(void) LDConfigSetUseEvaluationReasons(LDConfig *const config,
const bool reasons);
/** @brief Add a user attribute name to the private list which will not be
* recorded for all users. */
LD_EXPORT(void) LDConfigAddPrivateAttribute(LDConfig *const config,
const char *const name);
/** @brief Add another mobile key to the list of secondary environments.
*
* Both `name`, and `key` must be unique. You may not add the existing primary
* environment (the one you used to initialize `LDConfig`). The `name` of the
* key can later be used in conjunction with `LDClientGetForMobileKey`. This
* function returns false on failure. */
LD_EXPORT(bool) LDConfigAddSecondaryMobileKey(LDConfig *const config,
const char *const name, const char *const key);
/** @brief Set the path to the SSL certificate bundle used for peer
* authentication.
*
* This API is ineffective if LDConfigSetVerifyPeer is set to false. See
* [CURLOPT_CAINFO](https://curl.haxx.se/libcurl/c/CURLOPT_CAINFO.html) for
* more information. */
LD_EXPORT(void) LDConfigSetSSLCertificateAuthority(LDConfig *config,
const char *certFile);
/** @brief Free an existing `LDConfig` instance.
*
* You will likely never use this routine as ownership is transferred to
* `LDClient` on initialization. */
LD_EXPORT(void) LDConfigFree(LDConfig *const config);
/** @brief Get a reference to the (single, global) client. */
LD_EXPORT(struct LDClient_i *) LDClientGet();
/** @brief Get a reference to a secondary environment established in the
* configuration.
*
* If the environment name does not exist this function
* returns `NULL`. */
LD_EXPORT(struct LDClient_i *) LDClientGetForMobileKey(
const char *const keyName);
/** @brief Initialize the client with the config and user.
* After this call,
*
* the `config` and `user` must not be modified. The parameter `maxwaitmilli`
* indicates the maximum amount of time the client will wait to be fully
* initialized. If the timeout is hit the client will be available for
* feature flag evaluation but the results will be fallbacks. The client
* will continue attempting to connect to LaunchDarkly in the background.
* If `maxwaitmilli` is set to `0` then `LDClientInit` will wait indefinitely.
*
* Only a single initialized client from `LDClientInit` may exist at one time.
* To initialize another instance you must first cleanup the previous client
* with `LDClientClose`. Should you initialize with `LDClientInit` while
* another client exists `abort` will be called. Both `LDClientInit`, and
* `LDClientClose` are not thread safe. */
LD_EXPORT(struct LDClient_i *) LDClientInit(LDConfig *const config,
LDUser *const user, const unsigned int maxwaitmilli);
/** @brief Allocate a new user.
*
* The user may be modified *until* it is passed
* to the `LDClientIdentify` or `LDClientInit`. The `key` argument is not
* required. When `key` is `NULL` then a device specific ID is used. If a
* device specific ID cannot be obtained then a random fallback is generated. */
LD_EXPORT(LDUser *) LDUserNew(const char *const key);
/** @brief Free a user object */
LD_EXPORT(void) LDUserFree(LDUser *const user);
/** @brief Mark the user as anonymous. */
LD_EXPORT(void) LDUserSetAnonymous(LDUser *const user, const bool anon);
/** @brief Set the user's IP. */
LD_EXPORT(void) LDUserSetIP(LDUser *const user, const char *const str);
/** @brief Set the user's first name. */
LD_EXPORT(void) LDUserSetFirstName(LDUser *const user, const char *const str);
/** @brief Set the user's last name. */
LD_EXPORT(void) LDUserSetLastName(LDUser *const user, const char *const str);
/** @brief Set the user's email. */
LD_EXPORT(void) LDUserSetEmail(LDUser *const user, const char *const str);
/** @brief Set the user's name. */
LD_EXPORT(void) LDUserSetName(LDUser *const user, const char *const str);
/** @brief Set the user's avatar. */
LD_EXPORT(void) LDUserSetAvatar(LDUser *const user, const char *const str);
/** @brief Set the user's secondary key. */
LD_EXPORT(void) LDUserSetSecondary(LDUser *const user, const char *const str);
/** @brief Set custom attributes from JSON object string */
LD_EXPORT(bool) LDUserSetCustomAttributesJSON(LDUser *const user,
const char *const jstring);
/** @brief Set custom attributes with `LDNode` */
LD_EXPORT(void) LDUserSetCustomAttributes(LDUser *const user,
LDNode *const custom);
/** @brief Add an attribute name to the private list which will not be
* recorded. */
LD_EXPORT(void) LDUserAddPrivateAttribute(LDUser *const user,
const char *const attribute);
/** @brief Get JSON string containing all flags */
LD_EXPORT(char *) LDClientSaveFlags(struct LDClient_i *const client);
/** @brief Set flag store from JSON string */
LD_EXPORT(void) LDClientRestoreFlags(struct LDClient_i *const client,
const char *const data);
/** @brief Update the client with a new user.
*
* The old user is freed. This will re-fetch feature flag settings from
* LaunchDarkly. For performance reasons, user contexts should not be
* changed frequently. */
LD_EXPORT(void) LDClientIdentify(struct LDClient_i *const client,
LDUser *const user);
/** @brief Send any pending events to the server. They will normally be
*
* flushed after a timeout, but may also be flushed manually. This operation
* does not block. */
LD_EXPORT(void) LDClientFlush(struct LDClient_i *const client);
/** @brief Returns true if the client has been initialized. */
LD_EXPORT(bool) LDClientIsInitialized(struct LDClient_i *const client);
/** @brief Block until initialized up to timeout, returns true if initialized */
LD_EXPORT(bool) LDClientAwaitInitialized(struct LDClient_i *const client,
const unsigned int timeoutmilli);
/** @brief Returns the offline status of the client. */
LD_EXPORT(bool) LDClientIsOffline(struct LDClient_i *const client);
/** @brief Make the client operate in offline mode. No network traffic. */
LD_EXPORT(void) LDClientSetOffline(struct LDClient_i *const client);
/** @brief Return the client to online mode. */
LD_EXPORT(void) LDClientSetOnline(struct LDClient_i *const client);
/** @brief Enable or disable polling mode */
LD_EXPORT(void) LDClientSetBackground(struct LDClient_i *const client,
const bool background);
/** @brief Close the client, free resources, and generally shut down.
*
* This will additionally close all secondary environments. Do not attempt to
* manage secondary environments directly. */
LD_EXPORT(void) LDClientClose(struct LDClient_i *const client);
/** @brief Add handler for when client status changes */
LD_EXPORT(void) LDSetClientStatusCallback(void (callback)(int status));
/** @brief Access the flag store must unlock with LDClientUnlockFlags */
LD_EXPORT(LDNode *) LDClientGetLockedFlags(struct LDClient_i *const client);
/** @brief Unlock flag store after direct access */
LD_EXPORT(void) LDClientUnlockFlags(struct LDClient_i *const client);
/** @brief Record a custom event. */
LD_EXPORT(void) LDClientTrack(struct LDClient_i *const client,
const char *const name);
/** @brief Record a custom event and include custom data. */
LD_EXPORT(void) LDClientTrackData(struct LDClient_i *const client,
const char *const name, LDNode *const data);
/** @brief Record a custom event and include custom data / a metric. */
LD_EXPORT(void) LDClientTrackMetric(struct LDClient_i *const client,
const char *const name, LDNode *const data, const double metric);
/** @brief Returns a hash table of all flags. This must be freed with
* `LDNodeFree`. */
LD_EXPORT(LDNode *) LDAllFlags(struct LDClient_i *const client);
/** @brief Evaluate Bool flag */
LD_EXPORT(bool) LDBoolVariation(struct LDClient_i *const client,
const char *const featureKey, const bool fallback);
/** @brief Evaluate Int flag
*
* If the flag value is actually a float the result is truncated. */
LD_EXPORT(int) LDIntVariation(struct LDClient_i *const client,
const char *const featureKey, const int fallback);
/** @brief Evaluate Double flag */
LD_EXPORT(double) LDDoubleVariation(struct LDClient_i *const client,
const char *const featureKey, const double fallback);
/** @brief Evaluate String flag */
LD_EXPORT(char *) LDStringVariationAlloc(struct LDClient_i *const client,
const char *const featureKey, const char *const fallback);
/** @brief Evaluate String flag into fixed buffer */
LD_EXPORT(char *) LDStringVariation(struct LDClient_i *const client,
const char *const featureKey, const char *const fallback,
char *const resultBuffer, const size_t resultBufferSize);
/** @brief Evaluate JSON flag */
LD_EXPORT(LDNode *) LDJSONVariation(struct LDClient_i *const client,
const char *const featureKey, const LDNode *const fallback);
/** @brief Evaluate Bool flag with details */
LD_EXPORT(bool) LDBoolVariationDetail(struct LDClient_i *const client,
const char *const featureKey, const bool fallback,
LDVariationDetails *const details);
/** @brief Evaluate Int flag with details
*
* If the flag value is actually a float the result is truncated. */
LD_EXPORT(int) LDIntVariationDetail(struct LDClient_i *const client,
const char *const featureKey, const int fallback,
LDVariationDetails *const details);
/** @brief Evaluate Double flag with details */
LD_EXPORT(double) LDDoubleVariationDetail(struct LDClient_i *const client,
const char *const featureKey, const double fallback,
LDVariationDetails *const details);
/** @brief Evaluate String flag with details */
LD_EXPORT(char *) LDStringVariationAllocDetail(struct LDClient_i *const client,
const char *const featureKey, const char *const fallback,
LDVariationDetails *const details);
/** @brief Evaluate String flag into fixed buffer with details */
LD_EXPORT(char *) LDStringVariationDetail(struct LDClient_i *const client,
const char *const featureKey, const char *const fallback,
char *const resultBuffer, const size_t resultBufferSize,
LDVariationDetails *const details);
/** @brief Evaluate JSON flag with details */
LD_EXPORT(LDNode *) LDJSONVariationDetail(struct LDClient_i *const client,
const char *const key, const LDNode *const fallback,
LDVariationDetails *const details);
/** @brief Frees memory allocated by the SDK. */
LD_EXPORT(void) LDFree(void *const ptr);
/** @brief Allocate memory for usage by the SDK */
LD_EXPORT(void *) LDAlloc(const size_t bytes);
/** @brief Clear any memory associated with `LDVariationDetails` */
LD_EXPORT(void) LDFreeDetailContents(LDVariationDetails details);
/** @brief Create a new empty hash.
*
* (Implementation note: empty hash is a `NULL` pointer, not indicative of
* failure). */
LD_EXPORT(LDNode *) LDNodeCreateHash(void);
/** @brief Add Bool value to a hash */
LD_EXPORT(LDNode *) LDNodeAddBool(LDNode **const hash, const char *const key,
const bool b);
/** @brief Add Number value to a hash */
LD_EXPORT(LDNode *) LDNodeAddNumber(LDNode **const hash, const char *const key,
const double n);
/** @brief Add String value to a hash */
LD_EXPORT(LDNode *) LDNodeAddString(LDNode **const hash, const char *const key,
const char *const s);
/** @brief Add Hash value to a hash */
LD_EXPORT(LDNode *) LDNodeAddHash(LDNode **const hash, const char *const key,
LDNode *const h);
/** @brief Add Array value to a hash */
LD_EXPORT(LDNode *) LDNodeAddArray(LDNode **const hash, const char *const key,
LDNode *const a);
/** @brief Find a node in a hash. */
LD_EXPORT(LDNode *) LDNodeLookup(const LDNode *const hash,
const char *const key);
/** @brief Free a hash and all internal memory. */
LD_EXPORT(void) LDNodeFree(LDNode **const hash);
/** @brief Return the number of elements in a hash or array. */
LD_EXPORT(unsigned int) LDNodeCount(const LDNode *const hash);
/** @brief Return a deep copy of a hash */
LD_EXPORT(LDNode *) LDCloneHash(const LDNode *const original);
/** @brief Create a new empty array */
LD_EXPORT(LDNode *) LDNodeCreateArray(void);
/** @brief Append Bool value to an array */
LD_EXPORT(LDNode *) LDNodeAppendBool(LDNode **const array, const bool b);
/** @brief Append Number value to an array */
LD_EXPORT(LDNode *) LDNodeAppendNumber(LDNode **const array, const double n);
/** @brief Append String value to an array */
LD_EXPORT(LDNode *) LDNodeAppendString(LDNode **const array,
const char *const s);
/** @brief Append existing node to an array */
LD_EXPORT(LDNode *) LDNodeAppendArray(LDNode **const array, LDNode *const a);
/** @brief Add existing node to an array */
LD_EXPORT(LDNode *) LDNodeAppendHash(LDNode **const array, LDNode *const h);
/** @brief Lookup node at a given index in an Array */
LD_EXPORT(LDNode *) LDNodeIndex(const LDNode *const array,
const unsigned int idx);
/** @brief Deep copy array */
LD_EXPORT(LDNode *) LDCloneArray(const LDNode *const original);
/** @brief Serialize `LDNode` to JSON */
LD_EXPORT(char *) LDNodeToJSON(const LDNode *const node);
/** @brief Deserialize JSON into `LDNode` */
LD_EXPORT(LDNode *) LDNodeFromJSON(const char *const json);
/** @brief Utility to convert a hash to a JSON object. */
LD_EXPORT(char *) LDHashToJSON(const LDNode *const node);
/** @brief Set the log function and log level. Increasing log levels result in
* increasing output. */
LD_EXPORT(void) LDSetLogFunction(const int userlevel,
void (userlogfn)(const char *const text));
/** @brief Should write the `data` using the associated `context` to `name`.
* Returns `true` for success. */
typedef bool (*LD_store_stringwriter)(void *const context,
const char *const name, const char *const data);
/** @brief Read a string from the `name` associated with the `context`.
* Returns `NULL` on failure.
*
* Memory returned from the reader must come from `LDAlloc`. */
typedef char *(*LD_store_stringreader)(void *const context,
const char *const name);
/** @brief Sets the storage functions to be used.
*
* Reader and writer may optionally be `NULL`. The provided opaque context
* is passed to each open call. */
LD_EXPORT(void) LD_store_setfns(void *const context, LD_store_stringwriter,
LD_store_stringreader);
/** @brief Predefined `ld_store_stringwriter` for files. */
LD_EXPORT(bool) LD_store_filewrite(void *const context, const char *const name,
const char *const data);
/** @brief Predefined `ld_store_stringreader` for files */
LD_EXPORT(char *) LD_store_fileread(void *const context,
const char *const name);
/** @brief Feature flag listener callback type.
*
* Status 0 for new or updated, 1 for deleted. */
typedef void (*LDlistenerfn)(const char *const flagKey, const int status);
/** @brief Register a callback for when a flag is updated. */
LD_EXPORT(void) LDClientRegisterFeatureFlagListener(
struct LDClient_i *const client, const char *const flagKey,
LDlistenerfn listener);
/** @brief Unregister a callback registered with
* `LDClientRegisterFeatureFlagListener` */
LD_EXPORT(bool) LDClientUnregisterFeatureFlagListener(
struct LDClient_i *const client, const char *const flagKey,
LDlistenerfn listener);
#if !defined(__cplusplus) && !defined(LD_C_API)
/** @brief Opaque client object **/
typedef struct LDClient_i LDClient;
#endif
#ifdef __cplusplus
}
class LD_EXPORT(LDClient) {
public:
static LDClient *Get(void);
static LDClient *Init(LDConfig *const client, LDUser *const user,
const unsigned int maxwaitmilli);
bool isInitialized(void);
bool awaitInitialized(const unsigned int timeoutmilli);
bool boolVariation(const std::string &flagKey, const bool fallback);
int intVariation(const std::string &flagKey, const int fallback);
double doubleVariation(const std::string &flagKey,
const double fallback);
std::string stringVariation(const std::string &flagKey,
const std::string &fallback);
char *stringVariation(const std::string &flagKey,
const std::string &fallback, char *const resultBuffer,
const size_t resultBufferSize);
LDNode *JSONVariation(const std::string &flagKey,
const LDNode *const fallback);
bool boolVariationDetail(const std::string &flagKey,
const bool fallback, LDVariationDetails *const details);
int intVariationDetail(const std::string &flagKey, const int fallback,
LDVariationDetails *const details);
double doubleVariationDetail(const std::string &flagKey,
const double fallback, LDVariationDetails *const details);
std::string stringVariationDetail(const std::string &flagKey,
const std::string &fallback, LDVariationDetails *const details);
char *stringVariationDetail(const std::string &flagKey,
const std::string &fallback, char *const resultBuffer,
const size_t resultBufferSize, LDVariationDetails *const details);
LDNode *JSONVariationDetail(const std::string &flagKey,
const LDNode *const fallback, LDVariationDetails *const details);
LDNode *getLockedFlags();
void unlockFlags();
LDNode *getAllFlags();
void setOffline();
void setOnline();
bool isOffline();
void setBackground(const bool background);
std::string saveFlags();
void restoreFlags(const std::string &flags);
void identify(LDUser *);
void track(const std::string &name);
void track(const std::string &name, LDNode *const data);
void flush(void);
void close(void);
void registerFeatureFlagListener(const std::string &name,
LDlistenerfn fn);
bool unregisterFeatureFlagListener(const std::string &name,
LDlistenerfn fn);
private:
struct LDClient_i *client;
};
#endif
#endif /* C_CLIENT_LDIAPI_H */
| 36.694767 | 80 | 0.728551 | [
"object"
] |
3edb8c78c3ebe6bb8e1333534508797f4c076c5c | 3,297 | h | C | ampp/etl/string_util.h | kodokse/ampp | d97e11564a2974c2aa123fadafcb0280a4cdae2d | [
"MIT"
] | 1 | 2017-05-05T07:29:55.000Z | 2017-05-05T07:29:55.000Z | ampp/etl/string_util.h | kodokse/ampp | d97e11564a2974c2aa123fadafcb0280a4cdae2d | [
"MIT"
] | null | null | null | ampp/etl/string_util.h | kodokse/ampp | d97e11564a2974c2aa123fadafcb0280a4cdae2d | [
"MIT"
] | null | null | null | #pragma once
namespace etl
{
template <class CharT>
std::vector<std::basic_string<CharT>> Split(const CharT *&s, const CharT *end, CharT ch);
template <class CharT>
std::vector<std::basic_string<CharT>> Split(const CharT *&s, const CharT *end, const CharT *match);
template <class CharT>
std::vector<std::basic_string<CharT>> Split(const std::basic_string<CharT> &s, CharT ch);
template <class CharT>
std::vector<std::basic_string<CharT>> Split(const std::basic_string<CharT> &s, const CharT *match);
template <class CharT>
bool IsWhite(CharT c)
{
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
template <class CharT, class TraitsT>
std::basic_string<CharT, TraitsT> &TrimR(std::basic_string<CharT, TraitsT> &s)
{
auto l = s.length();
while (l > 0 && IsWhite(s[l - 1]))
{
--l;
}
if (l < s.length())
{
s.resize(l);
}
return s;
}
void Skip(const wchar_t *&fmtLine, const wchar_t *endFmtLine, wchar_t ch);
void SkipUntil(const wchar_t *&fmtLine, const wchar_t *endFmtLine, wchar_t ch);
template <class CIterT>
std::wstring CopyUntil(CIterT &fmtLine, const CIterT &endFmtLine, wchar_t ch)
{
std::wstring rv;
while(fmtLine != endFmtLine && *fmtLine != ch)
{
rv += *fmtLine++;
}
return rv;
}
template <class CIterT, class PredT>
std::wstring CopyWhile(CIterT &fmtLine, const CIterT &endFmtLine, PredT p)
{
std::wstring rv;
while (fmtLine != endFmtLine && p(*fmtLine))
{
rv += *fmtLine++;
}
return rv;
}
template <class CharT, class IntT>
struct IntTraits
{
private:
static const int MaxNumRadix = 10;
static bool IsNumDigit(CharT v, int radix)
{
return v >= CharT('0') && v < CharT('0') + __min(radix, MaxNumRadix);
}
public:
static bool IsDigit(CharT v, int radix)
{
if(IsNumDigit(v, radix))
{
return true;
}
auto lv = tolower(v);
return radix > 10 && lv >= CharT('a') && lv < CharT('a') + (radix - MaxNumRadix);
}
static int Value(CharT v, int radix)
{
return IsNumDigit(v, radix) ? v - CharT('0') : MaxNumRadix + (v - CharT('a'));
}
};
template <class CIterT, class IntT, std::enable_if_t<std::is_signed_v<IntT>>>
bool ParseInt(CIterT &cur, const CIterT &end, IntT &val, int radix, int maxDigits = -1)
{
using Traits = IntTraits<typename CIterT::value_type, IntT>;
bool negate = false;
auto tmp = cur;
if(*cur == '-')
{
++cur;
negate = true;
}
if(!Traits::IsDigit(*cur, radix))
{
cur = tmp;
return false;
}
int digitCount = 0;
val = 0;
while(cur != end && Traits::IsDigit(*cur, radix) && (maxDigits > 0 ? digitCount < maxDigits : true))
{
val *= radix;
val += Traits::Value(*cur, radix);
++cur;
++digitCount;
}
if(negate)
{
val = -val;
}
return true;
}
template <class CIterT, class IntT>
bool ParseInt(CIterT &cur, const CIterT &end, IntT &val, int radix, int maxDigits = -1)
{
using Traits = IntTraits<typename CIterT::value_type, IntT>;
if(!Traits::IsDigit(*cur, radix))
{
return false;
}
int digitCount = 0;
val = 0;
while(cur != end && Traits::IsDigit(*cur, radix) && (maxDigits > 0 ? digitCount < maxDigits : true))
{
val *= radix;
val += Traits::Value(*cur, radix);
++cur;
++digitCount;
}
return true;
}
} // namespace etl
| 23.382979 | 102 | 0.622081 | [
"vector"
] |
3edc13cf65f025710d717244048183e749e938f7 | 17,526 | h | C | include/Vorb/script/lua/ValueMediator.h | ChillstepCoder/Vorb | f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba | [
"MIT"
] | 65 | 2018-06-03T23:09:46.000Z | 2021-07-22T22:03:34.000Z | include/Vorb/script/lua/ValueMediator.h | ChillstepCoder/Vorb | f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba | [
"MIT"
] | 8 | 2018-06-20T17:21:30.000Z | 2020-06-30T01:06:26.000Z | include/Vorb/script/lua/ValueMediator.h | ChillstepCoder/Vorb | f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba | [
"MIT"
] | 34 | 2018-06-04T03:40:52.000Z | 2022-02-15T07:02:05.000Z | //
// lua/ValueMediator.h
// Vorb Engine
//
// Created by Matthew Marshall on 8 Nov 2018
// Adapted (read, basically entirely lifted) from original ScriptValueSenders by Cristian Zaloj.
// Copyright 2018 Regrowth Studios
// MIT License
//
/*! \file ValueMediator.h
* \brief Value mediator between Lua script env and C++.
*/
#pragma once
#ifndef Vorb_Lua_ValueMediator_h__
//! @cond DOXY_SHOW_HEADER_GUARDS
#define Vorb_Lua_ValueMediator_h__
//! @endcond
#ifdef VORB_USING_SCRIPT
#include <lua.hpp>
#include "Vorb/types.h"
namespace vorb {
namespace script {
namespace lua {
using Handle = lua_State*;
// Forward declare the ValueMediator struct.
// This struct is used to facilitate simpler templated pushing and popping of common types onto the lua state stack.
template<typename Type, typename = void> struct ValueMediator;
// Define a couple of macros to declare the various ValueMediator specialisations.
// In principle the type of the value to be pushed or popped could take up multiple values on the stack (e.g. a 2D vector would be 2 number values),
// so we return an integer from push indicating the number of values pushed onto the stack.
#define VALUE_MEDIATOR_REF(TYPE) \
template<> \
struct ValueMediator<TYPE, void> { \
public: \
static TYPE defaultValue(); \
static i32 getValueCount(); \
static i32 push(Handle state, const TYPE& value); \
static TYPE pop(Handle state); \
static bool tryPop(Handle state, OUT TYPE& value); \
static TYPE retrieve(Handle state, ui32 index); \
static bool tryRetrieve(Handle state, ui32 index, OUT TYPE& value); \
}
#define VALUE_MEDIATOR_VAL(TYPE) \
template<> \
struct ValueMediator<TYPE, void> { \
public: \
static TYPE defaultValue(); \
static i32 getValueCount(); \
static i32 push(Handle state, TYPE value); \
static TYPE pop(Handle state); \
static bool tryPop(Handle state, OUT TYPE& value); \
static TYPE retrieve(Handle state, ui32 index); \
static bool tryRetrieve(Handle state, ui32 index, OUT TYPE& value); \
}
#define VALUE_MEDIATOR_VEC(TYPE) \
VALUE_MEDIATOR_VAL(TYPE); \
VALUE_MEDIATOR_REF(TYPE##v2); \
VALUE_MEDIATOR_REF(TYPE##v3); \
VALUE_MEDIATOR_REF(TYPE##v4)
VALUE_MEDIATOR_VEC(i8);
VALUE_MEDIATOR_VEC(i16);
VALUE_MEDIATOR_VEC(i32);
VALUE_MEDIATOR_VEC(i64);
VALUE_MEDIATOR_VEC(ui8);
VALUE_MEDIATOR_VEC(ui16);
VALUE_MEDIATOR_VEC(ui32);
VALUE_MEDIATOR_VEC(ui64);
VALUE_MEDIATOR_VEC(f32);
VALUE_MEDIATOR_VEC(f64);
VALUE_MEDIATOR_VAL(bool);
VALUE_MEDIATOR_REF(nString);
VALUE_MEDIATOR_VAL(const cString);
VALUE_MEDIATOR_VAL(void*);
VALUE_MEDIATOR_REF(color4);
#undef VALUE_MEDIATOR_VEC
#undef VALUE_MEDIATOR_REF
#undef VALUE_MEDIATOR_VAL
#if defined(VORB_OS_WINDOWS)
template<typename Type>
i32 getTotalValueCount() {
return ValueMediator<Type>::getValueCount();
}
template<typename Type1, typename Type2, typename ...Types>
i32 getTotalValueCount() {
return getTotalValueCount<Type2, Types...>()
+ getTotalValueCount<Type1>();
}
#else
template<typename ...Types>
i32 getTotalValueCount() {
i32 temp = 0;
for (i32 size : { 0, ValueMediator<Types>::getValueCount()... }) {
temp += size;
}
return temp;
}
#endif
namespace impl {
/*!
* \brief Workaround for MSVC being shit.
*
* \tparam The type for whihc to get a default values.
*
* \return The default value of the type specified.
*/
template <typename Type>
Type getDefault() {
return ValueMediator<Type>::defaultValue();
}
/*!
* \brief rpopValues provides a recursive method to pop all expected values from the Lua stack.
*
* These three functions provide a recursive method to pop all expected values from
* the lua state stack. The list of value types provided is the reverse order to the
* order of the values on the stack. E.g. for parameters <int, double, nString>
* we would expect the top value on the stack to be a C string, the second to top a double
* and the third to be an integer.
*
* \param state The Lua stack.
* \param tPtr A pointer to the tuple we wish to populate.
*/
template<typename Type>
void rpopValues(Handle state, OUT std::tuple<Type>* tPtr) {
// Pop one value of type Type from stack and put in tuple.
std::get<0>(*tPtr) = ValueMediator<Type>::pop(state);
}
template<typename Type>
void rpopValues(Handle state, OUT std::tuple<Type&>* tPtr) {
// Copy the pointer to the value into the tuple.
void* value = ValueMediator<void*>::pop(state);
std::memcpy(tPtr, &value, sizeof(void*));
}
template<typename Type1, typename Type2, typename ...Types>
void rpopValues(Handle state, OUT std::tuple<Type1, Type2, Types...>* tPtr) {
// Pop all but the first value - we want this recursive approach to pop in reverse order of
// types provided.
std::tuple<Type2, Types...> tToPop{ ValueMediator<Type2>::defaultValue(), getDefault<Types>()... };
rpopValues<Type2, Types...>(state, &tToPop);
// Pop the first value.
std::tuple<Type1> tPopped{ ValueMediator<Type1>::defaultValue() };
rpopValues<Type1>(state, &tPopped);
// Concatenate tuples and swap with the pointer provided.
auto catRes = std::tuple_cat(tPopped, tToPop);
std::swap(*tPtr, catRes);
}
/*!
* \brief rpopValues provides a recursive method to safely pop all expected values from the Lua stack.
*
* These three functions provide a recursive method to safely pop all expected values from
* the lua state stack. The list of value types provided is the reverse order to the
* order of the values on the stack. E.g. for parameters <int, double, nString>
* we would expect the top value on the stack to be a C string, the second to top a double
* and the third to be an integer.
*
* \param state The Lua stack.
* \param tPtr A pointer to the tuple we wish to populate.
*
* \return True if all values are successfully popped, false otherwise.
*/
template<typename Type>
bool rtryPopValues(Handle state, OUT std::tuple<Type>* tPtr) {
// Pop one value of type Type from stack and put in tuple.
return ValueMediator<Type>::tryPop(state, std::get<0>(*tPtr));
}
template<typename Type>
bool rtryPopValues(Handle state, OUT std::tuple<Type&>* tPtr) {
// Attempt to pop off the pointer to the value, if successful copy the pointer into the tuple.
void* value = nullptr;
if (!ValueMediator<void*>::tryPop(state, value)) {
return false;
}
std::memcpy(tPtr, &value, sizeof(void*));
return true;
}
template<typename Type1, typename Type2, typename ...Types>
bool rtryPopValues(Handle state, OUT std::tuple<Type1, Type2, Types...>* tPtr) {
// Pop all but the first value - we want this recursive approach to pop in reverse order of
// types provided.
std::tuple<Type2, Types...> tToPop{ ValueMediator<Type2, Types>::defaultValue()... };
if (!rtryPopValues<Type2, Types...>(state, &tToPop)) {
return false;
}
// Pop the first value.
std::tuple<Type1> tPopped{ ValueMediator<Type1>::defaultValue() };
if (!rtryPopValues<Type1>(state, &tPopped)) {
return false;
}
// Concatenate tuples and swap with the pointer provided.
*tPtr = std::tuple_cat(tPopped, tToPop);
return true;
}
}
template<typename ...Types>
std::tuple<Types...> popValues(Handle state) {
// Initialise tuple with default values for each type of Parameters.
std::tuple<Types...> values{ ValueMediator<Types>::defaultValue()... };
impl::rpopValues(state, &values);
return std::move(values);
}
template<typename ...Types>
bool tryPopValues(Handle state, std::tuple<Types...>& values) {
return impl::rtryPopValues(state, &values);
}
// Provides support for pushing and popping enums by converting to and from their underlying type.
template<typename Type>
struct ValueMediator<Type, typename std::enable_if<std::is_enum<Type>::value>::type> {
// Gets the underlying type of the enum (e.g. ui8, ui16 etc.).
using EnumType = typename std::underlying_type<Type>::type;
public:
static Type defaultValue() {
return static_cast<Type>(0);
}
static i32 getValueCount() {
return 1;
}
static i32 push(Handle state, Type value) {
return ValueMediator<EnumType>::push(state, static_cast<EnumType>(value));
}
static Type pop(Handle state) {
return static_cast<Type>(ValueMediator<EnumType>::pop(state));
}
static bool tryPop(Handle state, OUT Type& value) {
EnumType result;
// Try to pop the underlying enum type.
bool success = ValueMediator<EnumType>::tryPop(state, result);
// If successful, set value to the Type casted result of the pop.
if (success) {
value = static_cast<Type>(result);
}
// Return success of pop.
return success;
}
static Type retrieve(Handle state, ui32 index) {
return static_cast<Type>(ValueMediator<EnumType>::retrieve(state, index));
}
static bool tryRetrieve(Handle state, ui32 index, OUT Type& value) {
EnumType result;
// Try to pop the underlying enum type.
bool success = ValueMediator<EnumType>::tryRetrieve(state, index, result);
// If successful, set value to the Type casted result of the pop.
if (success) {
value = static_cast<Type>(result);
}
// Return success of pop.
return success;
}
};
// Provides support for pushing and popping pointer types by casting to and from void*.
template<typename Type>
struct ValueMediator<Type*, typename std::enable_if<std::is_pointer<Type*>::value>::type> {
using NoConstType = typename std::remove_const<Type>::type;
public:
static Type* defaultValue() {
return (Type*)nullptr;
}
static i32 getValueCount() {
return 1;
}
static i32 push(Handle state, Type* value) {
return ValueMediator<void*>::push(state, reinterpret_cast<void*>(const_cast<NoConstType*>(value)));
}
static Type* pop(Handle state) {
return reinterpret_cast<Type*>(ValueMediator<void*>::pop(state));
}
static bool tryPop(Handle state, OUT Type*& value) {
void* result;
// Try to pop the light user data.
bool success = ValueMediator<void*>::tryPop(state, result);
// If successful, set value to the Type* casted result of the pop.
if (success) {
value = reinterpret_cast<Type*>(result);
}
// Return success of pop.
return success;
}
static Type* retrieve(Handle state, ui32 index) {
return reinterpret_cast<Type*>(ValueMediator<void*>::retrieve(state, index));
}
static bool tryRetrieve(Handle state, ui32 index, OUT Type*& value) {
void* result;
// Try to pop the light user data.
bool success = ValueMediator<void*>::tryRetrieve(state, index, result);
// If successful, set value to the Type* casted result of the pop.
if (success) {
value = reinterpret_cast<Type*>(result);
}
// Return success of pop.
return success;
}
};
// Provides support for pushing and popping reference types by casting to and from void*.
template<typename Type>
struct ValueMediator<Type&, typename std::enable_if<std::is_reference<Type&>::value>::type> {
public:
static Type& defaultValue() {
Type* temp = (Type*)nullptr;
return *temp;
}
static i32 getValueCount() {
return 1;
}
static i32 push(Handle state, Type& value) {
return ValueMediator<void*>::push(state, const_cast<void*>(&value));
}
static Type& pop(Handle state) {
return *((Type*)ValueMediator<void*>::pop(state));
}
static bool tryPop(Handle state, OUT Type& value) {
void* result;
// Try to pop the light user data.
bool success = ValueMediator<void*>::tryPop(state, result);
// If successful, set value to the Type casted result of the pop.
if (success) {
value = *(Type*)result;
}
// Return success of pop.
return success;
}
static Type& retrieve(Handle state, ui32 index) {
return *((Type*)ValueMediator<void*>::retrieve(state, index));
}
static bool tryRetrieve(Handle state, ui32 index, OUT Type& value) {
void* result;
// Try to pop the light user data.
bool success = ValueMediator<void*>::tryRetrieve(state, index, result);
// If successful, set value to the Type casted result of the pop.
if (success) {
value = *(Type*)result;
}
// Return success of pop.
return success;
}
};
}
}
}
namespace vscript = vorb::script;
#endif // VORB_USING_SCRIPT
#endif // !Vorb_Lua_ValueMediator_h__
| 45.759791 | 160 | 0.492697 | [
"vector"
] |
3ee09f4b09ec37111f57c4145cf869a3d8361d10 | 5,365 | h | C | src/nimbro_robotcontrol/hardware/robotcontrol/include/robotcontrol/motionmodule.h | hfarazi/humanoid_op_ros_kinetic | 84712bd541d0130b840ad1935d5bfe301814dbe6 | [
"BSD-3-Clause"
] | 45 | 2015-11-04T01:29:12.000Z | 2022-02-11T05:37:42.000Z | src/nimbro_robotcontrol/hardware/robotcontrol/include/robotcontrol/motionmodule.h | hfarazi/humanoid_op_ros_kinetic | 84712bd541d0130b840ad1935d5bfe301814dbe6 | [
"BSD-3-Clause"
] | 1 | 2018-11-22T08:34:34.000Z | 2018-11-22T08:34:34.000Z | src/nimbro_robotcontrol/hardware/robotcontrol/include/robotcontrol/motionmodule.h | hfarazi/humanoid_op_ros_kinetic | 84712bd541d0130b840ad1935d5bfe301814dbe6 | [
"BSD-3-Clause"
] | 20 | 2016-03-05T14:28:45.000Z | 2021-01-30T00:50:47.000Z | // Interface for robotcontrol motion module plugins
// Author: Philipp Allgeuer <pallgeuer@ais.uni-bonn.de>
// Sebastian Schüller <schuell1@cs.uni-bonn.de>
// Ensure header is only included once
#ifndef MOTIONMODULE_H
#define MOTIONMODULE_H
// Includes
#include <string>
// Robotcontrol namespace
namespace robotcontrol
{
// Class declarations
class RobotModel;
/**
* @class MotionModule
*
* @brief Abstract base class for all motion modules.
**/
class MotionModule
{
public:
//! @brief Default constructor
MotionModule() : m_model(NULL), m_paramString("") {}
//! @brief Default destructor
virtual ~MotionModule() {}
/**
* @brief Initialisation function
*
* This function is intended for overriding by derived motion module classes, to allow these subclasses to
* perform their required initialisation. Note however that the base implementation must be explicitly called
* first thing by all overrides of this function, and return `false` if it returns `false`. Something like:
* @code
* bool DerivedMotionModule::init(robotcontrol::RobotModel* model)
* {
* // Initialise the base class
* if(!MotionModule::init(model)) return false;
*
* // Extra initialisation
* ...
*
* // Return that initialisation was successful
* return true;
* }
* @endcode
*
* @param model The instance of RobotModel to operate on.
* @return `true` if initialisation is successful, `false` otherwise.
**/
virtual bool init(RobotModel* model);
/**
* @brief Deinitialisation function
*
* This function is intended for overriding by derived motion module classes, to allow these subclasses to
* handle the case when the motion module is no longer going to be used. The default implementation does nothing.
**/
virtual void deinit() {}
/**
* @brief Trigger function
*
* Returns whether the motion module wishes to be active and execute in the current time step.
* The default implementation always returns `true`, meaning that `step()` always executes.
**/
virtual bool isTriggered();
/**
* @brief Main step function of the motion module
*
* This function is called whenever the motion module is triggered, and should calculate and set joint commands
* appropriate for the required action of the motion module.
*
* The `step()` function is pure virtual and must be overridden in derived classes.
**/
virtual void step() = 0;
/**
* @brief Function to publish the required frame transforms
*
* This function can be used to, for example, publish TF frame transforms for the frames that the motion module
* defines and is responsible for. It should not be assumed that this function is called every time that `step()`
* is called for the motion module.
**/
virtual void publishTransforms() {}
//! @brief Return the internal instance of RobotModel that is being operated on
RobotModel* model() { return m_model; }
//! @brief Return the internal instance of RobotModel that is being operated on (constant reference)
const RobotModel* model() const { return m_model; }
/**
* @brief Determine if current situation is safe
*
* If this function returns false, a fade-in is prevented. This can be
* used to recognize some invalid robot state, and deny any fade-in
* request until the situation is manually resolved.
*
* @note If not overriden, this method always returns true.
**/
virtual bool isSafeToFadeIn();
//! @brief Get motion module name (class name)
const std::string& name() const
{ return m_name; }
/**
* @brief Handle emergency stop
*
* If you need to reset any internal state when the emergency stop is
* active (see HardwareInterface::emergencyStopActive()), you can do
* it here.
**/
virtual void handleEmergencyStop() {}
protected:
/**
* @brief Set a joint command based on position and effort only
*
* @param index Index of the joint to command in the `RobotModel::m_joints[]` array. See `RobotModel::jointIndex()`
* and `RobotModel::joint()` for more information on how to obtain the joint index you need.
* @param pos The position of the joint to command (`rad`).
* @param effort The effort to use in trying to follow the joint command (in the range `[0,1]`).
* @param raw Boolean flag specifying whether the joint command should be interpreted as a raw (i.e. direct) command (Default: False).
**/
void setJointCommand(int index, double pos, double effort, bool raw = false);
//! @brief Get the motion module parameter string (intended for use by overrides of the `init()` function, valid only if the init() function is being or has been called)
std::string getParamString() const { return m_paramString; }
private:
//! @brief Set the motion module's name for easier logging
void setName(const std::string& name) { m_name = name; }
//! @brief Set the motion module parameter string (intended for use by `RobotControl::initModules()` only)
void setParamString(const std::string& paramString) { m_paramString = paramString; }
//! @brief Internal `RobotModel` reference
RobotModel* m_model;
//! @brief Motion module name (class name)
std::string m_name;
//! @brief Motion module parameter string
std::string m_paramString;
// Friend classes
friend class RobotControl;
};
}
#endif /* MOTIONMODULE_H */
// EOF | 33.742138 | 171 | 0.710531 | [
"model"
] |
3ee50a94deb4ae084ea6934ab7ffbf62fa188d78 | 7,180 | h | C | include/External/CommonCPP/cc++/slog.h | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/CommonCPP/cc++/slog.h | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/CommonCPP/cc++/slog.h | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 1999-2001 Open Source Telecom Corporation.
//
// 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.
//
// As a special exception to the GNU General Public License, permission is
// granted for additional uses of the text contained in its release
// of Common C++.
//
// The exception is that, if you link the Common C++ library with other
// files to produce an executable, this does not by itself cause the
// resulting executable to be covered by the GNU General Public License.
// Your use of that executable is in no way restricted on account of
// linking the Common C++ library code into it.
//
// This exception does not however invalidate any other reasons why
// the executable file might be covered by the GNU General Public License.
//
// This exception applies only to the code released under the
// name Common C++. If you copy code from other releases into a copy of
// Common C++, as the General Public License permits, the exception does
// not apply to the code that you add in this way. To avoid misleading
// anyone as to the status of such modified files, you must delete
// this exception notice from them.
//
// If you write modifications of your own for Common C++, it is your choice
// whether to permit this exception to apply to your modifications.
// If you do not wish that, delete this exception notice.
#ifndef __CCXX_SLOG_H__
#define __CCXX_SLOG_H__
#ifndef CCXX_CONFIG_H_
#include <cc++/config.h>
#endif
#ifndef __CCXX_THREAD_H__
#include <cc++/thread.h>
#endif
#include <fstream>
#include <iostream>
#include <strstream>
#ifdef CCXX_NAMESPACES
namespace ost {
#endif
enum slog_class_t
{
SLOG_SECURITY,
SLOG_AUDIT,
SLOG_DAEMON,
SLOG_USER,
SLOG_DEFAULT
};
typedef enum slog_class_t slog_class_t;
enum slog_level_t
{
SLOG_EMERGENCY = 1,
SLOG_ALERT,
SLOG_CRITICAL,
SLOG_ERROR,
SLOG_WARNING,
SLOG_NOTICE,
SLOG_INFO,
SLOG_DEBUG
};
typedef enum slog_level_t slog_level_t;
/**
* The slog class is used to stream messages to the system's logging facility (syslogd).
* A default <code>slog</code> object is used to avoid confusion with the native syslog
* facility and to imply a logical relationship to the C++ <code>clog()</code>.
*
* The key difference is that the <code>slog</code> object sends it's output to the
* system logging daemon (typically syslogd) rather than through stderr.
* <code>slog</code> can be streamed with the <code><<</code> operator just
* like <code>clog</code>; a default slog object is pre-initialized, and you stream
* character data to it.
*
* The <code>slog</code> allows one to specify logging levels and other properties through the <code>()</code> operators.
* Hence, once can do:
*
* <code><pre>
* slog("mydaemon", SLOG_DAEMON, SLOG_EMERGENCY) << I just died << endl; </pre></code>
*
* or things like:
*
* <code><pre>
* slog("mydaemon", SLOG_DAEMON);
* slog(SLOG_INFO) << "daemon initalized" << endl; </pre></code>
*
* The intent is to be as common-place and as convenient to use as the stderr based clog facility
* found in C++, and this is especially useful for C++ daemons.
*
* The <code>std::flush</code> manipulator doesn't work. Either the
* <code>std::endl</code> or <code>std::ends</code> manipulators
* must be used to cause the output to be sent to the daemon.
*
* When this class is used on a system that doesn't have the syslog headers
* (i.e. a non-posix win32 box), the output goes to the a file with the same name
* as the syslog identifier string with '.log' appended to it. If the identifier string ends in
* '.exe', the '.exe' is removed before the '.log' is appened. (e.g. the identifier foo.exe will
* generate a log file named foo.log)
*
* @author David Sugar <dyfet@ostel.com>
* <br>Minor docs & hacks by Jon Little <littlej@arlut.utexas.edu>
*
* @short system logging facility class.
*/
#if defined(STLPORT) || defined(__KCC)
#define ostream ostream_withassign
#endif
class CCXX_CLASS_EXPORT Slog : public std::streambuf, public std::ostream
{
private:
#ifndef HAVE_SYSLOG_H
Mutex lock;
std::ofstream syslog;
#endif
int priority;
slog_level_t _level;
bool _enable;
bool _clogEnable;
protected:
/**
* This is the streambuf function that actually outputs the data
* to the device. Since all output should be done with the standard
* ostream operators, this function should never be called directly.
*/
int overflow(int c);
public:
/**
* Default (and only) constructor. The default log level is set to
* SLOG_DEBUG. There is no default log facility set. One should be
* set before attempting any output. This is done by the <code>open()</code> or the
* <code>operator()(const char*, slog_class_t, slog_level_t)</code>
* functions.
*/
Slog(void);
virtual ~Slog(void);
void close(void);
/**
* (re)opens the output stream.
* @param ident The identifier portion of the message sent to the syslog daemon.
* @param grp The log facility the message is sent to
*/
void open(const char *ident, slog_class_t grp = SLOG_USER);
/**
* Sets the log identifier, level, and class to use for subsequent output
* @param ident The identifier portion of the message
* @param grp The log facility the message is sent to
* @param level The log level of the message
*/
Slog &operator()(const char *ident, slog_class_t grp = SLOG_USER,
slog_level_t level = SLOG_ERROR);
/**
* Changes the log level and class to use for subsequent output
* @param level The log level of the message
* @param grp The log facility the message is sent to
*/
Slog &operator()(slog_level_t level, slog_class_t = SLOG_DEFAULT);
/**
* Does nothing except return *this.
*/
Slog &operator()(void);
/**
* Sets the logging level.
* @param enable is the logging level to use for further output
*/
inline void level(slog_level_t enable)
{_level = enable;};
/**
* Enables or disables the echoing of the messages to clog in addition
* to the syslog daemon. This is enabled by the default class constructor.
* @param f true to enable, false to disable clog output
*/
inline void clogEnable(bool f=true)
{_clogEnable = f;};
};
extern Slog slog;
#ifdef CCXX_NAMESPACES
};
#endif
#endif
/** EMACS **
* Local variables:
* mode: c++
* c-basic-offset: 8
* End:
*/
| 32.785388 | 121 | 0.698886 | [
"object"
] |
3ee79d6ed75357e705ede118097bee82e46ff6ba | 27,275 | c | C | src/lib/ecore_win32/ecore_win32.c | gfriloux/ecore | e1ca9832f8265db515837139a90c2995c1eca673 | [
"BSD-2-Clause"
] | null | null | null | src/lib/ecore_win32/ecore_win32.c | gfriloux/ecore | e1ca9832f8265db515837139a90c2995c1eca673 | [
"BSD-2-Clause"
] | null | null | null | src/lib/ecore_win32/ecore_win32.c | gfriloux/ecore | e1ca9832f8265db515837139a90c2995c1eca673 | [
"BSD-2-Clause"
] | null | null | null | #ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#include <windowsx.h>
#include <Eina.h>
#include <Ecore.h>
#include <Ecore_Input.h>
#include "Ecore_Win32.h"
#include "ecore_win32_private.h"
/*============================================================================*
* Local *
*============================================================================*/
/**
* @cond LOCAL
*/
/* OLE IID for Drag'n Drop */
# define INITGUID
# include <basetyps.h>
DEFINE_OLEGUID(IID_IEnumFORMATETC, 0x00000103L, 0, 0);
DEFINE_OLEGUID(IID_IDataObject, 0x0000010EL, 0, 0);
DEFINE_OLEGUID(IID_IDropSource, 0x00000121L, 0, 0);
DEFINE_OLEGUID(IID_IDropTarget, 0x00000122L, 0, 0);
DEFINE_OLEGUID(IID_IUnknown, 0x00000000L, 0, 0);
#define IDI_ICON 101
static int _ecore_win32_init_count = 0;
static void
_ecore_win32_size_check(Ecore_Win32_Window *win, int w, int h, int *dx, int *dy)
{
int minimal_width;
int minimal_height;
minimal_width = GetSystemMetrics(SM_CXMIN);
minimal_height = GetSystemMetrics(SM_CYMIN);
if ((w) < MAX(minimal_width, (int)win->min_width))
*dx = 0;
if ((w) > (int)win->max_width)
*dx = 0;
if ((h) < MAX(minimal_height, (int)win->min_height))
*dy = 0;
if ((h) > (int)win->max_height)
*dy = 0;
}
LRESULT CALLBACK
_ecore_win32_window_procedure(HWND window,
UINT message,
WPARAM window_param,
LPARAM data_param)
{
Ecore_Win32_Callback_Data *data;
DWORD coord;
data = (Ecore_Win32_Callback_Data *)malloc(sizeof(Ecore_Win32_Callback_Data));
if (!data) return DefWindowProc(window, message, window_param, data_param);
data->window = window;
data->message = message;
data->window_param = window_param;
data->data_param = data_param;
data->timestamp = GetMessageTime();
coord = GetMessagePos();
data->x = GET_X_LPARAM(coord);
data->y = GET_Y_LPARAM(coord);
data->discard_ctrl = EINA_FALSE;
switch (data->message)
{
/* Keyboard input notifications */
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if ((data->message == WM_KEYDOWN) &&
(data->window_param == VK_CONTROL) &&
((HIWORD(data->data_param) & KF_EXTENDED) == 0))
{
/* Ctrl left key is pressed */
BOOL res;
MSG next_msg;
/*
* we check if the next message
* - is a WM_KEYDOWN
* - has the same timestamp than the Ctrl one
* - is the key press of the right Alt key
*/
res = PeekMessage(&next_msg, data->window,
WM_KEYDOWN, WM_KEYDOWN,
PM_NOREMOVE);
if (res &&
(next_msg.wParam == VK_MENU) &&
(next_msg.time == data->timestamp) &&
(HIWORD(next_msg.lParam) & KF_EXTENDED))
{
INF("discard left Ctrl key press (sent by AltGr key press)");
data->discard_ctrl = EINA_TRUE;
}
}
_ecore_win32_event_handle_key_press(data, 1);
return 0;
case WM_CHAR:
case WM_SYSCHAR:
INF("char message");
_ecore_win32_event_handle_key_press(data, 0);
return 0;
case WM_KEYUP:
case WM_SYSKEYUP:
INF("keyup message");
if ((data->window_param == VK_CONTROL) &&
((HIWORD(data->data_param) & KF_EXTENDED) == 0))
{
/* Ctrl left key is pressed */
BOOL res;
MSG next_msg;
/*
* we check if the next message
* - is a WM_KEYUP or WM_SYSKEYUP
* - has the same timestamp than the Ctrl one
* - is the key release of the right Alt key
*/
res = PeekMessage(&next_msg, data->window,
WM_KEYUP, WM_SYSKEYUP,
PM_NOREMOVE);
if (res &&
((next_msg.message == WM_KEYUP) ||
(next_msg.message == WM_SYSKEYUP)) &&
(next_msg.wParam == VK_MENU) &&
(next_msg.time == data->timestamp) &&
(HIWORD(next_msg.lParam) & KF_EXTENDED))
{
INF("discard left Ctrl key release (sent by AltGr key release)");
data->discard_ctrl = EINA_TRUE;
}
}
_ecore_win32_event_handle_key_release(data);
return 0;
case WM_SETFOCUS:
INF("setfocus message");
_ecore_win32_event_handle_focus_in(data);
return 0;
case WM_KILLFOCUS:
INF("kill focus message");
_ecore_win32_event_handle_focus_out(data);
return 0;
/* Mouse input notifications */
case WM_LBUTTONDOWN:
INF("left button down message");
SetCapture(window);
_ecore_win32_event_handle_button_press(data, 1);
return 0;
case WM_MBUTTONDOWN:
INF("middle button down message");
_ecore_win32_event_handle_button_press(data, 2);
return 0;
case WM_RBUTTONDOWN:
INF("right button down message");
_ecore_win32_event_handle_button_press(data, 3);
return 0;
case WM_LBUTTONUP:
{
Ecore_Win32_Window *w = NULL;
INF("left button up message");
ReleaseCapture();
w = (Ecore_Win32_Window *)GetWindowLongPtr(window, GWLP_USERDATA);
if (w->drag.dragging)
{
w->drag.dragging = 0;
return 0;
}
_ecore_win32_event_handle_button_release(data, 1);
return 0;
}
case WM_MBUTTONUP:
INF("middle button up message");
_ecore_win32_event_handle_button_release(data, 2);
return 0;
case WM_RBUTTONUP:
INF("right button up message");
_ecore_win32_event_handle_button_release(data, 3);
return 0;
case WM_MOUSEMOVE:
{
RECT rect;
Ecore_Win32_Window *w = NULL;
INF("moue move message");
w = (Ecore_Win32_Window *)GetWindowLongPtr(window, GWLP_USERDATA);
if (w->drag.dragging)
{
POINT pt;
pt.x = GET_X_LPARAM(data_param);
pt.y = GET_Y_LPARAM(data_param);
if (ClientToScreen(window, &pt))
{
if (w->drag.type == HTCAPTION)
{
int dx;
int dy;
dx = pt.x - w->drag.px;
dy = pt.y - w->drag.py;
ecore_win32_window_move(w, w->drag.x + dx, w->drag.y + dy);
w->drag.x += dx;
w->drag.y += dy;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTLEFT)
{
int dw;
dw = pt.x - w->drag.px;
ecore_win32_window_move_resize(w, w->drag.x + dw, w->drag.y, w->drag.w - dw, w->drag.h);
w->drag.x += dw;
w->drag.w -= dw;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTRIGHT)
{
int dw;
dw = pt.x - w->drag.px;
ecore_win32_window_resize(w, w->drag.w + dw, w->drag.h);
w->drag.w += dw;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTTOP)
{
int dh;
dh = pt.y - w->drag.py;
ecore_win32_window_move_resize(w, w->drag.x, w->drag.y + dh, w->drag.w, w->drag.h - dh);
w->drag.y += dh;
w->drag.h -= dh;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTBOTTOM)
{
int dh;
dh = pt.y - w->drag.py;
ecore_win32_window_resize(w, w->drag.w, w->drag.h + dh);
w->drag.h += dh;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTTOPLEFT)
{
int dx;
int dy;
int dh;
int dw;
dw = pt.x - w->drag.px;
dh = pt.y - w->drag.py;
dx = dw;
dy = dh;
_ecore_win32_size_check(w,
w->drag.w - dw, w->drag.h - dh,
&dx, &dy);
ecore_win32_window_move_resize(w, w->drag.x + dx, w->drag.y + dy, w->drag.w - dw, w->drag.h - dh);
w->drag.x += dx;
w->drag.y += dy;
w->drag.w -= dw;
w->drag.h -= dh;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTTOPRIGHT)
{
int dx;
int dy;
int dh;
int dw;
dw = pt.x - w->drag.px;
dh = pt.y - w->drag.py;
dx = dw;
dy = dh;
_ecore_win32_size_check(w,
w->drag.w, w->drag.h - dh,
&dx, &dy);
ecore_win32_window_move_resize(w, w->drag.x, w->drag.y + dy, w->drag.w, w->drag.h - dh);
w->drag.y += dy;
w->drag.w += dw;
w->drag.h -= dh;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTBOTTOMLEFT)
{
int dx;
int dy;
int dh;
int dw;
dw = pt.x - w->drag.px;
dh = pt.y - w->drag.py;
dx = dw;
dy = dh;
_ecore_win32_size_check(w,
w->drag.w - dw, w->drag.h + dh,
&dx, &dy);
ecore_win32_window_move_resize(w, w->drag.x + dx, w->drag.y, w->drag.w - dw, w->drag.h + dh);
w->drag.x += dx;
w->drag.w -= dw;
w->drag.h += dh;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
if (w->drag.type == HTBOTTOMRIGHT)
{
int dh;
int dw;
dw = pt.x - w->drag.px;
dh = pt.y - w->drag.py;
ecore_win32_window_resize(w, w->drag.w + dw, w->drag.h + dh);
w->drag.w += dw;
w->drag.h += dh;
w->drag.px = pt.x;
w->drag.py = pt.y;
return 0;
}
}
}
if (GetClientRect(window, &rect))
{
POINT pt;
INF("mouse in window");
pt.x = GET_X_LPARAM(data_param);
pt.y = GET_Y_LPARAM(data_param);
if (!PtInRect(&rect, pt))
{
if (w->pointer_is_in)
{
w->pointer_is_in = 0;
_ecore_win32_event_handle_leave_notify(data);
}
}
else
{
if (!w->pointer_is_in)
{
w->pointer_is_in = 1;
_ecore_win32_event_handle_enter_notify(data);
}
}
}
else
{
ERR("GetClientRect() failed");
}
_ecore_win32_event_handle_motion_notify(data);
return 0;
}
case WM_MOUSEWHEEL:
INF("mouse wheel message");
_ecore_win32_event_handle_button_press(data, 4);
return 0;
/* Window notifications */
case WM_CREATE:
INF("create window message");
_ecore_win32_event_handle_create_notify(data);
return 0;
case WM_DESTROY:
INF("destroy window message");
_ecore_win32_event_handle_destroy_notify(data);
return 0;
case WM_SHOWWINDOW:
INF("show window message");
if ((data->data_param == SW_OTHERUNZOOM) ||
(data->data_param == SW_OTHERZOOM))
return 0;
if (data->window_param)
_ecore_win32_event_handle_map_notify(data);
else
_ecore_win32_event_handle_unmap_notify(data);
return 0;
case WM_CLOSE:
INF("close window message");
_ecore_win32_event_handle_delete_request(data);
return 0;
case WM_GETMINMAXINFO:
INF("get min max info window message");
return TRUE;
case WM_MOVING:
INF("moving window message");
_ecore_win32_event_handle_configure_notify(data);
return TRUE;
case WM_MOVE:
INF("move window message");
return 0;
case WM_SIZING:
INF("sizing window message");
_ecore_win32_event_handle_resize(data);
_ecore_win32_event_handle_configure_notify(data);
return TRUE;
case WM_SIZE:
INF("size window message");
return 0;
/* case WM_WINDOWPOSCHANGING: */
/* { */
/* RECT rect; */
/* GetClientRect(window, &rect); */
/* printf (" *** ecore message : WINDOWPOSCHANGING %ld %ld\n", */
/* rect.right - rect.left, rect.bottom - rect.top); */
/* } */
/* _ecore_win32_event_handle_configure_notify(data); */
/* return 0; */
case WM_WINDOWPOSCHANGED:
INF("position changed window message");
_ecore_win32_event_handle_configure_notify(data);
_ecore_win32_event_handle_expose(data);
return 0;
case WM_ENTERSIZEMOVE:
INF("enter size move window message");
return 0;
case WM_EXITSIZEMOVE:
INF("exit size move window message");
return 0;
case WM_NCLBUTTONDOWN:
INF("non client left button down window message");
if (((DWORD)window_param == HTCAPTION) ||
((DWORD)window_param == HTBOTTOM) ||
((DWORD)window_param == HTBOTTOMLEFT) ||
((DWORD)window_param == HTBOTTOMRIGHT) ||
((DWORD)window_param == HTLEFT) ||
((DWORD)window_param == HTRIGHT) ||
((DWORD)window_param == HTTOP) ||
((DWORD)window_param == HTTOPLEFT) ||
((DWORD)window_param == HTTOPRIGHT))
{
Ecore_Win32_Window *w;
w = (Ecore_Win32_Window *)GetWindowLongPtr(window, GWLP_USERDATA);
ecore_win32_window_geometry_get(w,
NULL, NULL,
&w->drag.w, &w->drag.h);
SetCapture(window);
w->drag.type = (DWORD)window_param;
w->drag.px = GET_X_LPARAM(data_param);
w->drag.py = GET_Y_LPARAM(data_param);
w->drag.dragging = 1;
return 0;
}
return DefWindowProc(window, message, window_param, data_param);
case WM_SYSCOMMAND:
INF("sys command window message %d", (int)window_param);
if ((((DWORD)window_param & 0xfff0) == SC_MOVE) ||
(((DWORD)window_param & 0xfff0) == SC_SIZE))
{
Ecore_Win32_Window *w;
INF("sys command MOVE or SIZE window message : %dx%d", GET_X_LPARAM(data_param), GET_Y_LPARAM(data_param));
w = (Ecore_Win32_Window *)GetWindowLongPtr(window, GWLP_USERDATA);
w->drag.dragging = 1;
return 0;
}
return DefWindowProc(window, message, window_param, data_param);
/* GDI notifications */
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
{
RECT rect;
INF("paint message");
if (GetUpdateRect(window, &rect, FALSE))
{
PAINTSTRUCT ps;
HDC hdc;
hdc = BeginPaint(window, &ps);
data->update = rect;
_ecore_win32_event_handle_expose(data);
EndPaint(window, &ps);
}
return 0;
}
case WM_SETREDRAW:
INF("set redraw message");
return 0;
case WM_SYNCPAINT:
INF("sync paint message");
return 0;
default:
return DefWindowProc(window, message, window_param, data_param);
}
}
/**
* @endcond
*/
/*============================================================================*
* Global *
*============================================================================*/
HINSTANCE _ecore_win32_instance = NULL;
double _ecore_win32_double_click_time = 0.25;
unsigned long _ecore_win32_event_last_time = 0;
Ecore_Win32_Window *_ecore_win32_event_last_window = NULL;
int _ecore_win32_log_dom_global = -1;
int ECORE_WIN32_EVENT_MOUSE_IN = 0;
int ECORE_WIN32_EVENT_MOUSE_OUT = 0;
int ECORE_WIN32_EVENT_WINDOW_FOCUS_IN = 0;
int ECORE_WIN32_EVENT_WINDOW_FOCUS_OUT = 0;
int ECORE_WIN32_EVENT_WINDOW_DAMAGE = 0;
int ECORE_WIN32_EVENT_WINDOW_CREATE = 0;
int ECORE_WIN32_EVENT_WINDOW_DESTROY = 0;
int ECORE_WIN32_EVENT_WINDOW_SHOW = 0;
int ECORE_WIN32_EVENT_WINDOW_HIDE = 0;
int ECORE_WIN32_EVENT_WINDOW_CONFIGURE = 0;
int ECORE_WIN32_EVENT_WINDOW_RESIZE = 0;
int ECORE_WIN32_EVENT_WINDOW_DELETE_REQUEST = 0;
/*============================================================================*
* API *
*============================================================================*/
/**
* @addtogroup Ecore_Win32_Group Ecore_Win32 library
*
* Ecore_Win32 is a library that wraps Windows graphic functions
* and integrate them nicely into the Ecore main loop.
*
* @section Ecore_Win32_Sec_Init Initialisation / Shutdown
*
* To fill...
*
* @section Ecore_Win32_Sec_Icons How to set icons to an application
*
* It is possible to also sets the icon of the application easily:
*
* @li Create an icon with your favorite image creator. The Gimp is a
* good choice. Create several images of size 16, 32 and 48. You can
* also create images of size 24, 64, 128 and 256. Paste all of them
* in the image of size 16 as a layer. Save the image of size 16 with
* the name my_icon.ico. Put it where the source code of the
* application is located.
* @li Create my_icon_rc.rc file with your code editor and add in it:
* @code
* 101 ICON DISCARDABLE "my_icon.ico"
* @endcode
* @li With Visual Studio, put that file in the 'Resource file' part
* of the project.
* @li With MinGW, you have to compile it with windres:
* @code
* windres my_icon_rc.rc my_icon_rc.o
* @endcode
* and add my_icon_rc.o to the object files of the application.
*
* @note The value 101 must not be changed, it's the ID used
* internally by Ecore_Win32 to get the icons.
*
* @{
*/
/**
* @brief Initialize the Ecore_Win32 library.
*
* @return 1 or greater on success, 0 on error.
*
* This function sets up the Windows graphic system. It returns 0 on
* failure, otherwise it returns the number of times it has already been
* called.
*
* When Ecore_Win32 is not used anymore, call ecore_win32_shutdown()
* to shut down the Ecore_Win32 library.
*/
EAPI int
ecore_win32_init()
{
WNDCLASSEX wc;
HICON icon;
HICON icon_sm;
if (++_ecore_win32_init_count != 1)
return _ecore_win32_init_count;
if (!eina_init())
return --_ecore_win32_init_count;
_ecore_win32_log_dom_global = eina_log_domain_register
("ecore_win32", ECORE_WIN32_DEFAULT_LOG_COLOR);
if (_ecore_win32_log_dom_global < 0)
{
EINA_LOG_ERR("Ecore_Win32: Could not register log domain");
goto shutdown_eina;
}
if (!ecore_event_init())
{
ERR("Ecore_Win32: Could not init ecore_event");
goto unregister_log_domain;
}
_ecore_win32_instance = GetModuleHandle(NULL);
if (!_ecore_win32_instance)
{
ERR("GetModuleHandle() failed");
goto shutdown_ecore_event;
}
icon = LoadImage(_ecore_win32_instance,
MAKEINTRESOURCE(IDI_ICON),
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON),
LR_DEFAULTCOLOR);
icon_sm = LoadImage(_ecore_win32_instance,
MAKEINTRESOURCE(IDI_ICON),
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
LR_DEFAULTCOLOR);
if (!icon)
icon = LoadIcon (NULL, IDI_APPLICATION);
if (!icon_sm)
icon_sm = LoadIcon (NULL, IDI_APPLICATION);
memset (&wc, 0, sizeof (WNDCLASSEX));
wc.cbSize = sizeof (WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = _ecore_win32_window_procedure;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = _ecore_win32_instance;
wc.hIcon = icon;
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(1 + COLOR_BTNFACE);
wc.lpszMenuName = NULL;
wc.lpszClassName = ECORE_WIN32_WINDOW_CLASS;
wc.hIconSm = icon_sm;
if(!RegisterClassEx(&wc))
{
ERR("RegisterClass() failed");
goto free_library;
}
if (!ecore_win32_dnd_init())
{
ERR("ecore_win32_dnd_init() failed");
goto unregister_class;
}
if (!ECORE_WIN32_EVENT_MOUSE_IN)
{
ECORE_WIN32_EVENT_MOUSE_IN = ecore_event_type_new();
ECORE_WIN32_EVENT_MOUSE_OUT = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_FOCUS_IN = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_FOCUS_OUT = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_DAMAGE = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_CREATE = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_DESTROY = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_SHOW = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_HIDE = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_CONFIGURE = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_RESIZE = ecore_event_type_new();
ECORE_WIN32_EVENT_WINDOW_DELETE_REQUEST = ecore_event_type_new();
}
return _ecore_win32_init_count;
unregister_class:
UnregisterClass(ECORE_WIN32_WINDOW_CLASS, _ecore_win32_instance);
free_library:
FreeLibrary(_ecore_win32_instance);
shutdown_ecore_event:
ecore_event_shutdown();
unregister_log_domain:
eina_log_domain_unregister(_ecore_win32_log_dom_global);
shutdown_eina:
eina_shutdown();
return --_ecore_win32_init_count;
}
/**
* @brief Shut down the Ecore_Win32 library.
*
* @return 0 when the library is completely shut down, 1 or
* greater otherwise.
*
* This function shuts down the Ecore_Win32 library. It returns 0 when it has
* been called the same number of times than ecore_win32_init(). In that case
* it shuts down all the Windows graphic system.
*/
EAPI int
ecore_win32_shutdown()
{
if (--_ecore_win32_init_count != 0)
return _ecore_win32_init_count;
ecore_win32_dnd_shutdown();
if (!UnregisterClass(ECORE_WIN32_WINDOW_CLASS, _ecore_win32_instance))
INF("UnregisterClass() failed");
if (!FreeLibrary(_ecore_win32_instance))
INF("FreeLibrary() failed");
_ecore_win32_instance = NULL;
ecore_event_shutdown();
eina_log_domain_unregister(_ecore_win32_log_dom_global);
_ecore_win32_log_dom_global = -1;
eina_shutdown();
return _ecore_win32_init_count;
}
/**
* @brief Retrieve the depth of the screen.
*
* @return The depth of the screen.
*
* This function returns the depth of the screen. If an error occurs,
* it returns 0.
*/
EAPI int
ecore_win32_screen_depth_get()
{
HDC dc;
int depth;
INF("getting screen depth");
dc = GetDC(NULL);
if (!dc)
{
ERR("GetDC() failed");
return 0;
}
depth = GetDeviceCaps(dc, BITSPIXEL);
if (!ReleaseDC(NULL, dc))
{
ERR("ReleaseDC() failed (device context not released)");
}
return depth;
}
/**
* @brief Sets the timeout for a double and triple clicks to be flagged.
*
* @param t The time in seconds.
*
* This function sets the time @p t between clicks before the
* double_click flag is set in a button down event. If 3 clicks occur
* within double this time, the triple_click flag is also set.
*/
EAPI void
ecore_win32_double_click_time_set(double t)
{
if (t < 0.0) t = 0.0;
_ecore_win32_double_click_time = t;
}
/**
* @brief Retrieve the double and triple click flag timeout.
*
* @return The timeout for double clicks in seconds.
*
* This function returns the double clicks in seconds. If
* ecore_win32_double_click_time_set() has not been called, the
* default value is returned. See ecore_win32_double_click_time_set()
* for more informations.
*/
EAPI double
ecore_win32_double_click_time_get(void)
{
return _ecore_win32_double_click_time;
}
/**
* @brief Return the last event time.
*
* @return The last envent time.
*
* This function returns the last event time.
*/
EAPI unsigned long
ecore_win32_current_time_get(void)
{
return _ecore_win32_event_last_time;
}
/**
* @}
*/
| 32.470238 | 123 | 0.51428 | [
"object"
] |
3eea6fd1c1572af7501c7e1ca41a2b89cc86d654 | 40,829 | c | C | esp32/modugfx.c | meneerhenk/micropython-esp32 | 76635bf83bda1a27bdfd48f9b6e0e592121d9271 | [
"MIT"
] | 12 | 2017-06-10T14:51:20.000Z | 2019-04-22T18:21:59.000Z | esp32/modugfx.c | meneerhenk/micropython-esp32 | 76635bf83bda1a27bdfd48f9b6e0e592121d9271 | [
"MIT"
] | 89 | 2017-06-09T20:57:27.000Z | 2018-03-06T19:54:04.000Z | esp32/modugfx.c | HackerHotel/micropython-esp32 | 5dbf3e7e6af454fc0a26ff2a281718c4b353d49a | [
"MIT"
] | 22 | 2017-05-31T20:56:16.000Z | 2020-01-21T11:45:49.000Z | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* SHA2017 Badge Firmware https://wiki.sha2017.org/w/Projects:Badge/MicroPython
*
* Based on work by EMF for their TiLDA MK3 badge
* https://github.com/emfcamp/micropython/tree/tilda-master/stmhal
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Paul Sokolovsky
* Copyright (c) 2016 Damien P. George
* Copyright (c) 2017 Anne Jan Brouwer
*
* 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 <stdbool.h>
#include <stdio.h>
#ifndef UNIX
#include "board_framebuffer.h"
#else
#include "badge_eink.h"
uint8_t target_lut;
#endif
#include "ginput_lld_toggle_config.h"
#include <stdint.h>
#include <badge_button.h>
#include "modugfx.h"
#include "gfxconf.h"
#define MF_RLEFONT_INTERNALS
#include <mcufont.h>
#include <string.h>
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/runtime.h"
#include "ugfx_widgets.h"
#define EMU_EINK_SCREEN_DELAY_MS 500
typedef struct _ugfx_obj_t { mp_obj_base_t base; } ugfx_obj_t;
extern bool ugfx_screen_flipped;
static orientation_t get_orientation(int a){
if (a == 90)
return GDISP_ROTATE_90;
else if (a == 180)
return GDISP_ROTATE_180;
else if (a == 270)
return GDISP_ROTATE_270;
else
return GDISP_ROTATE_0;
}
// Our default style - a white background theme
const GWidgetStyle BWWhiteWidgetStyle = {
White, // window background
Black, // focused
// enabled color set
{
Black, // text
Black, // edge
White, // fill
Black // progress - active area
},
// disabled color set
{
Black, // text
White, // edge
White, // fill
White // progress - active area
},
// pressed color set
{
White, // text
White, // edge
Black, // fill
Black // progress - active area
}
};
STATIC mp_obj_t ugfx_init(void) {
gwinSetDefaultFont(gdispOpenFont(gdispListFonts()->font->short_name));
gwinSetDefaultStyle(&BWWhiteWidgetStyle, FALSE);
gfxInit();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_init_obj, ugfx_init);
STATIC mp_obj_t ugfx_deinit(void) {
gfxDeinit();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_deinit_obj, ugfx_deinit);
// LUT stettings
STATIC mp_obj_t ugfx_set_lut(mp_obj_t selected_lut) {
int lut = mp_obj_get_int(selected_lut);
if (lut >= 0 && lut <= BADGE_EINK_LUT_MAX) {
target_lut = lut;
} else if (lut >= 0xf0 && lut <= 0xff) {
target_lut = lut;
} else {
mp_raise_msg(&mp_type_ValueError, "invalid LUT");
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(ugfx_set_lut_obj, ugfx_set_lut);
STATIC mp_obj_t ugfx_get_lut() {
return mp_obj_new_int(target_lut);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_get_lut_obj, ugfx_get_lut);
/// \method set_orientation(a)
///
/// Set orientation to 0, 90, 180 or 270 degrees
///
STATIC mp_obj_t ugfx_set_orientation(mp_uint_t n_args, const mp_obj_t *args) {
if (n_args > 0){
int a = mp_obj_get_int(args[0]);
a %= 360;
if (a >= 180) {
ugfx_screen_flipped = true;
a -= 180;
}
gdispSetOrientation(get_orientation(a));
}
int a = gdispGetOrientation();
if (ugfx_screen_flipped)
a += 180;
a %= 360;
return mp_obj_new_int(a);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_set_orientation_obj, 0, 1, ugfx_set_orientation);
/// \method width()
///
/// Gets current width of the screen in pixels
///
STATIC mp_obj_t ugfx_width(void) {
return mp_obj_new_int(gdispGetWidth());
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_width_obj, ugfx_width);
/// \method height()
///
/// Gets current width of the screen in pixels
///
STATIC mp_obj_t ugfx_height(void) {
return mp_obj_new_int(gdispGetHeight());
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_height_obj, ugfx_height);
/// \method get_pixel()
///
/// Gets the colour of the given pixel at (x,y)
///
STATIC mp_obj_t ugfx_get_pixel(mp_obj_t x_in, mp_obj_t y_in) {
// extract arguments
int x = mp_obj_get_int(x_in);
int y = mp_obj_get_int(y_in);
return mp_obj_new_int(gdispGetPixelColor(x,y));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(ugfx_get_pixel_obj, ugfx_get_pixel);
/// \method set_default_font()
///
/// Sets the default font used by widgets.
/// Note, it is only necessary to use a font object if font scaling is used, since
/// in this case memory will need to be cleared once the scaled font is no longer required
///
STATIC mp_obj_t ugfx_set_default_font(mp_obj_t font_obj) {
ugfx_font_obj_t *fo = font_obj;
if (MP_OBJ_IS_TYPE(font_obj, &ugfx_font_type)){
gwinSetDefaultFont(fo->font);
}else if (MP_OBJ_IS_STR(font_obj)){
const char *file = mp_obj_str_get_str(font_obj);
gwinSetDefaultFont(gdispOpenFont(file));
/*}else if (MP_OBJ_IS_INT(font_obj)){*/
/*if (mp_obj_get_int(font_obj) < sizeof(font_list)/sizeof(char*)){*/
/*gwinSetDefaultFont(gdispOpenFont(font_list[mp_obj_get_int(font_obj)]));*/
/*}*/
/*else*/
/*nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid font index"));*/
/*}*/
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(ugfx_set_default_font_obj, ugfx_set_default_font);
/// \method set_default_style()
///
/// Sets the default style used by widgets.
///
STATIC mp_obj_t ugfx_set_default_style(mp_obj_t style_obj) {
ugfx_style_obj_t *st = style_obj;
if (MP_OBJ_IS_TYPE(style_obj, &ugfx_style_type))
gwinSetDefaultStyle(&(st->style),FALSE);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(ugfx_set_default_style_obj, ugfx_set_default_style);
/// \method send_tab()
///
/// Sends a 'tab' signal to cycle through focus.
///
STATIC mp_obj_t ugfx_send_tab(void) {
GSourceListener *psl=0;
GEventKeyboard *pe;
while ((psl = geventGetSourceListener(ginputGetKeyboard(GKEYBOARD_ALL_INSTANCES), psl))){
pe = (GEventKeyboard *)geventGetEventBuffer(psl);
pe->type = GEVENT_KEYBOARD;
pe->bytecount = 1;
pe->c[0] = GKEY_TAB;
geventSendEvent(psl);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_send_tab_obj, ugfx_send_tab);
// PRIMITIVES
/// \method clear(color=ugfx.WHITE)
///
/// Clear screen
///
STATIC mp_obj_t ugfx_clear(mp_uint_t n_args, const mp_obj_t *args) {
int color = n_args == 0 ? White : mp_obj_get_int(args[0]);
gdispFillArea(0, 0, gdispGetWidth(), gdispGetHeight(), color);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_clear_obj, 0, 1, ugfx_clear);
/// \method flush()
///
/// Flush the display buffer to the screen
/// Optional LUT
///
STATIC mp_obj_t ugfx_flush(mp_uint_t n_args, const mp_obj_t *args) {
#ifdef UNIX
mp_hal_delay_ms(EMU_EINK_SCREEN_DELAY_MS);
#endif
uint8_t target_lut_backup = target_lut;
if (n_args == 1) {
ugfx_set_lut(args[0]);
}
gdispFlush();
target_lut = target_lut_backup;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_flush_obj, 0, 1, ugfx_flush);
/// \method get_char_width(char, font)
///
/// Get length in pixels of given character font combination.
///
STATIC mp_obj_t ugfx_get_char_width(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
mp_uint_t len;
const uint16_t data = mp_obj_get_int(args[0]);
const char *font = mp_obj_str_get_data(args[1], &len);
return mp_obj_new_int(gdispGetCharWidth(data, gdispOpenFont(font)));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_get_char_width_obj, 2, 2,
ugfx_get_char_width);
/// \method get_string_width(str, font)
///
/// Get length in pixels of given text font combination.
///
STATIC mp_obj_t ugfx_get_string_width(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
mp_uint_t len;
const char *data = mp_obj_str_get_data(args[0], &len);
const char *font = mp_obj_str_get_data(args[1], &len);
return mp_obj_new_int(gdispGetStringWidth(data, gdispOpenFont(font)));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_get_string_width_obj, 2, 2,
ugfx_get_string_width);
/// \method char(x, y, char, font, colour)
///
/// Draw the given character to the position `(x, y)` using the given font and
/// colour.
///
STATIC mp_obj_t ugfx_char(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
mp_uint_t len;
const uint16_t data = mp_obj_get_int(args[2]);
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int col = mp_obj_get_int(args[4]);
const char *font = mp_obj_str_get_data(args[3], &len);
gdispDrawChar(x0, y0, data, gdispOpenFont(font), col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_char_obj, 5, 5, ugfx_char);
/// \method text(x, y, str, colour)
///
/// Draw the given text to the position `(x, y)` using the given colour.
///
STATIC mp_obj_t ugfx_text(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
//ugfx_obj_t *self = args[0];
mp_uint_t len;
const char *data = mp_obj_str_get_data(args[2], &len);
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int col = mp_obj_get_int(args[3]);
gdispDrawString(x0, y0, data, gwinGetDefaultFont(), col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_text_obj, 4, 4, ugfx_text);
/// \method string(x, y, str, font, colour)
///
/// Draw the given text to the position `(x, y)` using the given font and
/// colour.
///
STATIC mp_obj_t ugfx_string(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
mp_uint_t len;
const char *data = mp_obj_str_get_data(args[2], &len);
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int col = mp_obj_get_int(args[4]);
const char *font = mp_obj_str_get_data(args[3], &len);
gdispDrawString(x0, y0, data, gdispOpenFont(font), col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_string_obj, 5, 5, ugfx_string);
/// \method string_box(x, y, a, b, str, font, colour, justify)
///
/// Draw the given text in a box at position `(x, y)` with lengths a, b
/// using the given font and colour.
///
STATIC mp_obj_t ugfx_string_box(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
mp_uint_t len;
const char *data = mp_obj_str_get_data(args[4], &len);
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int x1 = mp_obj_get_int(args[2]);
int y1 = mp_obj_get_int(args[3]);
int col = mp_obj_get_int(args[6]);
const char *font = mp_obj_str_get_data(args[5], &len);
justify_t justify = mp_obj_get_int(args[7]);
gdispDrawStringBox(x0, y0, x1, y1, data, gdispOpenFont(font), col, justify);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_string_box_obj, 8, 8,
ugfx_string_box);
/// \method pixel(x, y, colour)
///
/// Draw a pixel at (x,y) using the given colour.
///
STATIC mp_obj_t ugfx_pixel(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int col = mp_obj_get_int(args[2]);
gdispDrawPixel(x0, y0, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_pixel_obj, 3, 3, ugfx_pixel);
/// \method line(x1, y1, x2, y2, colour)
///
/// Draw a line from (x1,y1) to (x2,y2) using the given colour.
///
STATIC mp_obj_t ugfx_line(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int x1 = mp_obj_get_int(args[2]);
int y1 = mp_obj_get_int(args[3]);
int col = mp_obj_get_int(args[4]);
gdispDrawLine(x0, y0, x1, y1, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_line_obj, 5, 5, ugfx_line);
/// \method thickline(x1, y1, x2, y2, colour, width, round)
///
/// Draw a line with a given thickness from (x1,y1) to (x2,y2) using the given
/// colour. Option to round the ends
///
STATIC mp_obj_t ugfx_thickline(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int x1 = mp_obj_get_int(args[2]);
int y1 = mp_obj_get_int(args[3]);
int col = mp_obj_get_int(args[4]);
int width = mp_obj_get_int(args[5]);
bool rnd = (mp_obj_get_int(args[6]) != 0);
gdispDrawThickLine(x0, y0, x1, y1, col, width, rnd);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_thickline_obj, 7, 7,
ugfx_thickline);
/// \method arc(x1, y1, r, angle1, angle2, colour)
///
/// Draw an arc having a centre point at (x1,y1), radius r, using the given
/// colour.
///
STATIC mp_obj_t ugfx_arc(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int r = mp_obj_get_int(args[2]);
int col = mp_obj_get_int(args[5]);
int a1 = mp_obj_get_int(args[3]);
int a2 = mp_obj_get_int(args[4]);
gdispDrawArc(x0, y0, r, a1, a2, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_arc_obj, 6, 6, ugfx_arc);
/// \method fill_arc(x1, y1, r, angle1, angle2, colour)
///
/// Fill an arc having a centre point at (x1,y1), radius r, using the given
/// colour.
///
STATIC mp_obj_t ugfx_fill_arc(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int r = mp_obj_get_int(args[2]);
int col = mp_obj_get_int(args[5]);
int a1 = mp_obj_get_int(args[3]);
int a2 = mp_obj_get_int(args[4]);
gdispFillArc(x0, y0, r, a1, a2, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_fill_arc_obj, 6, 6,
ugfx_fill_arc);
/// \method circle(x1, y1, r, colour)
///
/// Draw a circle having a centre point at (x1,y1), radius r, using the given
/// colour.
///
STATIC mp_obj_t ugfx_circle(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int r = mp_obj_get_int(args[2]);
int col = mp_obj_get_int(args[3]);
gdispDrawCircle(x0, y0, r, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_circle_obj, 4, 4, ugfx_circle);
/// \method fill_circle(x1, y1, r, colour)
///
/// Fill a circle having a centre point at (x1,y1), radius r, using the given
/// colour.
///
STATIC mp_obj_t ugfx_fill_circle(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int r = mp_obj_get_int(args[2]);
int col = mp_obj_get_int(args[3]);
gdispFillCircle(x0, y0, r, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_fill_circle_obj, 4, 4,
ugfx_fill_circle);
/// \method ellipse(x1, y1, a, b, colour)
///
/// Draw a ellipse having a centre point at (x1,y1), lengths a,b, using the
/// given colour.
///
STATIC mp_obj_t ugfx_ellipse(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int a = mp_obj_get_int(args[2]);
int b = mp_obj_get_int(args[3]);
int col = mp_obj_get_int(args[4]);
gdispDrawEllipse(x0, y0, a, b, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_ellipse_obj, 5, 5,
ugfx_ellipse);
/// \method fill_ellipse(x1, y1, a, b, colour)
///
/// Fill a ellipse having a centre point at (x1,y1), lengths a,b, using the
/// given colour.
///
STATIC mp_obj_t ugfx_fill_ellipse(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int a = mp_obj_get_int(args[2]);
int b = mp_obj_get_int(args[3]);
int col = mp_obj_get_int(args[4]);
gdispFillEllipse(x0, y0, a, b, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_fill_ellipse_obj, 5, 5,
ugfx_fill_ellipse);
/// \method polygon(x1, y1, array, colour)
///
/// Draw a polygon starting at (x1,y1), using the array of points, using the
/// given colour.
///
STATIC mp_obj_t ugfx_polygon(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int col = mp_obj_get_int(args[3]);
point ar[20];
mp_obj_t *mp_arr;
mp_obj_t *mp_arr2;
size_t len;
size_t len2;
mp_obj_get_array(args[2], &len, &mp_arr);
if (len <= 20) {
int i, j;
j = 0;
for (i = 0; i < len; i++) {
mp_obj_get_array(mp_arr[i], &len2, &mp_arr2);
if (len2 == 2) {
point p = {mp_obj_get_int(mp_arr2[0]), mp_obj_get_int(mp_arr2[1])};
ar[j++] = p;
}
}
gdispDrawPoly(x0, y0, ar, j, col);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_polygon_obj, 4, 4,
ugfx_polygon);
/// \method fill_polygon(x1, y1, array, colour)
///
/// Fill a polygon starting at (x1,y1), using the array of points, using the
/// given colour.
///
STATIC mp_obj_t ugfx_fill_polygon(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int col = mp_obj_get_int(args[3]);
point ar[20];
mp_obj_t *mp_arr;
mp_obj_t *mp_arr2;
size_t len;
size_t len2;
mp_obj_get_array(args[2], &len, &mp_arr);
if (len <= 20) {
int i, j;
j = 0;
for (i = 0; i < len; i++) {
mp_obj_get_array(mp_arr[i], &len2, &mp_arr2);
if (len2 == 2) {
point p = {mp_obj_get_int(mp_arr2[0]), mp_obj_get_int(mp_arr2[1])};
ar[j++] = p;
}
}
gdispFillConvexPoly(x0, y0, ar, i, col);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_fill_polygon_obj, 4, 4,
ugfx_fill_polygon);
/// \method area(x, y, a, b, colour)
///
/// Fill area from (x,y), with lengths a,b, using the given colour.
///
STATIC mp_obj_t ugfx_area(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int a = mp_obj_get_int(args[2]);
int b = mp_obj_get_int(args[3]);
int col = mp_obj_get_int(args[4]);
gdispFillArea(x0, y0, a, b, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_area_obj, 5, 5, ugfx_area);
/// \method box(x, y, a, b, colour)
///
/// Draw a box from (x,y), with lengths a,b, using the given colour.
///
STATIC mp_obj_t ugfx_box(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int a = mp_obj_get_int(args[2]);
int b = mp_obj_get_int(args[3]);
int col = mp_obj_get_int(args[4]);
gdispDrawBox(x0, y0, a, b, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_box_obj, 5, 5, ugfx_box);
/// \method rounded_box(x, y, a, b, colour)
///
/// Draw a box from (x,y), with lengths a,b, rounded corners with radius r,
/// using the given colour.
///
STATIC mp_obj_t ugfx_rounded_box(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int a = mp_obj_get_int(args[2]);
int b = mp_obj_get_int(args[3]);
int r = mp_obj_get_int(args[4]);
int col = mp_obj_get_int(args[5]);
gdispDrawRoundedBox(x0, y0, a, b, r, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_rounded_box_obj, 6, 6,
ugfx_rounded_box);
/// \method fill_rounded_box(x, y, a, b, colour)
///
/// Draw a box from (x,y), with lengths a,b, rounded corners with radius r,
/// using the given colour.
///
STATIC mp_obj_t ugfx_fill_rounded_box(mp_uint_t n_args, const mp_obj_t *args) {
// extract arguments
// ugfx_obj_t *self = args[0];
int x0 = mp_obj_get_int(args[0]);
int y0 = mp_obj_get_int(args[1]);
int a = mp_obj_get_int(args[2]);
int b = mp_obj_get_int(args[3]);
int r = mp_obj_get_int(args[4]);
int col = mp_obj_get_int(args[5]);
gdispFillRoundedBox(x0, y0, a, b, r, col);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_fill_rounded_box_obj, 6, 6,
ugfx_fill_rounded_box);
// Image
/// \method display_image(x, y, image_object)
///
STATIC mp_obj_t ugfx_display_image(mp_uint_t n_args, const mp_obj_t *args){
// extract arguments
//pyb_ugfx_obj_t *self = args[0];
int x = mp_obj_get_int(args[0]);
int y = mp_obj_get_int(args[1]);
mp_obj_t img_obj = args[2];
gdispImage imo;
gdispImage *iptr;
if (img_obj != mp_const_none) {
if (MP_OBJ_IS_STR(img_obj)){
const char *img_str = mp_obj_str_get_str(img_obj);
gdispImageError er = gdispImageOpenFile(&imo, img_str);
if (er != 0){
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Error opening file"));
return mp_const_none;
}
iptr = &imo;
}
else if (MP_OBJ_IS_TYPE(img_obj, &ugfx_image_type))
iptr = &(((ugfx_image_obj_t*)img_obj)->thisImage);
else{
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "img argument needs to be be a Image or String type"));
return mp_const_none;
}
coord_t swidth, sheight;
// Get the display dimensions
swidth = gdispGetWidth();
sheight = gdispGetHeight();
// if (n_args > 3)
// set_blit_rotation(get_orientation(mp_obj_get_int(args[3])));
int err = gdispImageDraw(iptr, x, y, swidth, sheight, 0, 0);
// set_blit_rotation(GDISP_ROTATE_0);
if (MP_OBJ_IS_STR(img_obj))
gdispImageClose(&imo);
print_image_error(err); // TODO
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_display_image_obj, 3, 3, ugfx_display_image);
// INPUT
/// \method poll()
///
/// calls gfxYield, which will handle widget redrawing when for inputs.
/// Register as follows:
/// tim = pyb.Timer(3)
/// tim.init(freq=60)
/// tim.callback(lambda t:ugfx.poll())
///
STATIC mp_obj_t ugfx_poll(void) {
gfxYield();
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_poll_obj, ugfx_poll);
// callback system
STATIC mp_obj_t button_callbacks[1+BADGE_BUTTONS];
STATIC GListener button_listeners[1+BADGE_BUTTONS];
void ugfx_ginput_callback_handler(void *param, GEvent *pe){
size_t button = (size_t) param;
if(button_callbacks[button] != mp_const_none){
GEventToggle *toggle = (GEventToggle*) pe;
mp_sched_schedule(button_callbacks[button], mp_obj_new_bool(toggle->on ? 1 : 0));
}
}
/// \method ugfx_input_init()
///
/// Enable callbacks for button events
///
STATIC mp_obj_t ugfx_input_init(void) {
for(size_t i = 1; i <= BADGE_BUTTONS; i++){
button_callbacks[i] = mp_const_none;
geventListenerInit(&button_listeners[i]);
button_listeners[i].callback = ugfx_ginput_callback_handler;
button_listeners[i].param = (void*) i;
geventAttachSource(&button_listeners[i], ginputGetToggle(i), GLISTEN_TOGGLE_ON|GLISTEN_TOGGLE_OFF);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_input_init_obj, ugfx_input_init);
/// \method ugfx_input_attach(button, callback)
///
/// Register callbacks for button events. This overwrites any previous callback registered for this button.
///
STATIC mp_obj_t ugfx_input_attach(mp_uint_t n_args, const mp_obj_t *args) {
uint8_t button = mp_obj_get_int(args[0]);
button_callbacks[button] = args[1];
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_input_attach_obj, 2, 2, ugfx_input_attach);
// DEMO
STATIC mp_obj_t ugfx_demo(mp_obj_t hacking) {
font_t robotoBlackItalic;
font_t permanentMarker;
robotoBlackItalic = gdispOpenFont("Roboto_BlackItalic24");
permanentMarker = gdispOpenFont("PermanentMarker36");
uint16_t hackingWidth = gdispGetStringWidth(mp_obj_str_get_str(hacking), permanentMarker);
gdispClear(White);
gdispDrawStringBox(0, 6, 296, 40, "STILL", robotoBlackItalic, Black, justifyCenter);
gdispDrawStringBox(0, 42, 276, 40, mp_obj_str_get_str(hacking), permanentMarker, Black, justifyCenter);
// underline:
gdispDrawLine(
296/2 - hackingWidth/2 - 14,
42 + 36 + 2,
296/2 + hackingWidth/2 + 14,
42 + 36 + 2,
Black);
// cursor:
gdispDrawLine(
276/2 + hackingWidth/2 + 2 + 3,
42 + 4,
276/2 + hackingWidth/2 + 2,
42 + 36,
Black);
gdispDrawStringBox(0, 82, 296, 40, "Anyway", robotoBlackItalic, Black, justifyCenter);
#ifdef UNIX
mp_hal_delay_ms(EMU_EINK_SCREEN_DELAY_MS);
#endif
uint8_t target_lut_backup = target_lut;
target_lut = 0xff;
gdispFlush();
target_lut = target_lut_backup;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(ugfx_demo_obj, ugfx_demo);
STATIC mp_obj_t ugfx_fonts_list(void) {
mp_obj_t list = mp_obj_new_list(0, NULL);;
const struct mf_font_list_s *f = gdispListFonts();
while (f){
mp_obj_list_append(list, mp_obj_new_str(f->font->short_name, strlen(f->font->short_name), false));
f = f->next;
}
return list;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(ugfx_fonts_list_obj, ugfx_fonts_list);
#define store_dict_str(dict, field, contents) mp_obj_dict_store(dict, mp_obj_new_str(field, strlen(field), false), mp_obj_new_str(contents, strlen(contents), false))
#define store_dict_int(dict, field, contents) mp_obj_dict_store(dict, mp_obj_new_str(field, strlen(field), false), mp_obj_new_int(contents));
#define store_dict_foo(dict, field, contents) mp_obj_dict_store(dict, mp_obj_new_str(field, strlen(field), false), contents);
STATIC mp_obj_t ugfx_fonts_dump(mp_uint_t n_args, const mp_obj_t *args) {
mp_uint_t len;
const char *font = mp_obj_str_get_data(args[0], &len);
struct mf_rlefont_s* f = (struct mf_rlefont_s*) gdispOpenFont(font);
if(strcmp(f->font.short_name, font)){
return mp_const_none;
}
mp_obj_t dict_out = mp_obj_new_dict(0);
mp_obj_dict_t *dict = MP_OBJ_TO_PTR(dict_out);
mp_obj_dict_init(dict, 21);
store_dict_str(dict, "short_name", f->font.short_name);
store_dict_str(dict, "full_name", f->font.full_name);
store_dict_int(dict, "width", f->font.width);
store_dict_int(dict, "height", f->font.height);
store_dict_int(dict, "min_x_advance", f->font.min_x_advance);
store_dict_int(dict, "max_x_advance", f->font.max_x_advance);
store_dict_int(dict, "baseline_x", f->font.baseline_x);
store_dict_int(dict, "baseline_y", f->font.baseline_y);
store_dict_int(dict, "line_height", f->font.line_height);
store_dict_int(dict, "flags", f->font.flags);
store_dict_int(dict, "fallback_character", f->font.fallback_character);
mp_obj_t ranges = mp_obj_new_list(0, NULL);;
for (size_t i = 0; i < f->char_range_count; i++){
const struct mf_rlefont_char_range_s *range = &f->char_ranges[i];
mp_obj_t range_dict_out = mp_obj_new_dict(0);
mp_obj_dict_t *range_dict = MP_OBJ_TO_PTR(range_dict_out);
store_dict_int(range_dict, "first_char", range->first_char);
store_dict_int(range_dict, "char_count", range->char_count);
store_dict_foo(range_dict, "glyph_offsets", mp_obj_new_bytes((uint8_t*) range->glyph_offsets, 2*range->char_count+2));
store_dict_foo(range_dict, "glyph_data", mp_obj_new_bytes(range->glyph_data, (range->glyph_offsets[range->char_count])));
mp_obj_list_append(ranges, range_dict_out);
}
store_dict_foo(dict, "dictionary_offsets", mp_obj_new_bytes((uint8_t*) f->dictionary_offsets, 2*(f->dict_entry_count)+2));
store_dict_foo(dict, "dictionary_data", mp_obj_new_bytes(f->dictionary_data, f->dictionary_offsets[f->dict_entry_count]));
store_dict_int(dict, "rle_entry_count", f->rle_entry_count);
store_dict_int(dict, "dict_entry_count", f->dict_entry_count);
store_dict_int(dict, "char_range_count", f->char_range_count);
store_dict_foo(dict, "char_ranges", ranges);
return dict_out;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_fonts_dump_obj, 1, 1, ugfx_fonts_dump);
STATIC mp_obj_t ugfx_fonts_load(mp_uint_t n_args, const mp_obj_t *args) {
struct dynamic_mf_rlefont_char_range_s{
uint16_t first_char;
uint16_t char_count;
uint16_t *glyph_offsets;
uint8_t *glyph_data;
};
struct dynamic_mf_font_s{
const char *full_name;
const char *short_name;
uint8_t width;
uint8_t height;
uint8_t min_x_advance;
uint8_t max_x_advance;
uint8_t baseline_x;
uint8_t baseline_y;
uint8_t line_height;
uint8_t flags;
uint16_t fallback_character;
uint8_t (*character_width)(const struct mf_font_s *font, uint16_t character);
uint8_t (*render_character)(const struct mf_font_s *font,
int16_t x0, int16_t y0,
uint16_t character,
mf_pixel_callback_t callback,
void *state);
};
struct dynamic_mf_rlefont_s{
struct dynamic_mf_font_s font;
uint8_t version;
uint8_t *dictionary_data;
uint16_t *dictionary_offsets;
uint8_t rle_entry_count;
uint8_t dict_entry_count;
uint16_t char_range_count;
struct dynamic_mf_rlefont_char_range_s *char_ranges;
};
mp_obj_dict_t *dict = MP_OBJ_TO_PTR(args[0]);
struct dynamic_mf_rlefont_s* f = gfxAlloc(sizeof(struct mf_rlefont_s));
if(f){
f->font.short_name = mp_obj_str_get_str(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_short_name)));
if(gdispOpenFont(f->font.short_name)->short_name == f->font.short_name){
// font already loaded
return mp_obj_new_bool(0);
}
f->font.full_name = mp_obj_str_get_str(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_full_name)));
f->font.width = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_width)));
f->font.height = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_height)));
f->font.min_x_advance = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_min_x_advance)));
f->font.max_x_advance = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_max_x_advance)));
f->font.baseline_x = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_baseline_x)));
f->font.baseline_y = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_baseline_y)));
f->font.line_height = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_line_height)));
f->font.flags = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_flags))) | 0xc0; // FONT_FLAG_DYNAMIC|FONT_FLAG_UNLISTED
f->font.fallback_character = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_fallback_character)));
f->rle_entry_count = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_rle_entry_count)));
f->dict_entry_count = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_dict_entry_count)));
f->char_range_count = mp_obj_get_int(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_char_range_count)));
f->char_ranges = gfxAlloc(f->char_range_count * sizeof(struct mf_rlefont_s));
mp_obj_t ranges = mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_char_ranges));
size_t len;
uint8_t * data;
for (size_t i = 0; i < f->char_range_count; i++){
mp_obj_t * items;
size_t idx;
mp_obj_list_get(ranges, &idx, &items);
mp_obj_t range = items[0];
f->char_ranges[i].first_char = mp_obj_get_int(mp_obj_dict_get(range, MP_OBJ_NEW_QSTR(MP_QSTR_first_char)));
f->char_ranges[i].char_count = mp_obj_get_int(mp_obj_dict_get(range, MP_OBJ_NEW_QSTR(MP_QSTR_char_count)));
data = (uint8_t*) mp_obj_str_get_data(mp_obj_dict_get(range, MP_OBJ_NEW_QSTR(MP_QSTR_glyph_offsets)), &len);
f->char_ranges[i].glyph_offsets = gfxAlloc(len);
memcpy(f->char_ranges[i].glyph_offsets, data, len-2);
data = (uint8_t*) mp_obj_str_get_data(mp_obj_dict_get(range, MP_OBJ_NEW_QSTR(MP_QSTR_glyph_data)), &len);
f->char_ranges[i].glyph_offsets[f->char_ranges[i].char_count] = len;
f->char_ranges[i].glyph_data = gfxAlloc(len);
memcpy(f->char_ranges[i].glyph_data, data, len);
}
data = (uint8_t*) mp_obj_str_get_data(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_dictionary_offsets)), &len);
f->dictionary_offsets = gfxAlloc(len);
memcpy(f->dictionary_offsets, data, len-2);
size_t dict_len;
data = (uint8_t*) mp_obj_str_get_data(mp_obj_dict_get(dict, MP_OBJ_NEW_QSTR(MP_QSTR_dictionary_data)), &dict_len);
f->dictionary_offsets[(len/2)-1] = dict_len;
f->dictionary_data = gfxAlloc(dict_len);
memcpy(f->dictionary_data, data, dict_len);
f->font.character_width = &mf_rlefont_character_width;
f->font.render_character = &mf_rlefont_render_character;
gdispAddFont((font_t)f);
}
return mp_obj_new_bool(1);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ugfx_fonts_load_obj, 1, 1, ugfx_fonts_load);
// Module globals
STATIC const mp_rom_map_elem_t ugfx_module_globals_table[] = {
{MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ugfx)},
{MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&ugfx_init_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&ugfx_deinit_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_BLACK), MP_OBJ_NEW_SMALL_INT(Black)},
{MP_OBJ_NEW_QSTR(MP_QSTR_WHITE), MP_OBJ_NEW_SMALL_INT(White)},
{MP_OBJ_NEW_QSTR(MP_QSTR_justifyLeft), MP_OBJ_NEW_SMALL_INT(justifyLeft)},
{MP_OBJ_NEW_QSTR(MP_QSTR_justifyCenter),
MP_OBJ_NEW_SMALL_INT(justifyCenter)},
{MP_OBJ_NEW_QSTR(MP_QSTR_justifyRight), MP_OBJ_NEW_SMALL_INT(justifyR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T)},
{MP_OBJ_NEW_QSTR(MP_QSTR_LUT_MAX), MP_OBJ_NEW_SMALL_INT(BADGE_EINK_LUT_MAX)},
{MP_OBJ_NEW_QSTR(MP_QSTR_GREYSCALE), MP_OBJ_NEW_SMALL_INT(0xff)},
{MP_OBJ_NEW_QSTR(MP_QSTR_set_lut), (mp_obj_t)&ugfx_set_lut_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_get_lut), (mp_obj_t)&ugfx_get_lut_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_clear), (mp_obj_t)&ugfx_clear_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_flush), (mp_obj_t)&ugfx_flush_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_poll), (mp_obj_t)&ugfx_poll_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_get_string_width),
(mp_obj_t)&ugfx_get_string_width_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_get_char_width),
(mp_obj_t)&ugfx_get_char_width_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_char), (mp_obj_t)&ugfx_char_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_string), (mp_obj_t)&ugfx_string_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_text), (mp_obj_t)&ugfx_text_obj },
{MP_OBJ_NEW_QSTR(MP_QSTR_string_box), (mp_obj_t)&ugfx_string_box_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_get_pixel), (mp_obj_t)&ugfx_get_pixel_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_pixel), (mp_obj_t)&ugfx_pixel_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_line), (mp_obj_t)&ugfx_line_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_box), (mp_obj_t)&ugfx_box_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_rounded_box), (mp_obj_t)&ugfx_rounded_box_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_fill_rounded_box),
(mp_obj_t)&ugfx_fill_rounded_box_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_area), (mp_obj_t)&ugfx_area_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_thickline), (mp_obj_t)&ugfx_thickline_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_circle), (mp_obj_t)&ugfx_circle_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_fill_circle), (mp_obj_t)&ugfx_fill_circle_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_ellipse), (mp_obj_t)&ugfx_ellipse_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_fill_ellipse), (mp_obj_t)&ugfx_fill_ellipse_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_arc), (mp_obj_t)&ugfx_arc_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_fill_arc), (mp_obj_t)&ugfx_fill_arc_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_polygon), (mp_obj_t)&ugfx_polygon_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_fill_polygon), (mp_obj_t)&ugfx_fill_polygon_obj},
{ MP_OBJ_NEW_QSTR(MP_QSTR_display_image), (mp_obj_t)&ugfx_display_image_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_orientation), (mp_obj_t)&ugfx_set_orientation_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_width), (mp_obj_t)&ugfx_width_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_height), (mp_obj_t)&ugfx_height_obj },
{MP_OBJ_NEW_QSTR(MP_QSTR_fonts_list), (mp_obj_t)&ugfx_fonts_list_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_fonts_dump), (mp_obj_t)&ugfx_fonts_dump_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_fonts_load), (mp_obj_t)&ugfx_fonts_load_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_input_init), (mp_obj_t)&ugfx_input_init_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_input_attach), (mp_obj_t)&ugfx_input_attach_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_demo), (mp_obj_t)&ugfx_demo_obj},
{ MP_OBJ_NEW_QSTR(MP_QSTR_set_default_font), (mp_obj_t)&ugfx_set_default_font_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_set_default_style), (mp_obj_t)&ugfx_set_default_style_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_send_tab), (mp_obj_t)&ugfx_send_tab_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Button), (mp_obj_t)&ugfx_button_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Container), (mp_obj_t)&ugfx_container_type },
// { MP_OBJ_NEW_QSTR(MP_QSTR_Graph), (mp_obj_t)&ugfx_graph_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Font), (mp_obj_t)&ugfx_font_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_List), (mp_obj_t)&ugfx_list_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Textbox), (mp_obj_t)&ugfx_textbox_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Style), (mp_obj_t)&ugfx_style_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Keyboard), (mp_obj_t)&ugfx_keyboard_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Label), (mp_obj_t)&ugfx_label_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Image), (mp_obj_t)&ugfx_image_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Checkbox), (mp_obj_t)&ugfx_checkbox_type },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Imagebox), (mp_obj_t)&ugfx_imagebox_type },
};
STATIC MP_DEFINE_CONST_DICT(ugfx_module_globals, ugfx_module_globals_table);
const mp_obj_module_t ugfx_module = {
.base = {&mp_type_module}, .globals = (mp_obj_dict_t *)&ugfx_module_globals,
};
| 34.281276 | 165 | 0.71072 | [
"object"
] |
3eebe323fd0d5416c5f6c47e84f5b210231c1c97 | 3,985 | h | C | Engine/Source/Scene/Components/Components.h | jkorn2324/jkornEngine | 5822f2a311ed62e6ca495919872f0f436d300733 | [
"MIT"
] | null | null | null | Engine/Source/Scene/Components/Components.h | jkorn2324/jkornEngine | 5822f2a311ed62e6ca495919872f0f436d300733 | [
"MIT"
] | null | null | null | Engine/Source/Scene/Components/Components.h | jkorn2324/jkornEngine | 5822f2a311ed62e6ca495919872f0f436d300733 | [
"MIT"
] | null | null | null | #pragma once
#include "Source\Transform.h"
#include "Entity.h"
#include "GUID.h"
#include "BehaviorScriptContainer.h"
#include "SceneCamera.h"
#include "EntityHierarchyComponent.h"
#include "LightingComponents.h"
#include "BehaviorScript.h"
#include "AssetReferenceManager.h"
namespace Engine
{
using Transform2DComponent = MathLib::Transform2D;
using Transform3DComponent = MathLib::Transform3D;
class Mesh;
class Texture;
class Material;
class Shader;
struct IDComponent
{
GUID guid;
IDComponent() = default;
IDComponent(const GUID& guid)
: guid(guid) { }
};
struct SpriteComponent
{
AssetRef<Texture> texture;
MathLib::Vector4 color = MathLib::Vector4::One;
bool enabled = true;
explicit SpriteComponent() = default;
explicit SpriteComponent(const MathLib::Vector4& color)
: color(color), texture(), enabled(true) { }
explicit SpriteComponent(const AssetRef<Texture> texture, const MathLib::Vector4& color)
: color(color), texture(texture), enabled(true) { }
explicit SpriteComponent(const AssetRef<Texture> texture)
: color(MathLib::Vector4::One), texture(texture), enabled(true) { }
explicit SpriteComponent(bool enabled)
: color(MathLib::Vector4::One), texture(), enabled(enabled) { }
explicit SpriteComponent(bool enabled, const MathLib::Vector4& color)
: color(color), enabled(enabled), texture() { }
};
struct SceneCameraComponent
{
SceneCamera camera;
bool mainCamera = true;
bool enabled = true;
explicit SceneCameraComponent() = default;
explicit SceneCameraComponent(bool mainCam)
: mainCamera(mainCam), camera() { }
explicit SceneCameraComponent(bool mainCam,
SceneCameraType cameraType)
: mainCamera(mainCam), enabled(true), camera()
{
camera.SetSceneCameraType(cameraType);
}
explicit SceneCameraComponent(bool mainCamera, SceneCameraType type,
const CameraProperties& properties)
: mainCamera(mainCamera), camera(type, properties) { }
SceneCameraComponent(const SceneCameraComponent& component) = default;
};
struct NameComponent
{
std::string name;
explicit NameComponent() : name() { }
explicit NameComponent(const std::string& name)
: name(name) { }
explicit NameComponent(const char* name)
: name(name) { }
};
struct MeshComponent
{
// TODO: Generate a default material.
bool enabled = true;
AssetRef<Mesh> mesh;
AssetRef<Material> material;
explicit MeshComponent()
: mesh(), material() { }
explicit MeshComponent(const AssetRef<Mesh>& mesh, const AssetRef<Material>& material)
: mesh(mesh), material(material) { }
};
class BehaviorComponent
{
public:
BehaviorComponent()
: m_behaviorScriptContainer() { }
BehaviorComponent(const BehaviorComponent& component)
: m_behaviorScriptContainer()
{
if (component.IsValid())
{
m_behaviorScriptContainer = component.m_behaviorScriptContainer;
}
}
BehaviorComponent& operator=(const BehaviorComponent& component)
{
if (component.IsValid())
{
m_behaviorScriptContainer = component.m_behaviorScriptContainer;
}
return *this;
}
bool IsValid() const { return m_behaviorScriptContainer.get() != nullptr; }
BehaviorScriptContainer& Get() { return *m_behaviorScriptContainer.get(); }
const BehaviorScriptContainer& Get() const { return *m_behaviorScriptContainer.get(); }
friend void Copy(const BehaviorComponent& from, BehaviorComponent& to)
{
to.Copy(from);
}
private:
void Copy(const BehaviorComponent& from)
{
if (from.IsValid())
{
for (const auto& behavior : from.m_behaviorScriptContainer->GetBehaviors())
{
m_behaviorScriptContainer->CopyBehavior(behavior);
}
}
}
void Create(Entity& entity)
{
m_behaviorScriptContainer = std::make_shared<BehaviorScriptContainer>(entity);
}
void Destroy()
{
m_behaviorScriptContainer->Deallocate();
}
private:
std::shared_ptr<BehaviorScriptContainer> m_behaviorScriptContainer;
friend class Scene;
};
} | 24.90625 | 90 | 0.723463 | [
"mesh",
"transform"
] |
3eec5b6932e93fbd2aba289dc82787be3dc85999 | 1,047 | h | C | c/meterpreter/source/extensions/mimikatz/modules/mod_cryptong.h | RonKilps/metasploit-payloads | 67c93e6bba6452d8961c451a1cfc88567df1225b | [
"PSF-2.0"
] | 264 | 2015-01-02T10:15:42.000Z | 2022-03-31T06:59:13.000Z | c/meterpreter/source/extensions/mimikatz/modules/mod_cryptong.h | RonKilps/metasploit-payloads | 67c93e6bba6452d8961c451a1cfc88567df1225b | [
"PSF-2.0"
] | 112 | 2015-01-02T01:26:38.000Z | 2021-11-21T02:07:21.000Z | c/meterpreter/source/extensions/mimikatz/modules/mod_cryptong.h | RonKilps/metasploit-payloads | 67c93e6bba6452d8961c451a1cfc88567df1225b | [
"PSF-2.0"
] | 130 | 2015-01-02T05:29:46.000Z | 2022-03-18T19:50:39.000Z | /* Benjamin DELPY `gentilkiwi`
http://blog.gentilkiwi.com
benjamin@gentilkiwi.com
Licence : http://creativecommons.org/licenses/by/3.0/fr/
*/
#pragma once
#include "globdefs.h"
#include <bcrypt.h>
#include <sstream>
class mod_cryptong /* Ref : http://msdn.microsoft.com/en-us/library/aa376210.aspx */
{
public:
static bool getVectorProviders(vector<wstring> * monVectorProviders);
static bool getVectorContainers(vector<wstring> * monVectorContainers, bool isMachine = false);
static bool getHKeyFromName(wstring keyName, NCRYPT_KEY_HANDLE * keyHandle, bool isMachine = false);
static bool getKeySize(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE * provOrCle, DWORD * keySize);
static bool isKeyExportable(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE * provOrCle, bool * isExportable);
static bool getPrivateKey(NCRYPT_KEY_HANDLE maCle, PBYTE * monExport, DWORD * tailleExport, LPCWSTR pszBlobType = LEGACY_RSAPRIVATE_BLOB);
static bool NCryptFreeObject(NCRYPT_HANDLE hObject);
static bool isNcrypt;
static bool justInitCNG(LPCWSTR pszProviderName = NULL);
};
| 41.88 | 139 | 0.794651 | [
"vector"
] |
3ef12993046ab9d2d18def7ad5e6b5ada2f37aa8 | 1,142 | h | C | include/tiramisu/MainPage.h | BHafsa/tiramisu | 555f48f38b7f3460819d1999e7af5c89457a4c58 | [
"MIT"
] | null | null | null | include/tiramisu/MainPage.h | BHafsa/tiramisu | 555f48f38b7f3460819d1999e7af5c89457a4c58 | [
"MIT"
] | null | null | null | include/tiramisu/MainPage.h | BHafsa/tiramisu | 555f48f38b7f3460819d1999e7af5c89457a4c58 | [
"MIT"
] | null | null | null | /** \file
* This file only exists to contain the front-page of the documentation
*/
/** \mainpage Tiramisu Optimization Framework
* Tiramisu is a library that is designed to simplify code optimization and code generation. The user can express his code in the Tiramisu intermediate representation (Tiramisu IR), he can use the Tiramisu API to perform different optimizations and finaly he can generate an LLVM code from the optimized Tiramisu IR.
*
* Tiramisu provides few classes to enable users to represent their program:
* - The \ref tiramisu::function class: a function is composed of multiple computations and a vector of arguments (functions arguments).
* - The \ref tiramisu::computation class: a computation is composed of an expression and an iteration space but is not associated with any memory location.
* - The \ref tiramisu::buffer class: a class to represent memory buffers.
*
* \example tutorials/tutorial_01.cpp
* \example tutorials/tutorial_02.cpp
* \example tutorials/tutorial_03.cpp
* \example tutorials/tutorial_04.cpp
* \example tutorials/tutorial_05.cpp
* \example tutorials/tutorial_06.cpp
*/
| 57.1 | 317 | 0.774956 | [
"vector"
] |
3eff1883870953a3807c3c2129de205c4e842d6c | 2,806 | h | C | code/SDK/include/Maya_17/maya/MTextureEditorDrawInfo.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 1 | 2021-04-26T07:32:34.000Z | 2021-04-26T07:32:34.000Z | code/SDK/include/Maya_17/maya/MTextureEditorDrawInfo.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | null | null | null | code/SDK/include/Maya_17/maya/MTextureEditorDrawInfo.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 3 | 2021-11-01T06:21:26.000Z | 2022-01-08T16:13:23.000Z | #ifndef __MTextureEditorDrawInfo_h
#define __MTextureEditorDrawInfo_h
//-
// ===========================================================================
// Copyright 2018 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
// ===========================================================================
//+
//
// CLASS: MTextureEditorDrawInfo
//
// ****************************************************************************
//
#if defined __cplusplus
// ****************************************************************************
// INCLUDED HEADER FILES
#include <maya/MStatus.h>
#include <maya/MTypes.h>
#include <maya/MObject.h>
#include <maya/M3dView.h>
#include <maya/MDrawRequest.h>
// ****************************************************************************
// DECLARATIONS
class MSelectionTypeSet;
OPENMAYA_MAJOR_NAMESPACE_OPEN
// ****************************************************************************
// CLASS DECLARATION (MTextureEditorDrawInfo)
//! \ingroup OpenMayaUI
//! \brief Drawing state for drawing to the UV texture window with custom
//! shapes.
/*!
This class is used by drawUV method of MPxSurfaceShapeUI to specify
the current UV drawing state for a user defined shape. API users
must override the canDrawUV method on MPxSurfaceShapeUI to recieve
drawUV calls. The only situation where the drawing style can change
is during a selection event. However, selection events are currently
not passed onto the API user. Therefore, most of the functionality
in this class is place holder for future work.
\see MPxSurfaceShapeUI
*/
class OPENMAYAUI_EXPORT MTextureEditorDrawInfo
{
public:
MTextureEditorDrawInfo();
MTextureEditorDrawInfo( const MTextureEditorDrawInfo& in );
virtual ~MTextureEditorDrawInfo();
//! Draw modes
enum DrawingFunction {
kDrawFunctionFirst = 1, //!< Lowest possible enum value
//! Draw wireframe only (default)
kDrawWireframe = kDrawFunctionFirst,
kDrawEverything, //!< Draw vertices, uvs, faces, and edges
kDrawVertexForSelect, //!< Draw vertices for selection
kDrawEdgeForSelect, //!< Draw edges for selection
kDrawFacetForSelect, //!< Draw faces for selection
kDrawUVForSelect, //!< Draw uvs for selection
kDrawFunctionLast = kDrawUVForSelect //!< Highest possible enum value
} ;
DrawingFunction drawingFunction() const;
void setDrawingFunction( DrawingFunction func );
static const char* className();
private:
MTextureEditorDrawInfo( void * in );
void * fData;
};
OPENMAYA_NAMESPACE_CLOSE
#endif /* __cplusplus */
#endif /* _MTextureEditorDrawInfo */
| 31.177778 | 79 | 0.629722 | [
"shape"
] |
4104eddf95248c6336da962b40ab3ad76690073d | 769 | h | C | src/impl/organizeGffRecords.h | illarionovaanastasia/GEAN | b81bbf45dd869ffde2833fd1eb78463d09de45cb | [
"MIT"
] | 34 | 2019-01-17T22:47:17.000Z | 2021-12-20T08:36:44.000Z | src/impl/organizeGffRecords.h | illarionovaanastasia/GEAN | b81bbf45dd869ffde2833fd1eb78463d09de45cb | [
"MIT"
] | 7 | 2019-04-23T02:50:13.000Z | 2021-05-05T07:32:46.000Z | src/impl/organizeGffRecords.h | illarionovaanastasia/GEAN | b81bbf45dd869ffde2833fd1eb78463d09de45cb | [
"MIT"
] | 5 | 2019-03-14T23:05:46.000Z | 2020-08-17T09:14:17.000Z | //
// Created by Baoxing song on 20.10.18.
//
#ifndef ZSDP_ORGANIZEGFFRECORDS_H
#define ZSDP_ORGANIZEGFFRECORDS_H
#include "../model/model.h"
#include "../util/util.h"
#include "./TranscriptUpdateInformation.h"
#include "./checkOrfState.h"
bool exactlySame( Gene & g1, Gene & g2);
void mergeToFirstOne( Gene & g1, Gene & g2);
void updateGeneInformation(std::map<std::string, std::vector<Gene> > & geneMap, NucleotideCodeSubstitutionMatrix & nucleotideCodeSubstitutionMatrix,
const size_t & minIntron, std::map<std::string, Fasta> & querySequences);
void removeDuplication(std::map<std::string, std::vector<Gene> > & geneMap, const size_t & minGene, std::map<std::string, std::set<int32_t>> & toRemove);
#endif //ZSDP_ORGANIZEGFFRECORDS_H
| 40.473684 | 153 | 0.723017 | [
"vector",
"model"
] |
4106ac3a10dadc436ae2f6e40df4b36daf2353ec | 166 | h | C | compiler/Parser.h | ATsahikian/PeProtector | 4e005ea636a5679b82c9e58e09a0de53618896c5 | [
"MIT"
] | 43 | 2016-07-30T13:50:21.000Z | 2021-06-17T22:45:00.000Z | compiler/Parser.h | ATsahikian/pe-protector | 4e005ea636a5679b82c9e58e09a0de53618896c5 | [
"MIT"
] | null | null | null | compiler/Parser.h | ATsahikian/pe-protector | 4e005ea636a5679b82c9e58e09a0de53618896c5 | [
"MIT"
] | 16 | 2016-09-08T09:10:27.000Z | 2020-06-14T00:30:59.000Z | #pragma once
#include <vector>
#include "common\SCommand.h"
namespace NPeProtector {
std::vector<SCommand> parse(std::istream& input);
} // namespace NPeProtector | 18.444444 | 49 | 0.746988 | [
"vector"
] |
410da918fe4c1d265ec3bc48510c5c625bcfb98e | 4,563 | h | C | cpp/test-harness/ta2/test-script.h | nathanawmk/SPARTA | 6eeb28b2dd147088b6e851876b36eeba3e700f16 | [
"BSD-2-Clause"
] | 37 | 2017-06-09T13:55:23.000Z | 2022-01-28T12:51:17.000Z | cpp/test-harness/ta2/test-script.h | nathanawmk/SPARTA | 6eeb28b2dd147088b6e851876b36eeba3e700f16 | [
"BSD-2-Clause"
] | null | null | null | cpp/test-harness/ta2/test-script.h | nathanawmk/SPARTA | 6eeb28b2dd147088b6e851876b36eeba3e700f16 | [
"BSD-2-Clause"
] | 5 | 2017-06-09T13:55:26.000Z | 2021-11-11T03:51:56.000Z | //*****************************************************************
// Copyright 2015 MIT Lincoln Laboratory
// Project: SPAR
// Authors: Yang
// Description: A TestScript that executes a specified test
//
// Modifications:
// Date Name Modification
// ---- ---- ------------
// 25 Sep 2012 yang Original Version
//*****************************************************************
#ifndef CPP_TEST_HARNESS_TA2_TEST_SCRIPT_H_
#define CPP_TEST_HARNESS_TA2_TEST_SCRIPT_H_
#include <string>
#include <map>
#include "key-message-handler.h"
#include "circuit-message-handler.h"
#include "input-message-handler.h"
#include "stream-util.h"
// A TestScript spawns the client and server instances of the SUT or baseline
// and executes a series of key exchange, circuit ingestion, and homomorphic
// evaluation rounds. A TestScript object coordinates the communication between
// the client and server using a set of message handlers. The actual
// communication is performed by the message handlers.
class TestScript {
public:
TestScript(std::ostream* log);
// Frees all registered MessageHandlers.
~TestScript();
// Begin a test. This method takes as input a file path to the test script.
// Each test script contains delimiters followed immediately by relative paths
// to other files containing the security parameter, circuit description, and
// inputs. Any number of circuits can be specified per security parameter. In
// addition, any number of inputs can be specified per circuit description. An
// example test script might look like:
//
// KEY
// path/to/key1
// CIRCUIT
// path/to/circuit1
// INPUT
// path/to/input1
// INPUT
// path/to/input2
// CIRCUIT
// path/to/circuit2
//
// This method parses the test script line-by-line and passes the file path to
// the correct message handler indicated by the delimter. If an unexpected
// delimeter is encountered, the function will abort the test.
void Execute(const std::string& test_path);
// In the test-harness crashes at any point during its execution, calling
// Resume() will begin the test-harness in the most recent state prior to the
// crash. This means that all successfully run key-exchanges, injestions, and
// evaluations will *not* be run again. Calling Resume() if a test
// successfully completes does nothing.
void Resume(const std::string& test_path);
// The test-harness will create four file streams that log the stdin/stdout of
// the client/server. Setting a logger may impact the performance of executing
// tests. These files can also become quite large.
void SetDebugLogStream(bool buffered);
// Registers a MessageHandler with the TestScript. Each MessageHandler is tied
// to a specific delimiter. When the TestScript parses a delimeter, it
// executes the corresponding MessageHandler by passing it a file stream.
// The TestScript takes ownership of the MessageHandlers.
void RegisterHandler(const std::string& delim, MessageHandler* mh);
// Spawns the client process, passing it the arguments specified in args.
void SpawnClient(const std::string& client_path, const std::string& args);
// Spawns the server process, passing it the arguments specified in args.
void SpawnServer(const std::string& server_path, const std::string& args);
// After the client and server processes have been spawned, InitHandlers will
// assign the client and server stdin/outs to each registered MessageHandler.
// This method must be called once before the first call to Execute().
void InitHandlers();
// These static constants define the string sequence used to identity each
// delimeter used in the test file.
const static std::string KEY_DELIM;
const static std::string CIRCUIT_DELIM;
const static std::string INPUT_DELIM;
private:
void SaveState(std::string delim, std::string path);
void Run(std::istream& script);
std::unique_ptr<TestHarnessOStream> client_stdin_;
std::unique_ptr<TestHarnessIStream> client_stdout_;
std::unique_ptr<TestHarnessOStream> server_stdin_;
std::unique_ptr<TestHarnessIStream> server_stdout_;
std::map<std::string, MessageHandler*> handlers_;
std::string current_param_;
std::string current_circuit_;
unsigned int line_num_;
std::ostream* log_;
// Get the keyword to output to the log file from the keyword to
// use with the client and servers
const static std::map<std::string, std::string> delimToLogDelim;
};
#endif
| 38.669492 | 81 | 0.711374 | [
"object"
] |
991d0d9de6d6b62697fb3ac52a33448888a398a7 | 7,833 | h | C | ScriptingBridge/iTerm2.h | ethanliu/dterm | 427308915c70d187a9854618fb7b4f53428ee63d | [
"MIT"
] | 110 | 2015-01-01T16:35:00.000Z | 2022-03-24T09:53:42.000Z | ScriptingBridge/iTerm2.h | ethanliu/dterm | 427308915c70d187a9854618fb7b4f53428ee63d | [
"MIT"
] | 19 | 2016-01-20T08:10:09.000Z | 2022-03-07T19:03:56.000Z | ScriptingBridge/iTerm2.h | ethanliu/dterm | 427308915c70d187a9854618fb7b4f53428ee63d | [
"MIT"
] | 15 | 2016-05-10T00:48:07.000Z | 2021-03-07T17:14:54.000Z | /*
* iTerm2.h
*/
#import <AppKit/AppKit.h>
#import <ScriptingBridge/ScriptingBridge.h>
@class iTerm2Application, iTerm2Window, iTerm2Tab, iTerm2Session;
enum iTerm2SaveOptions {
iTerm2SaveOptionsYes = 'yes ' /* Save the file. */,
iTerm2SaveOptionsNo = 'no ' /* Do not save the file. */,
iTerm2SaveOptionsAsk = 'ask ' /* Ask the user whether or not to save the file. */
};
typedef enum iTerm2SaveOptions iTerm2SaveOptions;
@protocol iTerm2GenericMethods
- (void) delete; // Delete an object.
- (void) duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location.
- (BOOL) exists; // Verify if an object exists.
- (void) moveTo:(SBObject *)to; // Move object(s) to a new location.
- (void) close; // Close a document.
- (iTerm2Tab *) createTabWithProfile:(NSString *)withProfile command:(NSString *)command; // Create a new tab
- (iTerm2Tab *) createTabWithDefaultProfileCommand:(NSString *)command; // Create a new tab with the default profile
- (void) writeContentsOfFile:(NSURL *)contentsOfFile text:(NSString *)text newline:(BOOL)newline; // Send text as though it was typed.
- (void) select; // Make receiver visible and selected.
- (iTerm2Session *) splitVerticallyWithProfile:(NSString *)withProfile command:(NSString *)command; // Split a session vertically.
- (iTerm2Session *) splitVerticallyWithDefaultProfileCommand:(NSString *)command; // Split a session vertically, using the default profile for the new session
- (iTerm2Session *) splitVerticallyWithSameProfileCommand:(NSString *)command; // Split a session vertically, using the original session's profile for the new session
- (iTerm2Session *) splitHorizontallyWithProfile:(NSString *)withProfile command:(NSString *)command; // Split a session horizontally.
- (iTerm2Session *) splitHorizontallyWithDefaultProfileCommand:(NSString *)command; // Split a session horizontally, using the default profile for the new session
- (iTerm2Session *) splitHorizontallyWithSameProfileCommand:(NSString *)command; // Split a session horizontally, using the original session's profile for the new session
- (NSString *) variableNamed:(NSString *)named; // Returns the value of a session variable with the given name
- (NSString *) setVariableNamed:(NSString *)named to:(NSString *)to; // Sets the value of a session variable
- (void) revealHotkeyWindow; // Reveals a hotkey window. Only to be called on windows that are hotkey windows.
- (void) hideHotkeyWindow; // Hides a hotkey window. Only to be called on windows that are hotkey windows.
- (void) toggleHotkeyWindow; // Toggles the visibility of a hotkey window. Only to be called on windows that are hotkey windows.
@end
/*
* Standard Suite
*/
// The application's top-level scripting object.
@interface iTerm2Application : SBApplication
- (SBElementArray<iTerm2Window *> *) windows;
@property (copy) iTerm2Window *currentWindow; // The frontmost window
@property (copy, readonly) NSString *name; // The name of the application.
@property (readonly) BOOL frontmost; // Is this the frontmost (active) application?
@property (copy, readonly) NSString *version; // The version of the application.
- (iTerm2Window *) createWindowWithProfile:(NSString *)x command:(NSString *)command; // Create a new window
- (iTerm2Window *) createHotkeyWindowWithProfile:(NSString *)x; // Create a hotkey window
- (iTerm2Window *) createWindowWithDefaultProfileCommand:(NSString *)command; // Create a new window with the default profile
@end
// A window.
@interface iTerm2Window : SBObject <iTerm2GenericMethods>
- (SBElementArray<iTerm2Tab *> *) tabs;
- (NSInteger) id; // The unique identifier of the session.
@property (copy, readonly) NSString *alternateIdentifier; // The alternate unique identifier of the session.
@property (copy, readonly) NSString *name; // The full title of the window.
@property NSInteger index; // The index of the window, ordered front to back.
@property NSRect bounds; // The bounding rectangle of the window.
@property (readonly) BOOL closeable; // Whether the window has a close box.
@property (readonly) BOOL miniaturizable; // Whether the window can be minimized.
@property BOOL miniaturized; // Whether the window is currently minimized.
@property (readonly) BOOL resizable; // Whether the window can be resized.
@property BOOL visible; // Whether the window is currently visible.
@property (readonly) BOOL zoomable; // Whether the window can be zoomed.
@property BOOL zoomed; // Whether the window is currently zoomed.
@property BOOL frontmost; // Whether the window is currently the frontmost window.
@property (copy) iTerm2Tab *currentTab; // The currently selected tab
@property (copy) iTerm2Session *currentSession; // The current session in a window
@property BOOL isHotkeyWindow; // Whether the window is a hotkey window.
@property (copy) NSString *hotkeyWindowProfile; // If the window is a hotkey window, this gives the name of the profile that created the window.
@property NSPoint position; // The position of the window, relative to the upper left corner of the screen.
@property NSPoint origin; // The position of the window, relative to the lower left corner of the screen.
@property NSPoint size; // The width and height of the window
@property NSRect frame; // The bounding rectangle, relative to the lower left corner of the screen.
@end
/*
* iTerm2 Suite
*/
// A terminal tab
@interface iTerm2Tab : SBObject <iTerm2GenericMethods>
- (SBElementArray<iTerm2Session *> *) sessions;
@property (copy) iTerm2Session *currentSession; // The current session in a tab
@property NSInteger index; // Index of tab in parent tab view control
@end
// A terminal session
@interface iTerm2Session : SBObject <iTerm2GenericMethods>
- (NSString *) id; // The unique identifier of the session.
@property BOOL isProcessing; // The session has received output recently.
@property BOOL isAtShellPrompt; // The terminal is at the shell prompt. Requires shell integration.
@property NSInteger columns;
@property NSInteger rows;
@property (copy, readonly) NSString *tty;
@property (copy) NSString *contents; // The currently visible contents of the session.
@property (copy, readonly) NSString *text; // The currently visible contents of the session.
@property (copy) NSString *colorPreset;
@property (copy) NSColor *backgroundColor;
@property (copy) NSColor *boldColor;
@property (copy) NSColor *cursorColor;
@property (copy) NSColor *cursorTextColor;
@property (copy) NSColor *foregroundColor;
@property (copy) NSColor *selectedTextColor;
@property (copy) NSColor *selectionColor;
@property (copy) NSColor *ANSIBlackColor;
@property (copy) NSColor *ANSIRedColor;
@property (copy) NSColor *ANSIGreenColor;
@property (copy) NSColor *ANSIYellowColor;
@property (copy) NSColor *ANSIBlueColor;
@property (copy) NSColor *ANSIMagentaColor;
@property (copy) NSColor *ANSICyanColor;
@property (copy) NSColor *ANSIWhiteColor;
@property (copy) NSColor *ANSIBrightBlackColor;
@property (copy) NSColor *ANSIBrightRedColor;
@property (copy) NSColor *ANSIBrightGreenColor;
@property (copy) NSColor *ANSIBrightYellowColor;
@property (copy) NSColor *ANSIBrightBlueColor;
@property (copy) NSColor *ANSIBrightMagentaColor;
@property (copy) NSColor *ANSIBrightCyanColor;
@property (copy) NSColor *ANSIBrightWhiteColor;
@property (copy) NSColor *underlineColor;
@property BOOL useUnderlineColor; // Whether the use a dedicated color for underlining.
@property (copy) NSString *backgroundImage;
@property (copy) NSString *name;
@property double transparency;
@property (copy, readonly) NSString *uniqueID;
@property (copy, readonly) NSString *profileName; // The session's profile name
@property (copy) NSString *answerbackString; // ENQ Answerback string
@end
| 49.264151 | 171 | 0.761139 | [
"object"
] |
992080374cb0afbdcb6d1a06952fdd856349eeac | 1,849 | h | C | src/ImageSequenceLoader.h | atarabi/Cinder-AfterEffects | 7cc85a00f827d301b640dbb76cb09318c223f2f5 | [
"MIT"
] | 10 | 2015-06-26T22:14:15.000Z | 2022-02-06T06:42:23.000Z | src/ImageSequenceLoader.h | atarabi/Cinder-AfterEffects | 7cc85a00f827d301b640dbb76cb09318c223f2f5 | [
"MIT"
] | null | null | null | src/ImageSequenceLoader.h | atarabi/Cinder-AfterEffects | 7cc85a00f827d301b640dbb76cb09318c223f2f5 | [
"MIT"
] | 1 | 2017-02-27T12:16:39.000Z | 2017-02-27T12:16:39.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Kareobana
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include "cinder/Filesystem.h"
#include "cinder/ImageIo.h"
#include <string>
#include <vector>
namespace atarabi {
class ImageSequenceLoader {
public:
ImageSequenceLoader() {}
ImageSequenceLoader(const std::string &firstImagePath);
void load(const std::string &firstImagePath);
void reset();
void setLoop(bool loop) { mLoop = loop; }
bool isLoop() const { return mLoop; }
bool empty() const { return mFileNames.empty(); }
int32_t getNumFrames() const { return static_cast<int32_t>(mFileNames.size()); }
cinder::ImageSourceRef getImage(int32_t frame) const;
protected:
bool mLoop = false;
cinder::fs::path mFirstImagePath;
cinder::fs::path mParentPath;
std::vector<std::string> mFileNames;
};
} | 32.438596 | 81 | 0.757166 | [
"vector"
] |
9925068f6c121d576ef8246287790ad614dca15c | 406 | h | C | StyleTransfer/StyleTransfer/View/CollectionViewCell.h | kingandyoga/StyleTransfer-iOS | 5ad3bbb197c26dac8dd05123d2e7f8c55957c3fe | [
"MIT"
] | 101 | 2017-09-04T03:46:12.000Z | 2018-01-29T05:04:40.000Z | StyleTransfer/StyleTransfer/View/CollectionViewCell.h | mohsinalimat/StyleTransfer-iOS | 5ad3bbb197c26dac8dd05123d2e7f8c55957c3fe | [
"MIT"
] | 4 | 2018-04-01T09:37:09.000Z | 2021-04-01T01:55:08.000Z | StyleTransfer/StyleTransfer/View/CollectionViewCell.h | mohsinalimat/StyleTransfer-iOS | 5ad3bbb197c26dac8dd05123d2e7f8c55957c3fe | [
"MIT"
] | 25 | 2018-02-08T09:24:54.000Z | 2020-11-06T10:23:27.000Z | //
// CollectionViewCell.h
// StyleTransfer
//
// Created by 李金 on 2017/8/31.
// Copyright © 2017年 Kingandyoga. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "StyleModel.h"
typedef void(^ClickStyleBlock) (StyleModelType type);
@interface CollectionViewCell : UICollectionViewCell
@property (nonatomic, strong) StyleModel *model;
@property (nonatomic, copy) ClickStyleBlock clickBlock;
@end
| 23.882353 | 55 | 0.753695 | [
"model"
] |
992ad5ca5b433f71a65f2249a3e74cc610f8c510 | 6,684 | h | C | iotexplorer/include/tencentcloud/iotexplorer/v20190423/model/ControlDeviceDataRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | iotexplorer/include/tencentcloud/iotexplorer/v20190423/model/ControlDeviceDataRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | iotexplorer/include/tencentcloud/iotexplorer/v20190423/model/ControlDeviceDataRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_IOTEXPLORER_V20190423_MODEL_CONTROLDEVICEDATAREQUEST_H_
#define TENCENTCLOUD_IOTEXPLORER_V20190423_MODEL_CONTROLDEVICEDATAREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Iotexplorer
{
namespace V20190423
{
namespace Model
{
/**
* ControlDeviceData请求参数结构体
*/
class ControlDeviceDataRequest : public AbstractModel
{
public:
ControlDeviceDataRequest();
~ControlDeviceDataRequest() = default;
std::string ToJsonString() const;
/**
* 获取产品ID
* @return ProductId 产品ID
*/
std::string GetProductId() const;
/**
* 设置产品ID
* @param ProductId 产品ID
*/
void SetProductId(const std::string& _productId);
/**
* 判断参数 ProductId 是否已赋值
* @return ProductId 是否已赋值
*/
bool ProductIdHasBeenSet() const;
/**
* 获取设备名称
* @return DeviceName 设备名称
*/
std::string GetDeviceName() const;
/**
* 设置设备名称
* @param DeviceName 设备名称
*/
void SetDeviceName(const std::string& _deviceName);
/**
* 判断参数 DeviceName 是否已赋值
* @return DeviceName 是否已赋值
*/
bool DeviceNameHasBeenSet() const;
/**
* 获取属性数据, JSON格式字符串, 注意字段需要在物模型属性里定义
* @return Data 属性数据, JSON格式字符串, 注意字段需要在物模型属性里定义
*/
std::string GetData() const;
/**
* 设置属性数据, JSON格式字符串, 注意字段需要在物模型属性里定义
* @param Data 属性数据, JSON格式字符串, 注意字段需要在物模型属性里定义
*/
void SetData(const std::string& _data);
/**
* 判断参数 Data 是否已赋值
* @return Data 是否已赋值
*/
bool DataHasBeenSet() const;
/**
* 获取请求类型 , 不填该参数或者 desired 表示下发属性给设备, reported 表示模拟设备上报属性
* @return Method 请求类型 , 不填该参数或者 desired 表示下发属性给设备, reported 表示模拟设备上报属性
*/
std::string GetMethod() const;
/**
* 设置请求类型 , 不填该参数或者 desired 表示下发属性给设备, reported 表示模拟设备上报属性
* @param Method 请求类型 , 不填该参数或者 desired 表示下发属性给设备, reported 表示模拟设备上报属性
*/
void SetMethod(const std::string& _method);
/**
* 判断参数 Method 是否已赋值
* @return Method 是否已赋值
*/
bool MethodHasBeenSet() const;
/**
* 获取设备ID,该字段有值将代替 ProductId/DeviceName , 通常情况不需要填写
* @return DeviceId 设备ID,该字段有值将代替 ProductId/DeviceName , 通常情况不需要填写
*/
std::string GetDeviceId() const;
/**
* 设置设备ID,该字段有值将代替 ProductId/DeviceName , 通常情况不需要填写
* @param DeviceId 设备ID,该字段有值将代替 ProductId/DeviceName , 通常情况不需要填写
*/
void SetDeviceId(const std::string& _deviceId);
/**
* 判断参数 DeviceId 是否已赋值
* @return DeviceId 是否已赋值
*/
bool DeviceIdHasBeenSet() const;
/**
* 获取上报数据UNIX时间戳(毫秒), 仅对Method:reported有效
* @return DataTimestamp 上报数据UNIX时间戳(毫秒), 仅对Method:reported有效
*/
int64_t GetDataTimestamp() const;
/**
* 设置上报数据UNIX时间戳(毫秒), 仅对Method:reported有效
* @param DataTimestamp 上报数据UNIX时间戳(毫秒), 仅对Method:reported有效
*/
void SetDataTimestamp(const int64_t& _dataTimestamp);
/**
* 判断参数 DataTimestamp 是否已赋值
* @return DataTimestamp 是否已赋值
*/
bool DataTimestampHasBeenSet() const;
private:
/**
* 产品ID
*/
std::string m_productId;
bool m_productIdHasBeenSet;
/**
* 设备名称
*/
std::string m_deviceName;
bool m_deviceNameHasBeenSet;
/**
* 属性数据, JSON格式字符串, 注意字段需要在物模型属性里定义
*/
std::string m_data;
bool m_dataHasBeenSet;
/**
* 请求类型 , 不填该参数或者 desired 表示下发属性给设备, reported 表示模拟设备上报属性
*/
std::string m_method;
bool m_methodHasBeenSet;
/**
* 设备ID,该字段有值将代替 ProductId/DeviceName , 通常情况不需要填写
*/
std::string m_deviceId;
bool m_deviceIdHasBeenSet;
/**
* 上报数据UNIX时间戳(毫秒), 仅对Method:reported有效
*/
int64_t m_dataTimestamp;
bool m_dataTimestampHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_IOTEXPLORER_V20190423_MODEL_CONTROLDEVICEDATAREQUEST_H_
| 33.757576 | 92 | 0.446738 | [
"vector",
"model"
] |
9931169bb01af21060332f227cc00ef89083c4da | 2,444 | h | C | saber/server/server_options.h | QiumingLu/saber | 4b8647611eee03398e02a0578a513e4cb5dadc0c | [
"BSD-3-Clause"
] | 7 | 2017-03-19T02:44:27.000Z | 2021-10-04T07:10:08.000Z | saber/server/server_options.h | QiumingLu/saber | 4b8647611eee03398e02a0578a513e4cb5dadc0c | [
"BSD-3-Clause"
] | null | null | null | saber/server/server_options.h | QiumingLu/saber | 4b8647611eee03398e02a0578a513e4cb5dadc0c | [
"BSD-3-Clause"
] | 3 | 2018-01-26T12:38:42.000Z | 2021-12-12T08:10:14.000Z | // Copyright (c) 2017 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SABER_SERVER_SERVER_OPTIONS_H_
#define SABER_SERVER_SERVER_OPTIONS_H_
#include <stdint.h>
#include <string>
#include <vector>
namespace saber {
struct ServerMessage {
// Default: 1 between [0, 4096)
uint64_t id;
// Default: "127.0.0.1"
std::string host;
// Default: 6666
uint16_t client_port;
// Default: 5666
uint16_t paxos_port;
ServerMessage();
};
struct ServerOptions {
// The saber's thread model is:
// ______________________________________________
// | name | size |
// |————————————————————————————————————————————--|
// | |
// | main thread | 1 |
// | |
// | runloop thread | 1 |
// | |
// | voyager thread model | N |
// | |
// | skywalker thread model | N |
// | |
// -----------------------------------------------
// The saber' thread size is:
// 7 + server_thread_size + paxos_io_thread_size + paxos_callback_thread_size
// Default: 3
uint32_t server_thread_size;
// Default: 2
uint32_t paxos_io_thread_size;
// Default: 1
uint32_t paxos_callback_thread_size;
// Default: 10
uint32_t paxos_group_size;
// Default: 3 * 1000 * 1000 microseconds
uint32_t tick_time;
// Default: 4 * tick_time
uint32_t session_timeout;
// Default: 60000
uint32_t max_all_connections;
// Default: 60
uint32_t max_ip_connections;
// Default: 1024 * 1024
uint32_t max_data_size;
// Default: 1000000
uint32_t keep_log_count;
// Default: 10
uint32_t log_sync_interval;
// Default: 3
uint32_t keep_checkpoint_count;
// Default: 200000
uint32_t make_checkpoint_interval;
// Default: true
bool async_serialize_checkpoint_data;
// Default: ""
std::string log_storage_path;
// Default: ""
std::string checkpoint_storage_path;
ServerMessage my_server_message;
std::vector<ServerMessage> all_server_messages;
ServerOptions();
};
} // namespace saber
#endif // SABER_SERVER_SERVER_OPTIONS_H_
| 23.27619 | 79 | 0.563421 | [
"vector",
"model"
] |
994028b9600e6ff042fd8a769ffdff7a10102e39 | 68,296 | c | C | drivers/serial/mps/cyclades/z/cyzport/cyzinit.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/serial/mps/cyclades/z/cyzport/cyzinit.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/serial/mps/cyclades/z/cyzport/cyzinit.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*--------------------------------------------------------------------------
*
* Copyright (C) Cyclades Corporation, 1997-2001.
* All rights reserved.
*
* Cyclades-Z Port Driver
*
* This file: cyzinit.c
*
* Description: This module contains the code related to initialization
* and unload operations in the Cyclades-Z Port driver.
*
* Notes: This code supports Windows 2000 and Windows XP,
* x86 and IA64 processors.
*
* Complies with Cyclades SW Coding Standard rev 1.3.
*
*--------------------------------------------------------------------------
*/
/*-------------------------------------------------------------------------
*
* Change History
*
*--------------------------------------------------------------------------
*
*
*--------------------------------------------------------------------------
*/
#include "precomp.h"
//
// This is the actual definition of CyzDebugLevel.
// Note that it is only defined if this is a "debug"
// build.
//
#if DBG
extern ULONG CyzDebugLevel = CYZDBGALL;
#endif
//
// All our global variables except DebugLevel stashed in one
// little package
//
CYZ_GLOBALS CyzGlobals;
static const PHYSICAL_ADDRESS CyzPhysicalZero = {0};
//
// We use this to query into the registry as to whether we
// should break at driver entry.
//
CYZ_REGISTRY_DATA driverDefaults;
//
// INIT - only needed during init and then can be disposed
// PAGESRP0 - always paged / never locked
// PAGESER - must be locked when a device is open, else paged
//
//
// INIT is used for DriverEntry() specific code
//
// PAGESRP0 is used for code that is not often called and has nothing
// to do with I/O performance. An example, IRP_MJ_PNP/IRP_MN_START_DEVICE
// support functions
//
// PAGESER is used for code that needs to be locked after an open for both
// performance and IRQL reasons.
//
#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT,DriverEntry)
#pragma alloc_text(PAGESRP0, CyzRemoveDevObj)
#pragma alloc_text(PAGESRP0, CyzUnload)
//
// PAGESER handled is keyed off of CyzReset, so CyzReset
// must remain in PAGESER for things to work properly
//
#pragma alloc_text(PAGESER, CyzReset)
#pragma alloc_text(PAGESER, CyzCommError)
#endif
NTSTATUS
DriverEntry(
IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath
)
/*--------------------------------------------------------------------------
The entry point that the system point calls to initialize
any driver.
This routine will gather the configuration information,
report resource usage, attempt to initialize all serial
devices, connect to interrupts for ports. If the above
goes reasonably well it will fill in the dispatch points,
reset the serial devices and then return to the system.
Arguments:
DriverObject - Just what it says, really of little use
to the driver itself, it is something that the IO system
cares more about.
PathToRegistry - points to the entry for this driver
in the current control set of the registry.
Return Value:
Always STATUS_SUCCESS
--------------------------------------------------------------------------*/
{
//
// Lock the paged code in their frames
//
PVOID lockPtr = MmLockPagableCodeSection(CyzReset);
PAGED_CODE();
ASSERT(CyzGlobals.PAGESER_Handle == NULL);
#if DBG
CyzGlobals.PAGESER_Count = 0;
SerialLogInit();
#endif
CyzGlobals.PAGESER_Handle = lockPtr;
CyzGlobals.RegistryPath.MaximumLength = RegistryPath->MaximumLength;
CyzGlobals.RegistryPath.Length = RegistryPath->Length;
CyzGlobals.RegistryPath.Buffer
= ExAllocatePool(PagedPool, CyzGlobals.RegistryPath.MaximumLength);
if (CyzGlobals.RegistryPath.Buffer == NULL) {
MmUnlockPagableImageSection(lockPtr);
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(CyzGlobals.RegistryPath.Buffer,
CyzGlobals.RegistryPath.MaximumLength);
RtlMoveMemory(CyzGlobals.RegistryPath.Buffer,
RegistryPath->Buffer, RegistryPath->Length);
KeInitializeSpinLock(&CyzGlobals.GlobalsSpinLock);
//
// Initialize all our globals
//
InitializeListHead(&CyzGlobals.AllDevObjs);
//
// Call to find out default values to use for all the devices that the
// driver controls, including whether or not to break on entry.
//
CyzGetConfigDefaults(&driverDefaults, RegistryPath);
#if DBG
//
// Set global debug output level
//
CyzDebugLevel = driverDefaults.DebugLevel;
#endif
//
// Break on entry if requested via registry
//
if (driverDefaults.ShouldBreakOnEntry) {
DbgBreakPoint();
}
//
// Just dump out how big the extension is.
//
CyzDbgPrintEx(DPFLTR_INFO_LEVEL, "The number of bytes in the extension "
"is: %d\n", sizeof(CYZ_DEVICE_EXTENSION));
//
// Initialize the Driver Object with driver's entry points
//
DriverObject->DriverUnload = CyzUnload;
DriverObject->DriverExtension->AddDevice = CyzAddDevice;
DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = CyzFlush;
DriverObject->MajorFunction[IRP_MJ_WRITE] = CyzWrite;
DriverObject->MajorFunction[IRP_MJ_READ] = CyzRead;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = CyzIoControl;
DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL]
= CyzInternalIoControl;
DriverObject->MajorFunction[IRP_MJ_CREATE] = CyzCreateOpen;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = CyzClose;
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = CyzCleanup;
DriverObject->MajorFunction[IRP_MJ_PNP] = CyzPnpDispatch;
DriverObject->MajorFunction[IRP_MJ_POWER] = CyzPowerDispatch;
DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION]
= CyzQueryInformationFile;
DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION]
= CyzSetInformationFile;
DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL]
= CyzSystemControlDispatch;
//
// Unlock pageable text
//
MmUnlockPagableImageSection(lockPtr);
return STATUS_SUCCESS;
}
BOOLEAN
CyzCleanLists(IN PVOID Context)
/*++
Routine Description:
Removes a device object from any of the serial linked lists it may
appear on.
Arguments:
Context - Actually a PCYZ_DEVICE_EXTENSION (for the devobj being
removed).
Return Value:
Always TRUE
--*/
{
PCYZ_DEVICE_EXTENSION pDevExt = (PCYZ_DEVICE_EXTENSION)Context;
PCYZ_DISPATCH pDispatch;
ULONG i;
//
// Remove our entry from the dispatch context
//
pDispatch = (PCYZ_DISPATCH)pDevExt->OurIsrContext;
CyzDbgPrintEx(CYZPNPPOWER, "CLEAN: removing multiport isr "
"ext\n");
#ifdef POLL
if (pDispatch->PollingStarted) {
pDispatch->Extensions[pDevExt->PortIndex] = NULL;
for (i = 0; i < pDispatch->NChannels; i++) {
if (pDevExt->OurIsrContext) {
if (((PCYZ_DISPATCH)pDevExt->OurIsrContext)->Extensions[i] != NULL) {
break;
}
}
}
if (i < pDispatch->NChannels) {
pDevExt->OurIsrContext = NULL;
} else {
BOOLEAN cancelled;
pDispatch->PollingStarted = FALSE;
cancelled = KeCancelTimer(&pDispatch->PollingTimer);
if (cancelled) {
pDispatch->PollingDrained = TRUE;
}
}
}
#else
pDispatch->Extensions[pDevExt->PortIndex] = NULL;
for (i = 0; i < pDispatch->NChannels; i++) {
if (pDispatch->Extensions[i] != NULL) {
break;
}
}
if (i < pDispatch->NChannels) {
// Others are chained on this interrupt, so we don't want to
// disconnect it.
pDevExt->Interrupt = NULL;
}
#endif
return TRUE;
}
VOID
CyzReleaseResources(IN PCYZ_DEVICE_EXTENSION PDevExt)
/*++
Routine Description:
Releases resources (not pool) stored in the device extension.
Arguments:
PDevExt - Pointer to the device extension to release resources from.
Return Value:
VOID
--*/
{
#ifdef POLL
KIRQL pollIrql;
BOOLEAN timerStarted, timerDrained;
PCYZ_DISPATCH pDispatch = PDevExt->OurIsrContext;
ULONG pollCount;
#endif
KIRQL oldIrql;
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, ">CyzReleaseResources(%X)\n",
PDevExt);
//
// AllDevObjs should never be empty since we have a sentinal
// Note: serial removes device from AllDevObjs list after calling
// SerialCleanLists. We do it before to make sure no other port will
// be added to share the polling routine or PDevExt->Interrut that is
// on the way to be disconnected.
//
KeAcquireSpinLock(&CyzGlobals.GlobalsSpinLock, &oldIrql);
ASSERT(!IsListEmpty(&PDevExt->AllDevObjs));
RemoveEntryList(&PDevExt->AllDevObjs);
KeReleaseSpinLock(&CyzGlobals.GlobalsSpinLock, oldIrql);
InitializeListHead(&PDevExt->AllDevObjs);
//
// Remove us from any lists we may be on
//
#ifdef POLL
KeAcquireSpinLock(&pDispatch->PollingLock,&pollIrql); //Changed in 11/09/00
CyzCleanLists(PDevExt);
timerStarted = pDispatch->PollingStarted;
timerDrained = pDispatch->PollingDrained;
KeReleaseSpinLock(&pDispatch->PollingLock,pollIrql); // Changed in 11/09/00
// If we are the last device, free this memory
if (!timerStarted) {
// We are the last device, because timer was cancelled.
// Let's see if no more pending DPC.
if (!timerDrained) {
KeWaitForSingleObject(&pDispatch->PendingDpcEvent, Executive,
KernelMode, FALSE, NULL);
}
KeAcquireSpinLock(&pDispatch->PollingLock,&pollIrql); // needed to wait for PollingDpc end
pollCount = InterlockedDecrement(&pDispatch->PollingCount);
KeReleaseSpinLock(&pDispatch->PollingLock,pollIrql);
if (pollCount == 0) {
CyzDbgPrintEx(CYZPNPPOWER, "Release - freeing multi context\n");
if (PDevExt->OurIsrContext != NULL) { // added in DDK build 2072, but
ExFreePool(PDevExt->OurIsrContext); // we already had the free of OurIsrContext.
PDevExt->OurIsrContext = NULL; //
}
}
}
#else
KeSynchronizeExecution(PDevExt->Interrupt, CyzCleanLists, PDevExt);
//
// Stop servicing interrupts if we are the last device
//
if (PDevExt->Interrupt != NULL) {
// Disable interrupts in the PLX
{
ULONG intr_reg;
intr_reg = CYZ_READ_ULONG(&(PDevExt->Runtime)->intr_ctrl_stat);
intr_reg &= ~(0x00030B00UL);
CYZ_WRITE_ULONG(&(PDevExt->Runtime)->intr_ctrl_stat,intr_reg);
}
CyzDbgPrintEx(CYZPNPPOWER, "Release - disconnecting interrupt %X\n",
PDevExt->Interrupt);
IoDisconnectInterrupt(PDevExt->Interrupt);
PDevExt->Interrupt = NULL;
// If we are the last device, free this memory
CyzDbgPrintEx(CYZPNPPOWER, "Release - freeing multi context\n");
if (PDevExt->OurIsrContext != NULL) { // added in DDK build 2072, but
ExFreePool(PDevExt->OurIsrContext); // we already had the free of OurIsrContext.
PDevExt->OurIsrContext = NULL; //
}
}
#endif
//
// Stop handling timers
//
CyzCancelTimer(&PDevExt->ReadRequestTotalTimer, PDevExt);
CyzCancelTimer(&PDevExt->ReadRequestIntervalTimer, PDevExt);
CyzCancelTimer(&PDevExt->WriteRequestTotalTimer, PDevExt);
CyzCancelTimer(&PDevExt->ImmediateTotalTimer, PDevExt);
CyzCancelTimer(&PDevExt->XoffCountTimer, PDevExt);
CyzCancelTimer(&PDevExt->LowerRTSTimer, PDevExt);
//
// Stop servicing DPC's
//
CyzRemoveQueueDpc(&PDevExt->CompleteWriteDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->CompleteReadDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->TotalReadTimeoutDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->IntervalReadTimeoutDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->TotalWriteTimeoutDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->CommErrorDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->CompleteImmediateDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->TotalImmediateTimeoutDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->CommWaitDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->XoffCountTimeoutDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->XoffCountCompleteDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->StartTimerLowerRTSDpc, PDevExt);
CyzRemoveQueueDpc(&PDevExt->PerhapsLowerRTSDpc, PDevExt);
//
// If necessary, unmap the device registers.
//
// if (PDevExt->BoardMemory) {
// MmUnmapIoSpace(PDevExt->BoardMemory, PDevExt->BoardMemoryLength);
// PDevExt->BoardMemory = NULL;
// }
if (PDevExt->BoardCtrl) {
MmUnmapIoSpace(PDevExt->BoardCtrl, sizeof(struct BOARD_CTRL));
PDevExt->BoardCtrl = NULL;
}
if (PDevExt->ChCtrl) {
MmUnmapIoSpace(PDevExt->ChCtrl,sizeof(struct CH_CTRL));
PDevExt->ChCtrl = NULL;
}
if (PDevExt->BufCtrl) {
MmUnmapIoSpace(PDevExt->BufCtrl,sizeof(struct BUF_CTRL));
PDevExt->BufCtrl = NULL;
}
if (PDevExt->TxBufaddr) {
MmUnmapIoSpace(PDevExt->TxBufaddr,PDevExt->TxBufsize);
PDevExt->TxBufaddr = NULL;
}
if (PDevExt->RxBufaddr) {
MmUnmapIoSpace(PDevExt->RxBufaddr,PDevExt->RxBufsize);
PDevExt->RxBufaddr = NULL;
}
if (PDevExt->PtZfIntQueue) {
MmUnmapIoSpace(PDevExt->PtZfIntQueue,sizeof(struct INT_QUEUE));
PDevExt->PtZfIntQueue = NULL;
}
if (PDevExt->Runtime) {
MmUnmapIoSpace(PDevExt->Runtime,
PDevExt->RuntimeLength);
PDevExt->Runtime = NULL;
}
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, "<CyzReleaseResources\n");
}
VOID
CyzDisableInterfacesResources(IN PDEVICE_OBJECT PDevObj,
BOOLEAN DisableUART)
{
PCYZ_DEVICE_EXTENSION pDevExt
= (PCYZ_DEVICE_EXTENSION)PDevObj->DeviceExtension;
PAGED_CODE();
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, ">CyzDisableInterfaces(%X, %s)\n",
PDevObj, DisableUART ? "TRUE" : "FALSE");
//
// Only do these many things if the device has started and still
// has resources allocated
//
if (pDevExt->Flags & CYZ_FLAGS_STARTED) {
if (!(pDevExt->Flags & CYZ_FLAGS_STOPPED)) {
if (DisableUART) {
#ifndef POLL
//TODO: Synchronize with Interrupt.
//
// Mask off interrupts
//
CYZ_WRITE_ULONG(&(pDevExt->ChCtrl)->intr_enable,C_IN_DISABLE); //1.0.0.11
CyzIssueCmd(pDevExt,C_CM_IOCTL,0L,FALSE);
#endif
}
CyzReleaseResources(pDevExt);
}
//
// Remove us from WMI consideration
//
IoWMIRegistrationControl(PDevObj, WMIREG_ACTION_DEREGISTER);
}
//
// Undo external names
//
CyzUndoExternalNaming(pDevExt);
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, "<CyzDisableInterfaces\n");
}
NTSTATUS
CyzRemoveDevObj(IN PDEVICE_OBJECT PDevObj)
/*++
Routine Description:
Removes a serial device object from the system.
Arguments:
PDevObj - A pointer to the Device Object we want removed.
Return Value:
Always TRUE
--*/
{
PCYZ_DEVICE_EXTENSION pDevExt
= (PCYZ_DEVICE_EXTENSION)PDevObj->DeviceExtension;
PAGED_CODE();
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, ">CyzRemoveDevObj(%X)\n", PDevObj);
// Removed by Fanny. These code is called directly from IRP_MN_REMOVE_DEVICE.
// if (!(pDevExt->DevicePNPAccept & CYZ_PNPACCEPT_SURPRISE_REMOVING)) {
// //
// // Disable all external interfaces and release resources
// //
//
// CyzDisableInterfacesResources(PDevObj, TRUE);
// }
IoDetachDevice(pDevExt->LowerDeviceObject);
//
// Free memory allocated in the extension
//
if (pDevExt->NtNameForPort.Buffer != NULL) {
ExFreePool(pDevExt->NtNameForPort.Buffer);
}
if (pDevExt->DeviceName.Buffer != NULL) {
ExFreePool(pDevExt->DeviceName.Buffer);
}
if (pDevExt->SymbolicLinkName.Buffer != NULL) {
ExFreePool(pDevExt->SymbolicLinkName.Buffer);
}
if (pDevExt->DosName.Buffer != NULL) {
ExFreePool(pDevExt->DosName.Buffer);
}
if (pDevExt->ObjectDirectory.Buffer) {
ExFreePool(pDevExt->ObjectDirectory.Buffer);
}
//
// Delete the devobj
//
IoDeleteDevice(PDevObj);
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, "<CyzRemoveDevObj %X\n",
STATUS_SUCCESS);
return STATUS_SUCCESS;
}
VOID
CyzKillPendingIrps(PDEVICE_OBJECT PDevObj)
/*++
Routine Description:
This routine kills any irps pending for the passed device object.
Arguments:
PDevObj - Pointer to the device object whose irps must die.
Return Value:
VOID
--*/
{
PCYZ_DEVICE_EXTENSION pDevExt = PDevObj->DeviceExtension;
KIRQL oldIrql;
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, ">CyzKillPendingIrps(%X)\n",
PDevObj);
//
// First kill all the reads and writes.
//
CyzKillAllReadsOrWrites(PDevObj, &pDevExt->WriteQueue,
&pDevExt->CurrentWriteIrp);
CyzKillAllReadsOrWrites(PDevObj, &pDevExt->ReadQueue,
&pDevExt->CurrentReadIrp);
//
// Next get rid of purges.
//
CyzKillAllReadsOrWrites(PDevObj, &pDevExt->PurgeQueue,
&pDevExt->CurrentPurgeIrp);
//
// Get rid of any mask operations.
//
CyzKillAllReadsOrWrites(PDevObj, &pDevExt->MaskQueue,
&pDevExt->CurrentMaskIrp);
//
// Now get rid a pending wait mask irp.
//
IoAcquireCancelSpinLock(&oldIrql);
if (pDevExt->CurrentWaitIrp) {
PDRIVER_CANCEL cancelRoutine;
cancelRoutine = pDevExt->CurrentWaitIrp->CancelRoutine;
pDevExt->CurrentWaitIrp->Cancel = TRUE;
if (cancelRoutine) {
pDevExt->CurrentWaitIrp->CancelIrql = oldIrql;
pDevExt->CurrentWaitIrp->CancelRoutine = NULL;
cancelRoutine(PDevObj, pDevExt->CurrentWaitIrp);
} else {
IoReleaseCancelSpinLock(oldIrql); // Added to fix modem share test 53 freeze
}
} else {
IoReleaseCancelSpinLock(oldIrql);
}
//
// Cancel any pending wait-wake irps
//
if (pDevExt->PendingWakeIrp != NULL) {
IoCancelIrp(pDevExt->PendingWakeIrp);
pDevExt->PendingWakeIrp = NULL;
}
//
// Finally, dump any stalled IRPS
//
CyzKillAllStalled(PDevObj);
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, "<CyzKillPendingIrps\n");
}
NTSTATUS
CyzInitMultiPort(IN PCYZ_DEVICE_EXTENSION PDevExt,
IN PCONFIG_DATA PConfigData, IN PDEVICE_OBJECT PDevObj)
/*++
Routine Description:
This routine initializes a multiport device by adding a port to an existing
one.
Arguments:
PDevExt - pointer to the device extension of the root of the multiport
device.
PConfigData - pointer to the config data for the new port
PDevObj - pointer to the devobj for the new port
Return Value:
STATUS_SUCCESS on success, appropriate error on failure.
--*/
{
PCYZ_DEVICE_EXTENSION pNewExt
= (PCYZ_DEVICE_EXTENSION)PDevObj->DeviceExtension;
NTSTATUS status;
PAGED_CODE();
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, ">CyzInitMultiPort(%X, %X, %X)\n",
PDevExt, PConfigData, PDevObj);
//
// Allow him to share OurIsrContext and interrupt object
//
pNewExt->OurIsrContext = PDevExt->OurIsrContext;
#ifndef POLL
pNewExt->Interrupt = PDevExt->Interrupt;
#endif
//
// First, see if we can initialize the one we have found
//
status = CyzInitController(PDevObj, PConfigData);
if (!NT_SUCCESS(status)) {
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, "<CyzInitMultiPort (1) %X\n",
status);
return status;
}
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, "<CyzInitMultiPort (3) %X\n",
STATUS_SUCCESS);
return STATUS_SUCCESS;
}
NTSTATUS
CyzInitController(IN PDEVICE_OBJECT PDevObj, IN PCONFIG_DATA PConfigData)
/*++
Routine Description:
Really too many things to mention here. In general initializes
kernel synchronization structures, allocates the typeahead buffer,
sets up defaults, etc.
Arguments:
PDevObj - Device object for the device to be started
PConfigData - Pointer to a record for a single port.
Return Value:
STATUS_SUCCCESS if everything went ok. A !NT_SUCCESS status
otherwise.
--*/
{
PCYZ_DEVICE_EXTENSION pDevExt = PDevObj->DeviceExtension;
//
// Holds the NT Status that is returned from each call to the
// kernel and executive.
//
NTSTATUS status = STATUS_SUCCESS;
BOOLEAN allocedDispatch = FALSE;
PCYZ_DISPATCH pDispatch = NULL;
BOOLEAN firstTimeThisBoard;
struct FIRM_ID *pt_firm_id;
struct ZFW_CTRL *zfw_ctrl;
struct BOARD_CTRL *board_ctrl;
struct BUF_CTRL *buf_ctrl;
struct CH_CTRL *ch_ctrl;
struct INT_QUEUE *zf_int_queue;
PUCHAR tx_buf;
PUCHAR rx_buf;
PUCHAR BoardMemory;
PHYSICAL_ADDRESS board_ctrl_phys;
PHYSICAL_ADDRESS buf_ctrl_phys;
PHYSICAL_ADDRESS ch_ctrl_phys;
PHYSICAL_ADDRESS zf_int_queue_phys;
PHYSICAL_ADDRESS tx_buf_phys;
PHYSICAL_ADDRESS rx_buf_phys;
#ifdef POLL
BOOLEAN incPoll = FALSE;
#endif
PAGED_CODE();
CyzDbgPrintEx(CYZDIAG1, "Initializing for configuration record of %wZ\n",
&pDevExt->DeviceName);
if (pDevExt->OurIsrContext == NULL) {
if ((pDevExt->OurIsrContext
= ExAllocatePool(NonPagedPool,sizeof(CYZ_DISPATCH))) == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
goto ExtensionCleanup;
}
RtlZeroMemory(pDevExt->OurIsrContext,sizeof(CYZ_DISPATCH));
allocedDispatch = TRUE;
firstTimeThisBoard = TRUE;
} else {
firstTimeThisBoard = FALSE;
}
//
// Initialize the timers used to timeout operations.
//
KeInitializeTimer(&pDevExt->ReadRequestTotalTimer);
KeInitializeTimer(&pDevExt->ReadRequestIntervalTimer);
KeInitializeTimer(&pDevExt->WriteRequestTotalTimer);
KeInitializeTimer(&pDevExt->ImmediateTotalTimer);
KeInitializeTimer(&pDevExt->XoffCountTimer);
KeInitializeTimer(&pDevExt->LowerRTSTimer);
//
// Intialialize the dpcs that will be used to complete
// or timeout various IO operations.
//
KeInitializeDpc(&pDevExt->CompleteWriteDpc, CyzCompleteWrite, pDevExt);
KeInitializeDpc(&pDevExt->CompleteReadDpc, CyzCompleteRead, pDevExt);
KeInitializeDpc(&pDevExt->TotalReadTimeoutDpc, CyzReadTimeout, pDevExt);
KeInitializeDpc(&pDevExt->IntervalReadTimeoutDpc, CyzIntervalReadTimeout,
pDevExt);
KeInitializeDpc(&pDevExt->TotalWriteTimeoutDpc, CyzWriteTimeout, pDevExt);
KeInitializeDpc(&pDevExt->CommErrorDpc, CyzCommError, pDevExt);
KeInitializeDpc(&pDevExt->CompleteImmediateDpc, CyzCompleteImmediate,
pDevExt);
KeInitializeDpc(&pDevExt->TotalImmediateTimeoutDpc, CyzTimeoutImmediate,
pDevExt);
KeInitializeDpc(&pDevExt->CommWaitDpc, CyzCompleteWait, pDevExt);
KeInitializeDpc(&pDevExt->XoffCountTimeoutDpc, CyzTimeoutXoff, pDevExt);
KeInitializeDpc(&pDevExt->XoffCountCompleteDpc, CyzCompleteXoff, pDevExt);
KeInitializeDpc(&pDevExt->StartTimerLowerRTSDpc, CyzStartTimerLowerRTS,
pDevExt);
KeInitializeDpc(&pDevExt->PerhapsLowerRTSDpc, CyzInvokePerhapsLowerRTS,
pDevExt);
KeInitializeDpc(&pDevExt->IsrUnlockPagesDpc, CyzUnlockPages, pDevExt);
#if 0 // DBG
//
// Init debug stuff
//
pDevExt->DpcQueued[0].Dpc = &pDevExt->CompleteWriteDpc;
pDevExt->DpcQueued[1].Dpc = &pDevExt->CompleteReadDpc;
pDevExt->DpcQueued[2].Dpc = &pDevExt->TotalReadTimeoutDpc;
pDevExt->DpcQueued[3].Dpc = &pDevExt->IntervalReadTimeoutDpc;
pDevExt->DpcQueued[4].Dpc = &pDevExt->TotalWriteTimeoutDpc;
pDevExt->DpcQueued[5].Dpc = &pDevExt->CommErrorDpc;
pDevExt->DpcQueued[6].Dpc = &pDevExt->CompleteImmediateDpc;
pDevExt->DpcQueued[7].Dpc = &pDevExt->TotalImmediateTimeoutDpc;
pDevExt->DpcQueued[8].Dpc = &pDevExt->CommWaitDpc;
pDevExt->DpcQueued[9].Dpc = &pDevExt->XoffCountTimeoutDpc;
pDevExt->DpcQueued[10].Dpc = &pDevExt->XoffCountCompleteDpc;
pDevExt->DpcQueued[11].Dpc = &pDevExt->StartTimerLowerRTSDpc;
pDevExt->DpcQueued[12].Dpc = &pDevExt->PerhapsLowerRTSDpc;
pDevExt->DpcQueued[13].Dpc = &pDevExt->IsrUnlockPagesDpc;
#endif
//
// Map the memory for the control registers for the serial device
// into virtual memory.
//
pDevExt->Runtime = MmMapIoSpace(PConfigData->TranslatedRuntime,
PConfigData->RuntimeLength,
FALSE);
//******************************
// Error injection
//if (pDevExt->Runtime) {
// MmUnmapIoSpace(pDevExt->Runtime, PConfigData->RuntimeLength);
// pDevExt->Runtime = NULL;
//}
//******************************
if (!pDevExt->Runtime) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_RUNTIME_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map Runtime memory for device "
"registers for %wZ\n", &pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
BoardMemory = MmMapIoSpace(PConfigData->TranslatedBoardMemory,
PConfigData->BoardMemoryLength,
FALSE);
//******************************
// Error injection
//if (pDevExt->BoardMemory) {
// MmUnmapIoSpace(pDevExt->BoardMemory, PConfigData->BoardMemoryLength);
// pDevExt->BoardMemory = NULL;
//}
//******************************
if (!BoardMemory) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_BOARD_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map Board memory for device "
"registers for %wZ\n", &pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
pDevExt->RuntimeAddressSpace = PConfigData->RuntimeAddressSpace;
pDevExt->OriginalRuntimeMemory = PConfigData->PhysicalRuntime;
pDevExt->RuntimeLength = PConfigData->RuntimeLength;
pDevExt->BoardMemoryAddressSpace = PConfigData->BoardMemoryAddressSpace;
pDevExt->OriginalBoardMemory = PConfigData->PhysicalBoardMemory;
pDevExt->BoardMemoryLength = PConfigData->BoardMemoryLength;
//
// Shareable interrupt?
//
#ifndef POLL
pDevExt->InterruptShareable = TRUE;
#endif
//
// Save off the interface type and the bus number.
//
pDevExt->InterfaceType = PConfigData->InterfaceType;
pDevExt->BusNumber = PConfigData->BusNumber;
pDevExt->PortIndex = PConfigData->PortIndex;
pDevExt->PPPaware = (BOOLEAN)PConfigData->PPPaware;
pDevExt->ReturnStatusAfterFwEmpty = (BOOLEAN)PConfigData->WriteComplete;
#ifndef POLL
//
// Get the translated interrupt vector, level, and affinity
//
pDevExt->OriginalIrql = PConfigData->OriginalIrql;
pDevExt->OriginalVector = PConfigData->OriginalVector;
//
// PnP uses the passed translated values rather than calling
// HalGetInterruptVector()
//
pDevExt->Vector = PConfigData->TrVector;
pDevExt->Irql = (UCHAR)PConfigData->TrIrql;
//
// Set up the Isr.
//
pDevExt->OurIsr = CyzIsr;
#endif
//
// Before we test whether the port exists (which will enable the FIFO)
// convert the rx trigger value to what should be used in the register.
//
// If a bogus value was given - crank them down to 1.
//
switch (PConfigData->RxFIFO) {
case 1:
pDevExt->RxFifoTrigger = SERIAL_1_BYTE_HIGH_WATER;
break;
case 4:
pDevExt->RxFifoTrigger = SERIAL_4_BYTE_HIGH_WATER;
break;
case 8:
pDevExt->RxFifoTrigger = SERIAL_8_BYTE_HIGH_WATER;
break;
case 14:
pDevExt->RxFifoTrigger = SERIAL_14_BYTE_HIGH_WATER;
break;
default:
pDevExt->RxFifoTrigger = SERIAL_1_BYTE_HIGH_WATER;
break;
}
if ((PConfigData->TxFIFO > 16) ||
(PConfigData->TxFIFO < 1)) {
pDevExt->TxFifoAmount = 1;
} else {
pDevExt->TxFifoAmount = PConfigData->TxFIFO;
}
pt_firm_id = (struct FIRM_ID *) (BoardMemory + ID_ADDRESS);
zfw_ctrl = (struct ZFW_CTRL *)(BoardMemory + CYZ_READ_ULONG(&pt_firm_id->zfwctrl_addr));
board_ctrl = &zfw_ctrl->board_ctrl;
ch_ctrl = &zfw_ctrl->ch_ctrl[pDevExt->PortIndex];
buf_ctrl = &zfw_ctrl->buf_ctrl[pDevExt->PortIndex];
tx_buf = BoardMemory + CYZ_READ_ULONG(&buf_ctrl->tx_bufaddr);
rx_buf = BoardMemory + CYZ_READ_ULONG(&buf_ctrl->rx_bufaddr);
zf_int_queue = (struct INT_QUEUE *)(BoardMemory +
CYZ_READ_ULONG(&(board_ctrl)->zf_int_queue_addr));
board_ctrl_phys = MmGetPhysicalAddress(board_ctrl);
ch_ctrl_phys = MmGetPhysicalAddress(ch_ctrl);
buf_ctrl_phys = MmGetPhysicalAddress(buf_ctrl);
tx_buf_phys = MmGetPhysicalAddress(tx_buf);
rx_buf_phys = MmGetPhysicalAddress(rx_buf);
zf_int_queue_phys = MmGetPhysicalAddress(zf_int_queue);
MmUnmapIoSpace(BoardMemory, PConfigData->BoardMemoryLength);
pDevExt->BoardCtrl = MmMapIoSpace(board_ctrl_phys,
sizeof(struct BOARD_CTRL),
FALSE);
if (pDevExt->BoardCtrl == NULL) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_BOARD_CTRL_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map BoardCtrl for %wZ\n",
&pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
pDevExt->ChCtrl = MmMapIoSpace(ch_ctrl_phys,
sizeof(struct CH_CTRL),
FALSE);
if (pDevExt->ChCtrl == NULL) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_CH_CTRL_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map Board memory ChCtrl "
"for %wZ\n",&pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
pDevExt->BufCtrl = MmMapIoSpace(buf_ctrl_phys,
sizeof(struct BUF_CTRL),
FALSE);
if (pDevExt->BufCtrl == NULL) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_BUF_CTRL_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map Board memory BufCtrl "
"for %wZ\n",&pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
buf_ctrl = pDevExt->BufCtrl;
pDevExt->TxBufsize = CYZ_READ_ULONG(&buf_ctrl->tx_bufsize);
pDevExt->RxBufsize = CYZ_READ_ULONG(&buf_ctrl->rx_bufsize);
pDevExt->TxBufaddr = MmMapIoSpace(tx_buf_phys,
pDevExt->TxBufsize,
FALSE);
if (pDevExt->TxBufaddr == NULL) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_TX_BUF_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map Board memory TxBuf "
"for %wZ\n",&pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
pDevExt->RxBufaddr = MmMapIoSpace(rx_buf_phys,
pDevExt->RxBufsize,
FALSE);
if (pDevExt->RxBufaddr == NULL) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_RX_BUF_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map Board memory RxBuf "
"for %wZ\n",&pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
pDevExt->PtZfIntQueue = MmMapIoSpace(zf_int_queue_phys,
sizeof(struct INT_QUEUE),
FALSE);
if (pDevExt->PtZfIntQueue == NULL) {
CyzLogError(
PDevObj->DriverObject,
pDevExt->DeviceObject,
PConfigData->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfigData->PortIndex+1,
STATUS_SUCCESS,
CYZ_INT_QUEUE_NOT_MAPPED,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Could not map Board memory IntQueue"
" for %wZ\n",&pDevExt->DeviceName);
status = STATUS_NONE_MAPPED;
goto ExtensionCleanup;
}
if (!CyzDoesPortExist(
pDevExt,
&pDevExt->DeviceName
)) {
//
// We couldn't verify that there was actually a
// port. No need to log an error as the port exist
// code will log exactly why.
//
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "DoesPortExist test failed for "
"%wZ\n", &pDevExt->DeviceName);
status = STATUS_NO_SUCH_DEVICE;
goto ExtensionCleanup;
}
//
// Set up the default device control fields.
// Note that if the values are changed after
// the file is open, they do NOT revert back
// to the old value at file close.
//
pDevExt->SpecialChars.XonChar = CYZ_DEF_XON;
pDevExt->SpecialChars.XoffChar = CYZ_DEF_XOFF;
pDevExt->HandFlow.ControlHandShake = SERIAL_DTR_CONTROL;
pDevExt->HandFlow.FlowReplace = SERIAL_RTS_CONTROL;
//
// Default Line control protocol. 7E1
//
// Seven data bits.
// Even parity.
// 1 Stop bits.
//
pDevExt->CommParity = C_PR_EVEN;
pDevExt->CommDataLen = C_DL_CS7 | C_DL_1STOP;
pDevExt->ValidDataMask = 0x7f;
pDevExt->CurrentBaud = 1200;
//
// We set up the default xon/xoff limits.
//
// This may be a bogus value. It looks like the BufferSize
// is not set up until the device is actually opened.
//
pDevExt->HandFlow.XoffLimit = pDevExt->BufferSize >> 3;
pDevExt->HandFlow.XonLimit = pDevExt->BufferSize >> 1;
pDevExt->BufferSizePt8 = ((3*(pDevExt->BufferSize>>2))+
(pDevExt->BufferSize>>4));
CyzDbgPrintEx(CYZDIAG1, " The default interrupt read buffer size is: %d\n"
"------ The XoffLimit is : %d\n"
"------ The XonLimit is : %d\n"
"------ The pt 8 size is : %d\n",
pDevExt->BufferSize, pDevExt->HandFlow.XoffLimit,
pDevExt->HandFlow.XonLimit, pDevExt->BufferSizePt8);
pDevExt->SupportedBauds = SERIAL_BAUD_075 | SERIAL_BAUD_110 |
SERIAL_BAUD_134_5 | SERIAL_BAUD_150 | SERIAL_BAUD_300 |
SERIAL_BAUD_600 | SERIAL_BAUD_1200 | SERIAL_BAUD_1800 |
SERIAL_BAUD_2400 | SERIAL_BAUD_4800 | SERIAL_BAUD_7200 |
SERIAL_BAUD_9600 | SERIAL_BAUD_14400 | SERIAL_BAUD_19200 |
SERIAL_BAUD_38400 | SERIAL_BAUD_56K | SERIAL_BAUD_57600 |
SERIAL_BAUD_115200 | SERIAL_BAUD_128K | SERIAL_BAUD_USER;
//
// Mark this device as not being opened by anyone. We keep a
// variable around so that spurious interrupts are easily
// dismissed by the ISR.
//
pDevExt->DeviceIsOpened = FALSE;
//
// Store values into the extension for interval timing.
//
//
// If the interval timer is less than a second then come
// in with a short "polling" loop.
//
// For large (> then 2 seconds) use a 1 second poller.
//
pDevExt->ShortIntervalAmount.QuadPart = -1;
pDevExt->LongIntervalAmount.QuadPart = -10000000;
pDevExt->CutOverAmount.QuadPart = 200000000;
// Initialize for the Isr Dispatch
pDispatch = pDevExt->OurIsrContext;
#ifndef POLL
pDispatch->Extensions[pDevExt->PortIndex] = pDevExt;
pDispatch->PoweredOn[pDevExt->PortIndex] = TRUE;
#endif
if (firstTimeThisBoard) {
#ifdef POLL
ULONG intr_reg;
ULONG pollingCycle;
pollingCycle = 10; // default = 20ms
pDispatch->PollingTime.LowPart = pollingCycle * 10000;
pDispatch->PollingTime.HighPart = 0;
pDispatch->PollingTime = RtlLargeIntegerNegate(pDispatch->PollingTime);
pDispatch->PollingPeriod = pollingCycle;
KeInitializeSpinLock(&pDispatch->PollingLock);
KeInitializeTimer(&pDispatch->PollingTimer);
KeInitializeDpc(&pDispatch->PollingDpc, CyzPollingDpc, pDispatch);
KeInitializeEvent(&pDispatch->PendingDpcEvent, SynchronizationEvent, FALSE);
intr_reg = CYZ_READ_ULONG(&(pDevExt->Runtime)->intr_ctrl_stat);
//intr_reg |= (0x00030800UL);
intr_reg |= (0x00030000UL);
CYZ_WRITE_ULONG(&(pDevExt->Runtime)->intr_ctrl_stat,intr_reg);
#else
CyzResetBoard(pDevExt); //Shouldn't we put this line on the POLL version?
#endif
pDispatch->NChannels = CYZ_READ_ULONG(&(pDevExt->BoardCtrl)->n_channel);
}
#ifdef POLL
InterlockedIncrement(&pDispatch->PollingCount);
incPoll = TRUE;
#endif
//
// Common error path cleanup. If the status is
// bad, get rid of the device extension, device object
// and any memory associated with it.
//
ExtensionCleanup: ;
if (!NT_SUCCESS(status)) {
#ifdef POLL
if (incPoll) {
InterlockedDecrement(&pDispatch->PollingCount);
}
#else
if (pDispatch) {
pDispatch->Extensions[pDevExt->PortIndex] = NULL;
}
#endif
if (allocedDispatch) {
ExFreePool(pDevExt->OurIsrContext);
pDevExt->OurIsrContext = NULL;
}
if (pDevExt->Runtime) {
MmUnmapIoSpace(pDevExt->Runtime, PConfigData->RuntimeLength);
pDevExt->Runtime = NULL;
}
if (pDevExt->BoardCtrl) {
MmUnmapIoSpace(pDevExt->BoardCtrl, sizeof(struct BOARD_CTRL));
pDevExt->BoardCtrl = NULL;
}
if (pDevExt->ChCtrl) {
MmUnmapIoSpace(pDevExt->ChCtrl,sizeof(struct CH_CTRL));
pDevExt->ChCtrl = NULL;
}
if (pDevExt->BufCtrl) {
MmUnmapIoSpace(pDevExt->BufCtrl,sizeof(struct BUF_CTRL));
pDevExt->BufCtrl = NULL;
}
if (pDevExt->TxBufaddr) {
MmUnmapIoSpace(pDevExt->TxBufaddr,pDevExt->TxBufsize);
pDevExt->TxBufaddr = NULL;
}
if (pDevExt->RxBufaddr) {
MmUnmapIoSpace(pDevExt->RxBufaddr,pDevExt->RxBufsize);
pDevExt->RxBufaddr = NULL;
}
if (pDevExt->PtZfIntQueue) {
MmUnmapIoSpace(pDevExt->PtZfIntQueue,sizeof(struct INT_QUEUE));
pDevExt->PtZfIntQueue = NULL;
}
}
return status;
}
BOOLEAN
CyzDoesPortExist(
IN PCYZ_DEVICE_EXTENSION Extension,
IN PUNICODE_STRING InsertString
)
/*++
Routine Description:
This routine examines several of what might be the serial device
registers. It ensures that the bits that should be zero are zero.
In addition, this routine will determine if the device supports
fifo's. If it does it will enable the fifo's and turn on a boolean
in the extension that indicates the fifo's presence.
NOTE: If there is indeed a serial port at the address specified
it will absolutely have interrupts inhibited upon return
from this routine.
NOTE: Since this routine should be called fairly early in
the device driver initialization, the only element
that needs to be filled in is the base register address.
NOTE: These tests all assume that this code is the only
code that is looking at these ports or this memory.
This is a not to unreasonable assumption even on
multiprocessor systems.
Arguments:
Extension - A pointer to a serial device extension.
InsertString - String to place in an error log entry.
Return Value:
Will return true if the port really exists, otherwise it
will return false.
--*/
{
return TRUE;
}
VOID
CyzResetBoard( PCYZ_DEVICE_EXTENSION Extension )
/*++
Routine Description:
This routine examines several of what might be the serial device
registers. It ensures that the bits that should be zero are zero.
In addition, this routine will determine if the device supports
fifo's. If it does it will enable the fifo's and turn on a boolean
in the extension that indicates the fifo's presence.
NOTE: If there is indeed a serial port at the address specified
it will absolutely have interrupts inhibited upon return
from this routine.
NOTE: Since this routine should be called fairly early in
the device driver initialization, the only element
that needs to be filled in is the base register address.
NOTE: These tests all assume that this code is the only
code that is looking at these ports or this memory.
This is a not to unreasonable assumption even on
multiprocessor systems.
Arguments:
Extension - A pointer to a serial device extension.
InsertString - String to place in an error log entry.
Return Value:
Will return true if the port really exists, otherwise it
will return false.
--*/
{
#ifndef POLL
//CyzIssueCmd(Extension,C_CM_SETNNDT,20L,FALSE); Removed. Let's firmware calculate NNDT.
#endif
//CyzIssueCmd(Extension,C_CM_RESET,0L,FALSE); // Added in 1.0.0.11
}
BOOLEAN
CyzReset(
IN PVOID Context
)
/*--------------------------------------------------------------------------
CyzReset()
Routine Description: This places the hardware in a standard
configuration. This assumes that it is called at interrupt level.
Arguments:
Context - The device extension for serial device being managed.
Return Value: Always FALSE.
--------------------------------------------------------------------------*/
{
PCYZ_DEVICE_EXTENSION extension = Context;
struct CH_CTRL *ch_ctrl = extension->ChCtrl;
struct BUF_CTRL *buf_ctrl = extension->BufCtrl;
CYZ_IOCTL_BAUD s;
//For interrupt mode: extension->RxFifoTriggerUsed = FALSE; (from cyyport)
// set the line control, modem control, and the baud to what they should be.
CyzSetLineControl(extension);
CyzSetupNewHandFlow(extension,&extension->HandFlow);
CyzHandleModemUpdate(extension,FALSE,0);
s.Extension = extension;
s.Baud = extension->CurrentBaud;
CyzSetBaud(&s);
//This flag is configurable from the Advanced Port Settings.
//extension->ReturnStatusAfterFwEmpty = TRUE; // We will loose performance, but it will be
// // closer to serial driver.
extension->ReturnWriteStatus = FALSE;
extension->CmdFailureLog = TRUE;
// Enable port
CYZ_WRITE_ULONG(&ch_ctrl->op_mode,C_CH_ENABLE);
#ifdef POLL
CYZ_WRITE_ULONG(&ch_ctrl->intr_enable,C_IN_MDCD | C_IN_MCTS | C_IN_MRI
| C_IN_MDSR | C_IN_RXBRK | C_IN_PR_ERROR
| C_IN_FR_ERROR | C_IN_OVR_ERROR | C_IN_RXOFL
| C_IN_IOCTLW | C_IN_TXFEMPTY);
#else
//CYZ_WRITE_ULONG(&buf_ctrl->rx_threshold,1024);
CYZ_WRITE_ULONG(&ch_ctrl->intr_enable,C_IN_MDCD | C_IN_MCTS | C_IN_MRI
| C_IN_MDSR | C_IN_RXBRK | C_IN_PR_ERROR
| C_IN_FR_ERROR | C_IN_OVR_ERROR | C_IN_RXOFL
| C_IN_IOCTLW | C_IN_TXBEMPTY //1.0.0.11: C_IN_TXBEMPTY OR C_IN_TXFEMPTY?
| C_IN_RXHIWM | C_IN_RXNNDT | C_IN_TXLOWWM);
#endif
//ToDo: Enable C_IN_IOCTLW in the interrupt version.
CyzIssueCmd(extension,C_CM_IOCTLW,0L,FALSE);
extension->HoldingEmpty = TRUE;
return FALSE;
}
VOID
CyzUnload(
IN PDRIVER_OBJECT DriverObject
)
/*--------------------------------------------------------------------------
CyzUnload()
Description: Cleans up all of the memory associated with the
Device Objects created by the driver.
Arguments:
DriverObject - A pointer to the driver object.
Return Value: None.
--------------------------------------------------------------------------*/
{
PVOID lockPtr;
PAGED_CODE();
lockPtr = MmLockPagableCodeSection(CyzUnload);
//
// Unnecessary since our BSS is going away, but do it anyhow to be safe
//
CyzGlobals.PAGESER_Handle = NULL;
if (CyzGlobals.RegistryPath.Buffer != NULL) {
ExFreePool(CyzGlobals.RegistryPath.Buffer);
CyzGlobals.RegistryPath.Buffer = NULL;
}
#if DBG
SerialLogFree();
#endif
CyzDbgPrintEx(CYZDIAG3, "In CyzUnload\n");
MmUnlockPagableImageSection(lockPtr);
}
CYZ_MEM_COMPARES
CyzMemCompare(
IN PHYSICAL_ADDRESS A,
IN ULONG SpanOfA,
IN PHYSICAL_ADDRESS B,
IN ULONG SpanOfB
)
/*++
Routine Description:
Compare two phsical address.
Arguments:
A - One half of the comparison.
SpanOfA - In units of bytes, the span of A.
B - One half of the comparison.
SpanOfB - In units of bytes, the span of B.
Return Value:
The result of the comparison.
--*/
{
LARGE_INTEGER a;
LARGE_INTEGER b;
LARGE_INTEGER lower;
ULONG lowerSpan;
LARGE_INTEGER higher;
//PAGED_CODE(); Non paged because it can be called during CyzLogError, which is non paged now.
a = A;
b = B;
if (a.QuadPart == b.QuadPart) {
return AddressesAreEqual;
}
if (a.QuadPart > b.QuadPart) {
higher = a;
lower = b;
lowerSpan = SpanOfB;
} else {
higher = b;
lower = a;
lowerSpan = SpanOfA;
}
if ((higher.QuadPart - lower.QuadPart) >= lowerSpan) {
return AddressesAreDisjoint;
}
return AddressesOverlap;
}
NTSTATUS
CyzFindInitController(IN PDEVICE_OBJECT PDevObj, IN PCONFIG_DATA PConfig)
/*++
Routine Description:
This function discovers what type of controller is responsible for
the given port and initializes the controller and port.
Arguments:
PDevObj - Pointer to the devobj for the port we are about to init.
PConfig - Pointer to configuration data for the port we are about to init.
Return Value:
STATUS_SUCCESS on success, appropriate error value on failure.
--*/
{
PCYZ_DEVICE_EXTENSION pDevExt = PDevObj->DeviceExtension;
PDEVICE_OBJECT pDeviceObject;
PCYZ_DEVICE_EXTENSION pExtension;
PHYSICAL_ADDRESS serialPhysicalMax;
PLIST_ENTRY pCurDevObj;
NTSTATUS status;
KIRQL oldIrql;
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, ">CyzFindInitController(%X, %X)\n",
PDevObj, PConfig);
serialPhysicalMax.LowPart = (ULONG)~0;
serialPhysicalMax.HighPart = ~0;
#ifdef POLL
CyzDbgPrintEx(CYZDIAG1, "Attempting to init %wZ\n"
"------- Runtime Memory is %x\n"
"------- Board Memory is %x\n"
"------- BusNumber is %d\n"
"------- BusType is %d\n"
"------- Runtime AddressSpace is %d\n"
"------- Board AddressSpace is %d\n",
&pDevExt->DeviceName,
PConfig->PhysicalRuntime.LowPart,
PConfig->PhysicalBoardMemory.LowPart,
PConfig->BusNumber,
PConfig->InterfaceType,
PConfig->RuntimeAddressSpace,
PConfig->BoardMemoryAddressSpace);
#else
CyzDbgPrintEx(CYZDIAG1, "Attempting to init %wZ\n"
"------- Runtime Memory is %x\n"
"------- Board Memory is %x\n"
"------- BusNumber is %d\n"
"------- BusType is %d\n"
"------- Runtime AddressSpace is %d\n"
"------- Board AddressSpace is %d\n"
"------- Interrupt Mode is %d\n",
&pDevExt->DeviceName,
PConfig->PhysicalRuntime.LowPart,
PConfig->PhysicalBoardMemory.LowPart,
PConfig->BusNumber,
PConfig->InterfaceType,
PConfig->RuntimeAddressSpace,
PConfig->BoardMemoryAddressSpace,
PConfig->InterruptMode);
#endif
//
// We don't support any boards whose memory wraps around
// the physical address space.
//
//*****************************************************
// error injection
// if (CyzMemCompare(
// PConfig->PhysicalRuntime,
// PConfig->RuntimeLength,
// serialPhysicalMax,
// (ULONG)0
// ) == AddressesAreDisjoint)
//*****************************************************
if (CyzMemCompare(
PConfig->PhysicalRuntime,
PConfig->RuntimeLength,
serialPhysicalMax,
(ULONG)0
) != AddressesAreDisjoint) {
CyzLogError(
PDevObj->DriverObject,
NULL,
PConfig->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfig->PortIndex+1,
STATUS_SUCCESS,
CYZ_RUNTIME_MEMORY_TOO_HIGH,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Error in config record for %wZ\n"
"------ Runtime memory wraps around physical memory\n",
&pDevExt->DeviceName);
return STATUS_NO_SUCH_DEVICE;
}
//*****************************************************
// error injection
// if (CyzMemCompare(
// PConfig->PhysicalBoardMemory,
// PConfig->BoardMemoryLength,
// serialPhysicalMax,
// (ULONG)0
// ) == AddressesAreDisjoint)
//*****************************************************
if (CyzMemCompare(
PConfig->PhysicalBoardMemory,
PConfig->BoardMemoryLength,
serialPhysicalMax,
(ULONG)0
) != AddressesAreDisjoint) {
CyzLogError(
PDevObj->DriverObject,
NULL,
PConfig->PhysicalBoardMemory,
CyzPhysicalZero,
0,
0,
0,
PConfig->PortIndex+1,
STATUS_SUCCESS,
CYZ_BOARD_MEMORY_TOO_HIGH,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Error in config record for %wZ\n"
"------ board memory wraps around physical memory\n",
&pDevExt->DeviceName);
return STATUS_NO_SUCH_DEVICE;
}
//
// Make sure that the Runtime memory addresses don't
// overlap the DP memory addresses for PCI cards
//
if (CyzMemCompare(
PConfig->PhysicalRuntime,
PConfig->RuntimeLength,
CyzPhysicalZero,
(ULONG)0
) != AddressesAreEqual) {
//*****************************************************
// error injection
// if (CyzMemCompare(
// PConfig->PhysicalRuntime,
// PConfig->RuntimeLength,
// PConfig->PhysicalBoardMemory,
// PConfig->BoardMemoryLength
// ) == AddressesAreDisjoint)
//*****************************************************
if (CyzMemCompare(
PConfig->PhysicalRuntime,
PConfig->RuntimeLength,
PConfig->PhysicalBoardMemory,
PConfig->BoardMemoryLength
) != AddressesAreDisjoint) {
CyzLogError(
PDevObj->DriverObject,
NULL,
PConfig->PhysicalBoardMemory,
PConfig->PhysicalRuntime,
0,
0,
0,
PConfig->PortIndex+1,
STATUS_SUCCESS,
CYZ_BOTH_MEMORY_CONFLICT,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
0,
NULL
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Error in config record for %wZ\n"
"------ Runtime memory wraps around Board memory\n",
&pDevExt->DeviceName);
return STATUS_NO_SUCH_DEVICE;
}
}
//
// Now, we will check if this is a port on a multiport card.
// The conditions are same BoardMemory set and same IRQL/Vector
//
//
// Loop through all previously attached devices
//
KeAcquireSpinLock(&CyzGlobals.GlobalsSpinLock, &oldIrql);
if (!IsListEmpty(&CyzGlobals.AllDevObjs)) {
pCurDevObj = CyzGlobals.AllDevObjs.Flink;
pExtension = CONTAINING_RECORD(pCurDevObj, CYZ_DEVICE_EXTENSION,
AllDevObjs);
} else {
pCurDevObj = NULL;
pExtension = NULL;
}
KeReleaseSpinLock(&CyzGlobals.GlobalsSpinLock, oldIrql);
//
// If there is an interrupt status then we
// loop through the config list again to look
// for a config record with the same interrupt
// status (on the same bus).
//
if (pCurDevObj != NULL) {
ASSERT(pExtension != NULL);
//
// We have an interrupt status. Loop through all
// previous records, look for an existing interrupt status
// the same as the current interrupt status.
//
do {
//
// We only care about this list if the elements are on the
// same bus as this new entry. (Their interrupts must therefore
// also be the on the same bus. We will check that momentarily).
//
// We don't check here for the dissimilar interrupts since that
// could cause us to miss the error of having the same interrupt
// status but different interrupts - which is bizzare.
//
if ((pExtension->InterfaceType == PConfig->InterfaceType) &&
(pExtension->BoardMemoryAddressSpace == PConfig->BoardMemoryAddressSpace) &&
(pExtension->BusNumber == PConfig->BusNumber)) {
//
// If the board memory is the same, then same card.
//
if (CyzMemCompare(
pExtension->OriginalBoardMemory,
pExtension->BoardMemoryLength,
PConfig->PhysicalBoardMemory,
PConfig->BoardMemoryLength
) == AddressesAreEqual) {
#ifndef POLL
//
// Same card. Now make sure that they
// are using the same interrupt parameters.
//
// BUILD 2128: OriginalIrql replaced by TrIrql and Irql; same for OriginalVector
if ((PConfig->TrIrql != pExtension->Irql) ||
(PConfig->TrVector != pExtension->Vector)) {
//
// We won't put this into the configuration
// list.
//
CyzLogError(
PDevObj->DriverObject,
NULL,
PConfig->PhysicalBoardMemory,
pExtension->OriginalBoardMemory,
0,
0,
0,
PConfig->PortIndex+1,
STATUS_SUCCESS,
CYZ_MULTI_INTERRUPT_CONFLICT,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
pExtension->DeviceName.Length
+ sizeof(WCHAR),
pExtension->DeviceName.Buffer
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Configuration error "
"for %wZ\n"
"------- Same multiport - different "
"interrupts\n", &pDevExt->DeviceName);
return STATUS_NO_SUCH_DEVICE;
}
#endif
//
// PCI board. Make sure the PCI memory addresses are equal.
//
if (CyzMemCompare(
pExtension->OriginalRuntimeMemory,
pExtension->RuntimeLength,
PConfig->PhysicalRuntime,
PConfig->RuntimeLength
) != AddressesAreEqual) {
//*****************************************************
// error injection
// if (CyzMemCompare(
// pExtension->OriginalRuntimeMemory,
// pExtension->RuntimeLength,
// PConfig->PhysicalRuntime,
// PConfig->RuntimeLength
// ) == AddressesAreEqual)
//*****************************************************
CyzLogError(
PDevObj->DriverObject,
NULL,
PConfig->PhysicalRuntime,
pExtension->OriginalRuntimeMemory,
0,
0,
0,
PConfig->PortIndex+1,
STATUS_SUCCESS,
CYZ_MULTI_RUNTIME_CONFLICT,
pDevExt->DeviceName.Length+sizeof(WCHAR),
pDevExt->DeviceName.Buffer,
pExtension->DeviceName.Length
+ sizeof(WCHAR),
pExtension->DeviceName.Buffer
);
CyzDbgPrintEx(DPFLTR_WARNING_LEVEL, "Configuration error "
"for %wZ\n"
"------- Same multiport - different "
"Runtime addresses\n", &pDevExt->DeviceName);
return STATUS_NO_SUCH_DEVICE;
}
//
// We should never get this far on a restart since we don't
// support stop on ISA multiport devices!
//
ASSERT(pDevExt->PNPState == CYZ_PNP_ADDED);
//
//
// Initialize the device as part of a multiport board
//
CyzDbgPrintEx(CYZDIAG1, "Aha! It is a multiport node\n");
CyzDbgPrintEx(CYZDIAG1, "Matched to %x\n", pExtension);
status = CyzInitMultiPort(pExtension, PConfig, PDevObj);
//
// A port can be one of two things:
// A non-root on a multiport
// A root on a multiport
//
// It can only share an interrupt if it is a root.
// Since this was a non-root we don't need to check
// if it shares an interrupt and we can return.
//
return status;
}
}
//
// No match, check some more
//
KeAcquireSpinLock(&CyzGlobals.GlobalsSpinLock, &oldIrql);
pCurDevObj = pCurDevObj->Flink;
if (pCurDevObj != NULL) {
pExtension = CONTAINING_RECORD(pCurDevObj,CYZ_DEVICE_EXTENSION,
AllDevObjs);
}
KeReleaseSpinLock(&CyzGlobals.GlobalsSpinLock, oldIrql);
} while (pCurDevObj != NULL && pCurDevObj != &CyzGlobals.AllDevObjs);
}
CyzDbgPrintEx(CYZDIAG1, "Aha! It is a first multi\n");
status = CyzInitController(PDevObj, PConfig);
if (!NT_SUCCESS(status)) {
return status;
}
return STATUS_SUCCESS;
}
VOID
CyzCommError(
IN PKDPC Dpc,
IN PVOID DeferredContext,
IN PVOID SystemContext1,
IN PVOID SystemContext2
)
/*--------------------------------------------------------------------------
CyzComError()
Routine Description: This routine is invoked at dpc level in response
to a comm error. All comm errors kill all read and writes
Arguments:
Dpc - Not Used.
DeferredContext - points to the device object.
SystemContext1 - Not Used.
SystemContext2 - Not Used.
Return Value: None.
--------------------------------------------------------------------------*/
{
PCYZ_DEVICE_EXTENSION Extension = DeferredContext;
UNREFERENCED_PARAMETER(SystemContext1);
UNREFERENCED_PARAMETER(SystemContext2);
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, ">CyzCommError(%X)\n", Extension);
CyzKillAllReadsOrWrites(
Extension->DeviceObject,
&Extension->WriteQueue,
&Extension->CurrentWriteIrp
);
CyzKillAllReadsOrWrites(
Extension->DeviceObject,
&Extension->ReadQueue,
&Extension->CurrentReadIrp
);
CyzDpcEpilogue(Extension, Dpc);
CyzDbgPrintEx(DPFLTR_TRACE_LEVEL, "<CyzCommError\n");
}
| 30.046634 | 98 | 0.560209 | [
"object",
"vector"
] |
994847e495e7ab6a45ec15dce5bcb5dad66c9a60 | 5,563 | h | C | backends/metadb.h | zhengqmark/indexfs_old | 622169a8af1c80e7de7648a9ee6f874af919200c | [
"BSD-3-Clause"
] | 6 | 2015-11-21T19:48:36.000Z | 2019-04-01T03:36:21.000Z | backends/metadb.h | zhengqmark/indexfs-0.3 | 622169a8af1c80e7de7648a9ee6f874af919200c | [
"BSD-3-Clause"
] | 1 | 2015-11-21T19:59:52.000Z | 2015-11-21T19:59:52.000Z | backends/metadb.h | zhengqmark/indexfs_old | 622169a8af1c80e7de7648a9ee6f874af919200c | [
"BSD-3-Clause"
] | 3 | 2019-02-06T23:02:28.000Z | 2019-11-05T04:10:22.000Z | // Copyright (c) 2014 The IndexFS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef _INDEXFS_BACKEND_METADB_H_
#define _INDEXFS_BACKEND_METADB_H_
#include <vector>
#include <string>
extern "C" {
#include "operations.h"
}
#include "common/common.h"
namespace indexfs {
class MetadataBackend {
protected:
MetaDB mdb;
public:
int Init(const std::string& dbname,
const char* hdfsIP,
int hdfsPort,
int serverID);
int Create(const TINumber dir_id,
const int partition_id,
const std::string &objname,
const std::string &realpath);
// Returns "0" if MDB creates the directory successfully, otherwise "-1" on error.
int Mkdir(const TINumber dir_id,
const int partition_id,
const std::string &objname,
const TINumber object_id,
const int server_id,
const int num_servers);
int CreateEntry(const TINumber dir_id,
const int partition_id,
const std::string &objname,
const StatInfo &info,
const std::string &realpath,
const std::string &data);
// Returns "0" if MDB removes the file successfully, otherwise "-1" on error.
int Remove(const TINumber dir_id,
const int partition_id,
const std::string &objname);
// Returns "0" if MDB get the file stat successfully,
// otherwise "-ENOENT" when no file is found.
int Getattr(const TINumber dir_id,
const int partition_id,
const std::string &objname,
StatInfo *info);
// Returns "0" if MDB get directory entries successfully,
// otherwise "-ENOENT" when no file is found.
int Readdir(const TINumber dir_id,
const int partition_id,
const std::string &start_key,
int entry_limit,
std::vector<std::string> *buf,
std::string *end_key,
unsigned char *more_entries_flag);
// Returns "0" if MDB get directory entries successfully,
// otherwise "-ENOENT" when no file is found.
int ReaddirPlus(const TINumber dir_id,
const int partition_id,
const std::string &start_key,
int entry_limit,
std::vector<std::string> *names,
std::vector<StatInfo> *entires,
std::string *end_key,
unsigned char *more_entries_flag);
// Returns "0" if MDB extract entries successfully,
// otherwise "-ENOENT" when the target directory is found.
int Extract(const TINumber dir_id,
const int old_partition_id,
const int new_partition_id,
const std::string &dir_with_new_partition,
uint64_t *min_sequence_number,
uint64_t *max_sequence_number);
// Returns "0" if MDB clean extraction successfully,
// otherwise negative integer on error.
int ExtractClean();
// Returns "0" if MDB bulkinsert entries successfully,
// otherwise negative integer on error.
int BulkInsert(const std::string &dir_with_new_partition,
uint64_t min_sequence_number,
uint64_t max_sequence_number);
int ReadBitmap(const TINumber dir_id,
struct giga_mapping_t *map_val);
int CreateBitmap(const TINumber dir_id,
struct giga_mapping_t &map_val,
const int server_id);
int UpdateBitmap(const TINumber dir_id,
const struct giga_mapping_t &map_val);
int Setattr(const TINumber dir_id,
const int partition_id,
const std::string &objname,
const StatInfo &info);
int Chmod(const TINumber dir_id,
const int partition_id,
const std::string &objname,
mode_t new_mode);
int OpenFile(const TINumber dir_id, const int partition_id,
const std::string &objname,
bool *is_embedded, int *data_len, char *data);
int ReadFile(const TINumber dir_id, const int partition_id,
const std::string &objname,
const size_t offset, const size_t *data_len, const char *data);
int WriteFile(const TINumber dir_id, const int partition_id,
const std::string &objname,
const size_t offset, size_t data_len, const char *data);
int WriteLink(const TINumber dir_id, const int partition_id,
const std::string &objname, const std::string &link);
void Close() { metadb_close(&mdb); }
TINumber NewInodeNumber();
TINumber NewInodeBatch(int bulk_size);
};
class ClientMetadataBackend : public MetadataBackend {
public:
std::string path_;
int Init(const std::string& dbname,
const char* hdfsIP,
int hdfsPort,
int serverID) {
return metadb_cliside_init(
&mdb, dbname.c_str(), hdfsIP, hdfsPort, serverID);
};
void Close() { metadb_cliside_close(&mdb); }
};
class ReadonlyMetadataBackend : public MetadataBackend {
public:
int Init(const std::string& dbname,
const char* hdfsIP,
int hdfsPort,
int serverID) {
return metadb_readonly_init(
&mdb, dbname.c_str(), hdfsIP, hdfsPort, serverID);
};
void Close() { metadb_readonly_close(&mdb); }
};
} // namespace indexfs
#endif /* _INDEXFS_BACKEND_METADB_H_ */
| 30.734807 | 84 | 0.624663 | [
"vector"
] |
99521845d7c4de1929989a95c85253aeea6dbd9e | 2,081 | c | C | ImageInLib/ImageInLib/src/printing_function.c | JozoUrban/ImageInLib | 41d30a4845690d474bea0a67b1b8de4d04d43f1c | [
"BSD-3-Clause"
] | null | null | null | ImageInLib/ImageInLib/src/printing_function.c | JozoUrban/ImageInLib | 41d30a4845690d474bea0a67b1b8de4d04d43f1c | [
"BSD-3-Clause"
] | 6 | 2019-02-23T00:36:08.000Z | 2019-09-16T11:40:47.000Z | ImageInLib/ImageInLib/src/printing_function.c | JozoUrban/ImageInLib | 41d30a4845690d474bea0a67b1b8de4d04d43f1c | [
"BSD-3-Clause"
] | 3 | 2019-02-28T10:00:33.000Z | 2019-04-04T10:24:57.000Z | /*
* Author: Markjoe Olunna UBA
* Purpose: ImageInLife project - 4D Image Segmentation Methods
* Language: C
*/
#include <stdio.h>
#include <stdlib.h>
#include "printing_function.h"
bool printing_function3D(unsigned char **array3DPtr, const size_t xDim, const size_t yDim, const size_t zDim)
{
size_t k;
//checks if the memory was allocated
if (array3DPtr == NULL)
return false;
// Addition of salt and pepper noise to 3D image
for (k = 0; k < zDim; k++)
{
printing_function2D(array3DPtr[k], xDim, yDim);
}
return true;
}
bool printing_function2D(unsigned char *array2DPtr, const size_t xDim, const size_t yDim)
{
size_t i, j;
//checks if the memory was allocated
if (array2DPtr == NULL)
return false;
//accessing the array and printing of values to the console
for (i = 0; i <= (xDim + 1); i++) {
for (j = 0; j <= (yDim + 1); j++) {
if ((i == 0) && (j == 0)) {
printf("%c", 218);//top left corner
}//end if
else if ((i == (xDim + 1)) && (j == yDim + 1)) {
printf("%c", 217);//bottom right corner
}//end if
else if ((i == 0) && (j == (yDim + 1))) {
printf("%c", 191);//top right corner
}//end if
else if ((i == (xDim + 1)) && (j == 0)) {
printf("%c", 192);//bottom left corner
}//end if
else if ((i >= 0 && i <= (xDim + 1)) && (j == 0)) {
printf("%c", 179);// boundary for first column
}//end if
else if ((i >= 0 && i <= (xDim + 1)) && (j == (yDim + 1))) {
printf("%c", 179); // boundary for last column
}//end if
else if ((i == 0) && (j >= 0 && j <= (yDim + 1))) {
printf("%c", 196); // boundary for first row
}//end if
else if ((i == (xDim + 1)) && (j >= 0 && j <= (yDim + 1))) {
printf("%c", 196);// boundary for last row
}//end if
else if ((*(array2DPtr + ((i - 1) * yDim) + (j - 1)) == 255)
|| (*(array2DPtr + ((i - 1) * yDim) + (j - 1)) == 0)) {
printf("%c", 219); //printing a shaded rectangle
}//end if
else {
printf("%d", *(array2DPtr + ((i - 1) * yDim) + (j - 1)));//printing a blank space
}
}
printf("\n");
}
return true;
}
| 25.691358 | 109 | 0.542047 | [
"3d"
] |
9955160102f7bcfc2fc98f2631c1ced21c92b3dd | 1,498 | h | C | src/http_client.h | shaunstoltz/cluster_mgr | a9915db4a02e32521981fdb8144483617a96d0a7 | [
"Apache-2.0"
] | 8 | 2021-03-10T06:34:45.000Z | 2021-07-14T11:00:40.000Z | src/http_client.h | shaunstoltz/cluster_mgr | a9915db4a02e32521981fdb8144483617a96d0a7 | [
"Apache-2.0"
] | null | null | null | src/http_client.h | shaunstoltz/cluster_mgr | a9915db4a02e32521981fdb8144483617a96d0a7 | [
"Apache-2.0"
] | 1 | 2021-04-12T02:04:56.000Z | 2021-04-12T02:04:56.000Z | /*
Copyright (c) 2019-2021 ZettaDB inc. All rights reserved.
This source code is licensed under Apache 2.0 License,
combined with Common Clause Condition 1.0, as detailed in the NOTICE file.
*/
#ifndef HTTP_CLIENT_H
#define HTTP_CLIENT_H
#include "sys_config.h"
#include <errno.h>
#include "global.h"
#include <unistd.h>
#include <pthread.h>
#include <vector>
#include <string>
#include <algorithm>
class Http_client
{
public:
enum Http_type {HTTP_NONE, HTTP_GET, HTTP_POST};
enum Content_type {Content_NONE, Content_form_urlencoded, Content_form_data};
static int do_exit;
private:
static Http_client *m_inst;
Http_client();
public:
~Http_client();
static Http_client *get_instance()
{
if (!m_inst) m_inst = new Http_client();
return m_inst;
}
bool Http_client_parse_url(const char *url, char *ip, int *port, char *path);
bool Http_client_content_length(const char* buf, int *length);
bool Http_client_get_filename(const char* filepath, std::string &filename_str);
int Http_client_socket(const char *ip, int port);
int Http_client_get(const char *url);
int Http_client_get_file(const char *url, const char *filename, int *pos);
int Http_client_get_file_range(const char *url, const char *filename, int *pos, int begin, int end);
int Http_client_post_para(const char *url, const char *post_str, std::string &result_str);
int Http_client_post_file(const char *url, const char *post_str, const char *filepath, std::string &result_str);
};
#endif // !HTTP_CLIENT_H
| 31.208333 | 113 | 0.757009 | [
"vector"
] |
9964b523a5159159956ba5b536a36ad228362e38 | 8,738 | h | C | modules/image/lib/PiiHistogram.h | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | 14 | 2015-01-19T22:14:18.000Z | 2020-04-13T23:27:20.000Z | modules/image/lib/PiiHistogram.h | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | null | null | null | modules/image/lib/PiiHistogram.h | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | 14 | 2015-01-16T05:43:15.000Z | 2019-01-29T07:57:11.000Z | /* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#ifndef _PIIHISTOGRAM_H
#define _PIIHISTOGRAM_H
#include "PiiQuantizer.h"
#include "PiiImage.h"
#include <PiiMath.h>
namespace PiiImage
{
/**
* Calculate the histogram of a one-channel image. The result will
* be a row matrix containing the frequencies of all values in the
* input image. The return type is determined by the `T` template
* parameter.
*
* @param image the input image. All integer types are supported. If
* another type is used, each element is casted to an int in
* processing. The minimum value of the image must not be negative.
*
* @param roi region-of-interest. See PiiImage.
*
* @param levels the number of distinct levels in the image. If zero
* is given, the maximum value of the image will be found. For 8 bit
* gray-scale images, use 256.
*
* @return the histogram as a PiiMatrix<T>
*/
template <class T, class U, class Roi> PiiMatrix<T> histogram(const PiiMatrix<U>& image, const Roi& roi, unsigned int levels);
/**
* Calculate the histogram of a one-channel image. This is a
* shorthand for `histogram<int>(image, roi, levels)`.
*/
template <class T, class Roi> inline PiiMatrix<int> histogram(const PiiMatrix<T>& image, const Roi& roi, unsigned int levels)
{
return histogram<int,T,Roi>(image, roi, levels);
}
/**
* Calculate the histogram of a one-channel image. This is a
* shorthand for `histogram<int>(image, PiiImage::DefaultRoi(),
* levels)`.
*/
template <class T> inline PiiMatrix<int> histogram(const PiiMatrix<T>& image, unsigned int levels=0)
{
return histogram<int,T>(image, PiiImage::DefaultRoi(), levels);
}
/**
* Calculate the histogram of a one-channel image. The result will
* be a row matrix containing the frequencies of all values in the
* input image. The return type is determined by the `T` template
* parameter.
*
* @param image the input image. All integer types are supported. If
* another type is used, each element is casted to an int in
* processing. The minimum value of the image must not be negative.
*
* @param roi region-of-interest. See PiiImage.
*
* @param quantizer a quantizer that converts image pixels into
* quantized values.
*/
template <class T, class U, class Roi> PiiMatrix<T> histogram(const PiiMatrix<U>& image, const Roi& roi, const PiiQuantizer<U>& quantizer);
/**
* Calculate the histogram of a one-channel image. This is a
* shorthand for `histogram<int>(image, quantizer)`.
*/
template <class T, class Roi> inline PiiMatrix<int> histogram(const PiiMatrix<T>& image, const Roi& roi, const PiiQuantizer<T>& quantizer)
{
return histogram<int>(image, roi, quantizer);
}
/**
* Calculate the histogram of a one-channel image. This is a
* shorthand for `histogram<int>(image, quantizer,
* PiiImage::DefaultRoi())`.
*/
template <class T> inline PiiMatrix<int> histogram(const PiiMatrix<T>& image, const PiiQuantizer<T>& quantizer)
{
return histogram<int>(image, PiiImage::DefaultRoi(), quantizer);
}
/**
* Calculate the cumulative frequency distribution of the given
* frequency distribution (histogram). The histogram must be
* represented as a row vector. If the input matrix has many rows,
* the cumulative histogram for each row is calculated.
*
* ~~~(c++)
* PiiMatrix<int> histogram(1,5, 1,2,3,4,5);
* PiiMatrix<int> cum(PiiImage::cumulative(histogram)); // sic!
* // cum = (1,3,6,10,15)
* ~~~
*
* @see Pii::cumulativeSum()
*/
template <class T> inline PiiMatrix<T> cumulative(const PiiMatrix<T>& histogram)
{
return Pii::cumulativeSum<T,PiiMatrix<T> >(histogram, Pii::Horizontally);
}
/**
* Normalize the given histogram so that its elements sum up to one.
* If the matrix has many rows, each row is normalized. The return
* type may be different from the input type. Typically, float or
* double is used as the return type. If all values in a row equal
* to zero, they are left as such.
*
* ~~~(c++)
* PiiMatrix<int> histogram(1,4, 1,2,3,4);
* PiiMatrix<double> normalized(PiiImage::normalize<double>(histogram));
* //normalized = (0.1, 0.2, 0.3, 0.4)
* ~~~
*/
template <class T, class U> PiiMatrix<T> normalize(const PiiMatrix<U>& histogram);
/**
* Find the index of the first entry in a cumulative frequency
* distribution that exceeds or equals to the given value. For
* normalized cumulative distributions, `value` should be between 0
* and 1.
*
* ~~~(c++)
* PiiMatrix<double> cumulative(1,4, 0.1, 0.3, 0.6, 1.0);
* int p = percentile(cumulative, 0.5);
* //p = 2
* ~~~
*
* @param cumulative a cumulative frequency distribution. A row
* matrix with monotonically increasing values.
*
* @param value the percentile value, which should be smaller than
* or equal to the maximum value in `cumulative`.
*
* @return the index of the first element exceeding or equal to
* `value`, or -1 if no such element was found
*/
template <class T> int percentile(const PiiMatrix<T>& cumulative, T value);
/**
* Histogram backprojection. In backprojection, each pixel in `img`
* is replaced by the corresponding value in `histogram`. Despite
* histogram backprojection this function can be used to convert
* indexed images to color images.
*
* @param img input image
*
* @param histogram the histogram. A 1-by-N matrix.
*
* The function makes no boundary checks for performance reasons. If
* you aren't sure about your data, you must check that
* `histogram`.columns() is larger than the maximum value in `img`
* and that there are no negative values in `img`.
*
* Since pixels in `img` are used as indices in `histogram`, they
* will be converted to integers. Using floating-point types in the
* `img` parameter is not suggested.
*
* ~~~(c++)
* // Normal backprojection
* PiiMatrix<int> histogram(1,256);
* PiiMatrix<unsigned char> img(100,100);
* PiiMatrix<int> backProjected(PiiImage::backProject(img,histogram));
*
* // Color mapping
* PiiMatrix<PiiColor<> > colorMap(1,256);
* PiiMatrix<unsigned char> indexedImg(100,100);
* PiiMatrix<PiiColor<> > colorImg(PiiImage::backProject(indexedImg, colorMap);
* ~~~
*/
template <class T, class U> PiiMatrix<U> backProject(const PiiMatrix<T>& img, const PiiMatrix<U>& histogram);
/**
* Two-dimensional histogram backprojection. This function is
* analogous to the previous one, but uses a two-dimensional
* histogram for backprojection. It is provided just for convenience
* as two-dimensional distributions can be converted to one
* dimension.
*
* @param ch1 first channel (indexes rows in `histogram`, maximum
* value N-1)
*
* @param ch2 second channel (indexes columns in `histogram`,
* maximum value M-1)
*
* @param histogram two-dimensional histogram (N-by-M)
*
* The sizes of `ch1` and `ch2` must be equal.
*
* ~~~(c++)
* // Backproject a two-dimensional RG histogram
* PiiMatrix<int> histogram(256,256);
* PiiMatrix<unsigned char> redChannel(100,100);
* PiiMatrix<unsigned char> greenChannel(100,100);
* PiiMatrix<int> backProjected(PiiImage::backProject(redChannel, greenChannel, histogram));
* ~~~
*/
template <class T, class U> PiiMatrix<U> backProject(const PiiMatrix<T>& ch1, const PiiMatrix<T>& ch2,
const PiiMatrix<U>& histogram);
/**
* Histogram equalization. Enhances the contrast of `img` by making
* its gray levels as uniformly distributed as possible.
*
* @param img the input image
*
* @param levels the number of quantization levels. If this value is
* omitted, the maximum value found in `image` will be used. If
* `levels` is smaller than the maximum value, the latter will be used.
*
* @return an image with enhanced contrast
*/
template <class T> PiiMatrix<T> equalize(const PiiMatrix<T>& img, unsigned int levels = 0);
};
#include "PiiHistogram-templates.h"
#endif //_PIIHISTOGRAM_H
| 36.869198 | 141 | 0.682078 | [
"vector"
] |
996506a9cf7bbd57d81f8c5936b63cd5ce1a4868 | 41,316 | c | C | source/blender/editors/space_view3d/space_view3d.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | 2 | 2018-06-18T01:50:25.000Z | 2018-06-18T01:50:32.000Z | source/blender/editors/space_view3d/space_view3d.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | source/blender/editors/space_view3d/space_view3d.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2008 Blender Foundation.
* All rights reserved.
*
*
* Contributor(s): Blender Foundation
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/editors/space_view3d/space_view3d.c
* \ingroup spview3d
*/
#include <string.h>
#include <stdio.h>
#include "DNA_material_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "MEM_guardedalloc.h"
#include "BLI_blenlib.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_icons.h"
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_object.h"
#include "BKE_scene.h"
#include "BKE_screen.h"
#include "ED_space_api.h"
#include "ED_screen.h"
#include "GPU_compositing.h"
#include "GPU_framebuffer.h"
#include "GPU_material.h"
#include "BIF_gl.h"
#include "WM_api.h"
#include "WM_types.h"
#include "RE_engine.h"
#include "RE_pipeline.h"
#include "RNA_access.h"
#include "UI_resources.h"
#ifdef WITH_PYTHON
# include "BPY_extern.h"
#endif
#include "DEG_depsgraph.h"
#include "view3d_intern.h" /* own include */
/* ******************** manage regions ********************* */
ARegion *view3d_has_buttons_region(ScrArea *sa)
{
ARegion *ar, *arnew;
ar = BKE_area_find_region_type(sa, RGN_TYPE_UI);
if (ar) return ar;
/* add subdiv level; after header */
ar = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
/* is error! */
if (ar == NULL) return NULL;
arnew = MEM_callocN(sizeof(ARegion), "buttons for view3d");
BLI_insertlinkafter(&sa->regionbase, ar, arnew);
arnew->regiontype = RGN_TYPE_UI;
arnew->alignment = RGN_ALIGN_RIGHT;
arnew->flag = RGN_FLAG_HIDDEN;
return arnew;
}
ARegion *view3d_has_tools_region(ScrArea *sa)
{
ARegion *ar, *artool = NULL, *arprops = NULL, *arhead;
for (ar = sa->regionbase.first; ar; ar = ar->next) {
if (ar->regiontype == RGN_TYPE_TOOLS)
artool = ar;
if (ar->regiontype == RGN_TYPE_TOOL_PROPS)
arprops = ar;
}
/* tool region hide/unhide also hides props */
if (arprops && artool) return artool;
if (artool == NULL) {
/* add subdiv level; after header */
for (arhead = sa->regionbase.first; arhead; arhead = arhead->next)
if (arhead->regiontype == RGN_TYPE_HEADER)
break;
/* is error! */
if (arhead == NULL) return NULL;
artool = MEM_callocN(sizeof(ARegion), "tools for view3d");
BLI_insertlinkafter(&sa->regionbase, arhead, artool);
artool->regiontype = RGN_TYPE_TOOLS;
artool->alignment = RGN_ALIGN_LEFT;
artool->flag = RGN_FLAG_HIDDEN;
}
if (arprops == NULL) {
/* add extra subdivided region for tool properties */
arprops = MEM_callocN(sizeof(ARegion), "tool props for view3d");
BLI_insertlinkafter(&sa->regionbase, artool, arprops);
arprops->regiontype = RGN_TYPE_TOOL_PROPS;
arprops->alignment = RGN_ALIGN_BOTTOM | RGN_SPLIT_PREV;
}
return artool;
}
/* ****************************************************** */
/* function to always find a regionview3d context inside 3D window */
RegionView3D *ED_view3d_context_rv3d(bContext *C)
{
RegionView3D *rv3d = CTX_wm_region_view3d(C);
if (rv3d == NULL) {
ScrArea *sa = CTX_wm_area(C);
if (sa && sa->spacetype == SPACE_VIEW3D) {
ARegion *ar = BKE_area_find_region_active_win(sa);
if (ar) {
rv3d = ar->regiondata;
}
}
}
return rv3d;
}
/* ideally would return an rv3d but in some cases the region is needed too
* so return that, the caller can then access the ar->regiondata */
bool ED_view3d_context_user_region(bContext *C, View3D **r_v3d, ARegion **r_ar)
{
ScrArea *sa = CTX_wm_area(C);
*r_v3d = NULL;
*r_ar = NULL;
if (sa && sa->spacetype == SPACE_VIEW3D) {
ARegion *ar = CTX_wm_region(C);
View3D *v3d = (View3D *)sa->spacedata.first;
if (ar) {
RegionView3D *rv3d;
if ((ar->regiontype == RGN_TYPE_WINDOW) && (rv3d = ar->regiondata) && (rv3d->viewlock & RV3D_LOCKED) == 0) {
*r_v3d = v3d;
*r_ar = ar;
return true;
}
else {
ARegion *ar_unlock_user = NULL;
ARegion *ar_unlock = NULL;
for (ar = sa->regionbase.first; ar; ar = ar->next) {
/* find the first unlocked rv3d */
if (ar->regiondata && ar->regiontype == RGN_TYPE_WINDOW) {
rv3d = ar->regiondata;
if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
ar_unlock = ar;
if (rv3d->persp == RV3D_PERSP || rv3d->persp == RV3D_CAMOB) {
ar_unlock_user = ar;
break;
}
}
}
}
/* camera/perspective view get priority when the active region is locked */
if (ar_unlock_user) {
*r_v3d = v3d;
*r_ar = ar_unlock_user;
return true;
}
if (ar_unlock) {
*r_v3d = v3d;
*r_ar = ar_unlock;
return true;
}
}
}
}
return false;
}
/* Most of the time this isn't needed since you could assume the view matrix was
* set while drawing, however when functions like mesh_foreachScreenVert are
* called by selection tools, we can't be sure this object was the last.
*
* for example, transparent objects are drawn after editmode and will cause
* the rv3d mat's to change and break selection.
*
* 'ED_view3d_init_mats_rv3d' should be called before
* view3d_project_short_clip and view3d_project_short_noclip in cases where
* these functions are not used during draw_object
*/
void ED_view3d_init_mats_rv3d(struct Object *ob, struct RegionView3D *rv3d)
{
/* local viewmat and persmat, to calculate projections */
mul_m4_m4m4(rv3d->viewmatob, rv3d->viewmat, ob->obmat);
mul_m4_m4m4(rv3d->persmatob, rv3d->persmat, ob->obmat);
/* initializes object space clipping, speeds up clip tests */
ED_view3d_clipping_local(rv3d, ob->obmat);
}
void ED_view3d_init_mats_rv3d_gl(struct Object *ob, struct RegionView3D *rv3d)
{
ED_view3d_init_mats_rv3d(ob, rv3d);
/* we have to multiply instead of loading viewmatob to make
* it work with duplis using displists, otherwise it will
* override the dupli-matrix */
glMultMatrixf(ob->obmat);
}
#ifdef DEBUG
/* ensure we correctly initialize */
void ED_view3d_clear_mats_rv3d(struct RegionView3D *rv3d)
{
zero_m4(rv3d->viewmatob);
zero_m4(rv3d->persmatob);
}
void ED_view3d_check_mats_rv3d(struct RegionView3D *rv3d)
{
BLI_ASSERT_ZERO_M4(rv3d->viewmatob);
BLI_ASSERT_ZERO_M4(rv3d->persmatob);
}
#endif
void ED_view3d_stop_render_preview(wmWindowManager *wm, ARegion *ar)
{
RegionView3D *rv3d = ar->regiondata;
if (rv3d->render_engine) {
#ifdef WITH_PYTHON
BPy_BEGIN_ALLOW_THREADS;
#endif
WM_jobs_kill_type(wm, ar, WM_JOB_TYPE_RENDER_PREVIEW);
#ifdef WITH_PYTHON
BPy_END_ALLOW_THREADS;
#endif
if (rv3d->render_engine->re)
RE_Database_Free(rv3d->render_engine->re);
RE_engine_free(rv3d->render_engine);
rv3d->render_engine = NULL;
}
}
void ED_view3d_shade_update(Main *bmain, Scene *scene, View3D *v3d, ScrArea *sa)
{
wmWindowManager *wm = bmain->wm.first;
if (v3d->drawtype != OB_RENDER) {
ARegion *ar;
for (ar = sa->regionbase.first; ar; ar = ar->next) {
if (ar->regiondata)
ED_view3d_stop_render_preview(wm, ar);
}
}
else if (scene->obedit != NULL && scene->obedit->type == OB_MESH) {
/* Tag mesh to load edit data. */
DAG_id_tag_update(scene->obedit->data, 0);
}
}
/* ******************** default callbacks for view3d space ***************** */
static SpaceLink *view3d_new(const bContext *C)
{
Scene *scene = CTX_data_scene(C);
ARegion *ar;
View3D *v3d;
RegionView3D *rv3d;
v3d = MEM_callocN(sizeof(View3D), "initview3d");
v3d->spacetype = SPACE_VIEW3D;
v3d->blockscale = 0.7f;
v3d->lay = v3d->layact = 1;
if (scene) {
v3d->lay = v3d->layact = scene->lay;
v3d->camera = scene->camera;
}
v3d->scenelock = true;
v3d->grid = 1.0f;
v3d->gridlines = 16;
v3d->gridsubdiv = 10;
v3d->drawtype = OB_SOLID;
v3d->gridflag = V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_FLOOR;
v3d->flag = V3D_SELECT_OUTLINE;
v3d->flag2 = V3D_SHOW_RECONSTRUCTION | V3D_SHOW_GPENCIL;
v3d->lens = 35.0f;
v3d->near = 0.01f;
v3d->far = 1000.0f;
v3d->twflag |= U.tw_flag & V3D_USE_MANIPULATOR;
v3d->twtype = V3D_MANIP_TRANSLATE;
v3d->around = V3D_AROUND_CENTER_MEAN;
v3d->bundle_size = 0.2f;
v3d->bundle_drawtype = OB_PLAINAXES;
/* stereo */
v3d->stereo3d_camera = STEREO_3D_ID;
v3d->stereo3d_flag |= V3D_S3D_DISPPLANE;
v3d->stereo3d_convergence_alpha = 0.15f;
v3d->stereo3d_volume_alpha = 0.05f;
/* header */
ar = MEM_callocN(sizeof(ARegion), "header for view3d");
BLI_addtail(&v3d->regionbase, ar);
ar->regiontype = RGN_TYPE_HEADER;
ar->alignment = RGN_ALIGN_BOTTOM;
/* tool shelf */
ar = MEM_callocN(sizeof(ARegion), "toolshelf for view3d");
BLI_addtail(&v3d->regionbase, ar);
ar->regiontype = RGN_TYPE_TOOLS;
ar->alignment = RGN_ALIGN_LEFT;
ar->flag = RGN_FLAG_HIDDEN;
/* tool properties */
ar = MEM_callocN(sizeof(ARegion), "tool properties for view3d");
BLI_addtail(&v3d->regionbase, ar);
ar->regiontype = RGN_TYPE_TOOL_PROPS;
ar->alignment = RGN_ALIGN_BOTTOM | RGN_SPLIT_PREV;
ar->flag = RGN_FLAG_HIDDEN;
/* buttons/list view */
ar = MEM_callocN(sizeof(ARegion), "buttons for view3d");
BLI_addtail(&v3d->regionbase, ar);
ar->regiontype = RGN_TYPE_UI;
ar->alignment = RGN_ALIGN_RIGHT;
ar->flag = RGN_FLAG_HIDDEN;
/* main region */
ar = MEM_callocN(sizeof(ARegion), "main region for view3d");
BLI_addtail(&v3d->regionbase, ar);
ar->regiontype = RGN_TYPE_WINDOW;
ar->regiondata = MEM_callocN(sizeof(RegionView3D), "region view3d");
rv3d = ar->regiondata;
rv3d->viewquat[0] = 1.0f;
rv3d->persp = RV3D_PERSP;
rv3d->view = RV3D_VIEW_USER;
rv3d->dist = 10.0;
return (SpaceLink *)v3d;
}
/* not spacelink itself */
static void view3d_free(SpaceLink *sl)
{
View3D *vd = (View3D *) sl;
BGpic *bgpic;
for (bgpic = vd->bgpicbase.first; bgpic; bgpic = bgpic->next) {
if (bgpic->source == V3D_BGPIC_IMAGE) {
id_us_min((ID *)bgpic->ima);
}
else if (bgpic->source == V3D_BGPIC_MOVIE) {
id_us_min((ID *)bgpic->clip);
}
}
BLI_freelistN(&vd->bgpicbase);
if (vd->localvd) MEM_freeN(vd->localvd);
if (vd->properties_storage) MEM_freeN(vd->properties_storage);
/* matcap material, its preview rect gets freed via icons */
if (vd->defmaterial) {
if (vd->defmaterial->gpumaterial.first)
GPU_material_free(&vd->defmaterial->gpumaterial);
BKE_previewimg_free(&vd->defmaterial->preview);
MEM_freeN(vd->defmaterial);
}
if (vd->fx_settings.ssao)
MEM_freeN(vd->fx_settings.ssao);
if (vd->fx_settings.dof)
MEM_freeN(vd->fx_settings.dof);
}
/* spacetype; init callback */
static void view3d_init(wmWindowManager *UNUSED(wm), ScrArea *UNUSED(sa))
{
}
static SpaceLink *view3d_duplicate(SpaceLink *sl)
{
View3D *v3do = (View3D *)sl;
View3D *v3dn = MEM_dupallocN(sl);
BGpic *bgpic;
/* clear or remove stuff from old */
if (v3dn->localvd) {
v3dn->localvd = NULL;
v3dn->properties_storage = NULL;
v3dn->lay = v3do->localvd->lay & 0xFFFFFF;
}
if (v3dn->drawtype == OB_RENDER)
v3dn->drawtype = OB_SOLID;
/* copy or clear inside new stuff */
v3dn->defmaterial = NULL;
BLI_duplicatelist(&v3dn->bgpicbase, &v3do->bgpicbase);
for (bgpic = v3dn->bgpicbase.first; bgpic; bgpic = bgpic->next) {
if (bgpic->source == V3D_BGPIC_IMAGE) {
id_us_plus((ID *)bgpic->ima);
}
else if (bgpic->source == V3D_BGPIC_MOVIE) {
id_us_plus((ID *)bgpic->clip);
}
}
v3dn->properties_storage = NULL;
if (v3dn->fx_settings.dof)
v3dn->fx_settings.dof = MEM_dupallocN(v3do->fx_settings.dof);
if (v3dn->fx_settings.ssao)
v3dn->fx_settings.ssao = MEM_dupallocN(v3do->fx_settings.ssao);
return (SpaceLink *)v3dn;
}
/* add handlers, stuff you only do once or on area/region changes */
static void view3d_main_region_init(wmWindowManager *wm, ARegion *ar)
{
ListBase *lb;
wmKeyMap *keymap;
/* object ops. */
/* important to be before Pose keymap since they can both be enabled at once */
keymap = WM_keymap_find(wm->defaultconf, "Face Mask", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Weight Paint Vertex Selection", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
/* pose is not modal, operator poll checks for this */
keymap = WM_keymap_find(wm->defaultconf, "Pose", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Object Mode", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Paint Curve", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Curve", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Image Paint", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Vertex Paint", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Weight Paint", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Sculpt", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Mesh", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Curve", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Armature", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Pose", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Metaball", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Lattice", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Particle", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
/* editfont keymap swallows all... */
keymap = WM_keymap_find(wm->defaultconf, "Font", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Object Non-modal", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "Frames", 0, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
/* own keymap, last so modes can override it */
keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
keymap = WM_keymap_find(wm->defaultconf, "3D View", SPACE_VIEW3D, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
/* add drop boxes */
lb = WM_dropboxmap_find("View3D", SPACE_VIEW3D, RGN_TYPE_WINDOW);
WM_event_add_dropbox_handler(&ar->handlers, lb);
}
static void view3d_main_region_exit(wmWindowManager *wm, ARegion *ar)
{
RegionView3D *rv3d = ar->regiondata;
ED_view3d_stop_render_preview(wm, ar);
if (rv3d->gpuoffscreen) {
GPU_offscreen_free(rv3d->gpuoffscreen);
rv3d->gpuoffscreen = NULL;
}
if (rv3d->compositor) {
GPU_fx_compositor_destroy(rv3d->compositor);
rv3d->compositor = NULL;
}
}
static int view3d_ob_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event))
{
if (drag->type == WM_DRAG_ID) {
ID *id = drag->poin;
if (GS(id->name) == ID_OB)
return 1;
}
return 0;
}
static int view3d_group_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event))
{
if (drag->type == WM_DRAG_ID) {
ID *id = drag->poin;
if (GS(id->name) == ID_GR)
return 1;
}
return 0;
}
static int view3d_mat_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event))
{
if (drag->type == WM_DRAG_ID) {
ID *id = drag->poin;
if (GS(id->name) == ID_MA)
return 1;
}
return 0;
}
static int view3d_ima_drop_poll(bContext *UNUSED(C), wmDrag *drag, const wmEvent *UNUSED(event))
{
if (drag->type == WM_DRAG_ID) {
ID *id = drag->poin;
if (GS(id->name) == ID_IM)
return 1;
}
else if (drag->type == WM_DRAG_PATH) {
if (ELEM(drag->icon, 0, ICON_FILE_IMAGE, ICON_FILE_MOVIE)) /* rule might not work? */
return 1;
}
return 0;
}
static int view3d_ima_bg_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event)
{
if (event->ctrl)
return false;
if (!ED_view3d_give_base_under_cursor(C, event->mval)) {
return view3d_ima_drop_poll(C, drag, event);
}
return 0;
}
static int view3d_ima_empty_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event)
{
Base *base = ED_view3d_give_base_under_cursor(C, event->mval);
/* either holding and ctrl and no object, or dropping to empty */
if (((base == NULL) && event->ctrl) ||
((base != NULL) && base->object->type == OB_EMPTY))
{
return view3d_ima_drop_poll(C, drag, event);
}
return 0;
}
static int view3d_ima_mesh_drop_poll(bContext *C, wmDrag *drag, const wmEvent *event)
{
Base *base = ED_view3d_give_base_under_cursor(C, event->mval);
if (base && base->object->type == OB_MESH)
return view3d_ima_drop_poll(C, drag, event);
return 0;
}
static void view3d_ob_drop_copy(wmDrag *drag, wmDropBox *drop)
{
ID *id = drag->poin;
RNA_string_set(drop->ptr, "name", id->name + 2);
}
static void view3d_group_drop_copy(wmDrag *drag, wmDropBox *drop)
{
ID *id = drag->poin;
drop->opcontext = WM_OP_EXEC_DEFAULT;
RNA_string_set(drop->ptr, "name", id->name + 2);
}
static void view3d_id_drop_copy(wmDrag *drag, wmDropBox *drop)
{
ID *id = drag->poin;
RNA_string_set(drop->ptr, "name", id->name + 2);
}
static void view3d_id_path_drop_copy(wmDrag *drag, wmDropBox *drop)
{
ID *id = drag->poin;
if (id) {
RNA_string_set(drop->ptr, "name", id->name + 2);
RNA_struct_property_unset(drop->ptr, "filepath");
}
else if (drag->path[0]) {
RNA_string_set(drop->ptr, "filepath", drag->path);
RNA_struct_property_unset(drop->ptr, "image");
}
}
/* region dropbox definition */
static void view3d_dropboxes(void)
{
ListBase *lb = WM_dropboxmap_find("View3D", SPACE_VIEW3D, RGN_TYPE_WINDOW);
WM_dropbox_add(lb, "OBJECT_OT_add_named", view3d_ob_drop_poll, view3d_ob_drop_copy);
WM_dropbox_add(lb, "OBJECT_OT_drop_named_material", view3d_mat_drop_poll, view3d_id_drop_copy);
WM_dropbox_add(lb, "MESH_OT_drop_named_image", view3d_ima_mesh_drop_poll, view3d_id_path_drop_copy);
WM_dropbox_add(lb, "OBJECT_OT_drop_named_image", view3d_ima_empty_drop_poll, view3d_id_path_drop_copy);
WM_dropbox_add(lb, "VIEW3D_OT_background_image_add", view3d_ima_bg_drop_poll, view3d_id_path_drop_copy);
WM_dropbox_add(lb, "OBJECT_OT_group_instance_add", view3d_group_drop_poll, view3d_group_drop_copy);
}
/* type callback, not region itself */
static void view3d_main_region_free(ARegion *ar)
{
RegionView3D *rv3d = ar->regiondata;
if (rv3d) {
if (rv3d->localvd) MEM_freeN(rv3d->localvd);
if (rv3d->clipbb) MEM_freeN(rv3d->clipbb);
if (rv3d->render_engine)
RE_engine_free(rv3d->render_engine);
if (rv3d->depths) {
if (rv3d->depths->depths) MEM_freeN(rv3d->depths->depths);
MEM_freeN(rv3d->depths);
}
if (rv3d->sms) {
MEM_freeN(rv3d->sms);
}
if (rv3d->gpuoffscreen) {
GPU_offscreen_free(rv3d->gpuoffscreen);
}
if (rv3d->compositor) {
GPU_fx_compositor_destroy(rv3d->compositor);
}
MEM_freeN(rv3d);
ar->regiondata = NULL;
}
}
/* copy regiondata */
static void *view3d_main_region_duplicate(void *poin)
{
if (poin) {
RegionView3D *rv3d = poin, *new;
new = MEM_dupallocN(rv3d);
if (rv3d->localvd)
new->localvd = MEM_dupallocN(rv3d->localvd);
if (rv3d->clipbb)
new->clipbb = MEM_dupallocN(rv3d->clipbb);
new->depths = NULL;
new->gpuoffscreen = NULL;
new->render_engine = NULL;
new->sms = NULL;
new->smooth_timer = NULL;
new->compositor = NULL;
return new;
}
return NULL;
}
static void view3d_recalc_used_layers(ARegion *ar, wmNotifier *wmn, Scene *scene)
{
wmWindow *win = wmn->wm->winactive;
ScrArea *sa;
unsigned int lay_used = 0;
Base *base;
if (!win) return;
base = scene->base.first;
while (base) {
lay_used |= base->lay & ((1 << 20) - 1); /* ignore localview */
if (lay_used == (1 << 20) - 1)
break;
base = base->next;
}
for (sa = win->screen->areabase.first; sa; sa = sa->next) {
if (sa->spacetype == SPACE_VIEW3D) {
if (BLI_findindex(&sa->regionbase, ar) != -1) {
View3D *v3d = sa->spacedata.first;
v3d->lay_used = lay_used;
break;
}
}
}
}
static void view3d_main_region_listener(bScreen *sc, ScrArea *sa, ARegion *ar, wmNotifier *wmn)
{
Scene *scene = sc->scene;
View3D *v3d = sa->spacedata.first;
/* context changes */
switch (wmn->category) {
case NC_ANIMATION:
switch (wmn->data) {
case ND_KEYFRAME_PROP:
case ND_NLA_ACTCHANGE:
ED_region_tag_redraw(ar);
break;
case ND_NLA:
case ND_KEYFRAME:
if (ELEM(wmn->action, NA_EDITED, NA_ADDED, NA_REMOVED))
ED_region_tag_redraw(ar);
break;
case ND_ANIMCHAN:
if (wmn->action == NA_SELECTED)
ED_region_tag_redraw(ar);
break;
}
break;
case NC_SCENE:
switch (wmn->data) {
case ND_LAYER_CONTENT:
if (wmn->reference)
view3d_recalc_used_layers(ar, wmn, wmn->reference);
ED_region_tag_redraw(ar);
break;
case ND_FRAME:
case ND_TRANSFORM:
case ND_OB_ACTIVE:
case ND_OB_SELECT:
case ND_OB_VISIBLE:
case ND_LAYER:
case ND_RENDER_OPTIONS:
case ND_MARKERS:
case ND_MODE:
ED_region_tag_redraw(ar);
break;
case ND_WORLD:
/* handled by space_view3d_listener() for v3d access */
break;
case ND_DRAW_RENDER_VIEWPORT:
{
if (v3d->camera && (scene == wmn->reference)) {
RegionView3D *rv3d = ar->regiondata;
if (rv3d->persp == RV3D_CAMOB) {
ED_region_tag_redraw(ar);
}
}
break;
}
}
if (wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
break;
case NC_OBJECT:
switch (wmn->data) {
case ND_BONE_ACTIVE:
case ND_BONE_SELECT:
case ND_TRANSFORM:
case ND_POSE:
case ND_DRAW:
case ND_MODIFIER:
case ND_CONSTRAINT:
case ND_KEYS:
case ND_PARTICLE:
case ND_POINTCACHE:
case ND_LOD:
ED_region_tag_redraw(ar);
break;
}
switch (wmn->action) {
case NA_ADDED:
ED_region_tag_redraw(ar);
break;
}
break;
case NC_GEOM:
switch (wmn->data) {
case ND_DATA:
case ND_VERTEX_GROUP:
case ND_SELECT:
ED_region_tag_redraw(ar);
break;
}
switch (wmn->action) {
case NA_EDITED:
ED_region_tag_redraw(ar);
break;
}
break;
case NC_CAMERA:
switch (wmn->data) {
case ND_DRAW_RENDER_VIEWPORT:
{
if (v3d->camera && (v3d->camera->data == wmn->reference)) {
RegionView3D *rv3d = ar->regiondata;
if (rv3d->persp == RV3D_CAMOB) {
ED_region_tag_redraw(ar);
}
}
break;
}
}
break;
case NC_GROUP:
/* all group ops for now */
ED_region_tag_redraw(ar);
break;
case NC_BRUSH:
switch (wmn->action) {
case NA_EDITED:
ED_region_tag_redraw_overlay(ar);
break;
case NA_SELECTED:
/* used on brush changes - needed because 3d cursor
* has to be drawn if clone brush is selected */
ED_region_tag_redraw(ar);
break;
}
break;
case NC_MATERIAL:
switch (wmn->data) {
case ND_SHADING:
case ND_NODES:
{
#ifdef WITH_LEGACY_DEPSGRAPH
Object *ob = OBACT;
if ((v3d->drawtype == OB_MATERIAL) ||
(ob && (ob->mode == OB_MODE_TEXTURE_PAINT)) ||
(v3d->drawtype == OB_TEXTURE &&
(scene->gm.matmode == GAME_MAT_GLSL ||
BKE_scene_use_new_shading_nodes(scene))) ||
!DEG_depsgraph_use_legacy())
#endif
{
ED_region_tag_redraw(ar);
}
break;
}
case ND_SHADING_DRAW:
case ND_SHADING_LINKS:
ED_region_tag_redraw(ar);
break;
}
break;
case NC_WORLD:
switch (wmn->data) {
case ND_WORLD_DRAW:
/* handled by space_view3d_listener() for v3d access */
break;
}
break;
case NC_LAMP:
switch (wmn->data) {
case ND_LIGHTING:
if ((v3d->drawtype == OB_MATERIAL) ||
(v3d->drawtype == OB_TEXTURE && (scene->gm.matmode == GAME_MAT_GLSL)) ||
!DEG_depsgraph_use_legacy())
{
ED_region_tag_redraw(ar);
}
break;
case ND_LIGHTING_DRAW:
ED_region_tag_redraw(ar);
break;
}
break;
case NC_IMAGE:
/* this could be more fine grained checks if we had
* more context than just the region */
ED_region_tag_redraw(ar);
break;
case NC_TEXTURE:
/* same as above */
ED_region_tag_redraw(ar);
break;
case NC_MOVIECLIP:
if (wmn->data == ND_DISPLAY || wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
break;
case NC_SPACE:
if (wmn->data == ND_SPACE_VIEW3D) {
if (wmn->subtype == NS_VIEW3D_GPU) {
RegionView3D *rv3d = ar->regiondata;
rv3d->rflag |= RV3D_GPULIGHT_UPDATE;
}
ED_region_tag_redraw(ar);
}
break;
case NC_ID:
if (wmn->action == NA_RENAME)
ED_region_tag_redraw(ar);
break;
case NC_SCREEN:
switch (wmn->data) {
case ND_ANIMPLAY:
case ND_SKETCH:
ED_region_tag_redraw(ar);
break;
case ND_SCREENBROWSE:
case ND_SCREENDELETE:
case ND_SCREENSET:
/* screen was changed, need to update used layers due to NC_SCENE|ND_LAYER_CONTENT */
/* updates used layers only for View3D in active screen */
if (wmn->reference) {
bScreen *sc_ref = wmn->reference;
view3d_recalc_used_layers(ar, wmn, sc_ref->scene);
}
ED_region_tag_redraw(ar);
break;
}
break;
case NC_GPENCIL:
if (wmn->data == ND_DATA || ELEM(wmn->action, NA_EDITED, NA_SELECTED)) {
ED_region_tag_redraw(ar);
}
break;
}
}
/* concept is to retrieve cursor type context-less */
static void view3d_main_region_cursor(wmWindow *win, ScrArea *UNUSED(sa), ARegion *UNUSED(ar))
{
Scene *scene = win->screen->scene;
if (scene->obedit) {
WM_cursor_set(win, CURSOR_EDIT);
}
else {
WM_cursor_set(win, CURSOR_STD);
}
}
/* add handlers, stuff you only do once or on area/region changes */
static void view3d_header_region_init(wmWindowManager *wm, ARegion *ar)
{
wmKeyMap *keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
ED_region_header_init(ar);
}
static void view3d_header_region_draw(const bContext *C, ARegion *ar)
{
ED_region_header(C, ar);
}
static void view3d_header_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
case NC_SCENE:
switch (wmn->data) {
case ND_FRAME:
case ND_OB_ACTIVE:
case ND_OB_SELECT:
case ND_OB_VISIBLE:
case ND_MODE:
case ND_LAYER:
case ND_TOOLSETTINGS:
case ND_LAYER_CONTENT:
case ND_RENDER_OPTIONS:
ED_region_tag_redraw(ar);
break;
}
break;
case NC_SPACE:
if (wmn->data == ND_SPACE_VIEW3D)
ED_region_tag_redraw(ar);
break;
case NC_GPENCIL:
if (wmn->data & ND_GPENCIL_EDITMODE)
ED_region_tag_redraw(ar);
break;
}
}
/* add handlers, stuff you only do once or on area/region changes */
static void view3d_buttons_region_init(wmWindowManager *wm, ARegion *ar)
{
wmKeyMap *keymap;
ED_region_panels_init(wm, ar);
keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
}
static void view3d_buttons_region_draw(const bContext *C, ARegion *ar)
{
ED_region_panels(C, ar, NULL, -1, true);
}
static void view3d_buttons_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
case NC_ANIMATION:
switch (wmn->data) {
case ND_KEYFRAME_PROP:
case ND_NLA_ACTCHANGE:
ED_region_tag_redraw(ar);
break;
case ND_NLA:
case ND_KEYFRAME:
if (ELEM(wmn->action, NA_EDITED, NA_ADDED, NA_REMOVED))
ED_region_tag_redraw(ar);
break;
}
break;
case NC_SCENE:
switch (wmn->data) {
case ND_FRAME:
case ND_OB_ACTIVE:
case ND_OB_SELECT:
case ND_OB_VISIBLE:
case ND_MODE:
case ND_LAYER:
case ND_LAYER_CONTENT:
case ND_TOOLSETTINGS:
ED_region_tag_redraw(ar);
break;
}
switch (wmn->action) {
case NA_EDITED:
ED_region_tag_redraw(ar);
break;
}
break;
case NC_OBJECT:
switch (wmn->data) {
case ND_BONE_ACTIVE:
case ND_BONE_SELECT:
case ND_TRANSFORM:
case ND_POSE:
case ND_DRAW:
case ND_KEYS:
case ND_MODIFIER:
ED_region_tag_redraw(ar);
break;
}
break;
case NC_GEOM:
switch (wmn->data) {
case ND_DATA:
case ND_VERTEX_GROUP:
case ND_SELECT:
ED_region_tag_redraw(ar);
break;
}
if (wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
break;
case NC_TEXTURE:
case NC_MATERIAL:
/* for brush textures */
ED_region_tag_redraw(ar);
break;
case NC_BRUSH:
/* NA_SELECTED is used on brush changes */
if (ELEM(wmn->action, NA_EDITED, NA_SELECTED))
ED_region_tag_redraw(ar);
break;
case NC_SPACE:
if (wmn->data == ND_SPACE_VIEW3D)
ED_region_tag_redraw(ar);
break;
case NC_ID:
if (wmn->action == NA_RENAME)
ED_region_tag_redraw(ar);
break;
case NC_GPENCIL:
if ((wmn->data & (ND_DATA | ND_GPENCIL_EDITMODE)) || (wmn->action == NA_EDITED))
ED_region_tag_redraw(ar);
break;
case NC_IMAGE:
/* Update for the image layers in texture paint. */
if (wmn->action == NA_EDITED)
ED_region_tag_redraw(ar);
break;
}
}
/* add handlers, stuff you only do once or on area/region changes */
static void view3d_tools_region_init(wmWindowManager *wm, ARegion *ar)
{
wmKeyMap *keymap;
ED_region_panels_init(wm, ar);
keymap = WM_keymap_find(wm->defaultconf, "3D View Generic", SPACE_VIEW3D, 0);
WM_event_add_keymap_handler(&ar->handlers, keymap);
}
static void view3d_tools_region_draw(const bContext *C, ARegion *ar)
{
ED_region_panels(C, ar, CTX_data_mode_string(C), -1, true);
}
static void view3d_props_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegion *ar, wmNotifier *wmn)
{
/* context changes */
switch (wmn->category) {
case NC_WM:
if (wmn->data == ND_HISTORY)
ED_region_tag_redraw(ar);
break;
case NC_SCENE:
if (wmn->data == ND_MODE)
ED_region_tag_redraw(ar);
break;
case NC_SPACE:
if (wmn->data == ND_SPACE_VIEW3D)
ED_region_tag_redraw(ar);
break;
}
}
/* area (not region) level listener */
static void space_view3d_listener(bScreen *UNUSED(sc), ScrArea *sa, struct wmNotifier *wmn)
{
View3D *v3d = sa->spacedata.first;
/* context changes */
switch (wmn->category) {
case NC_SCENE:
switch (wmn->data) {
case ND_WORLD:
if (v3d->flag2 & V3D_RENDER_OVERRIDE)
ED_area_tag_redraw_regiontype(sa, RGN_TYPE_WINDOW);
break;
}
break;
case NC_WORLD:
switch (wmn->data) {
case ND_WORLD_DRAW:
case ND_WORLD:
if (v3d->flag3 & V3D_SHOW_WORLD)
ED_area_tag_redraw_regiontype(sa, RGN_TYPE_WINDOW);
break;
}
break;
case NC_MATERIAL:
switch (wmn->data) {
case ND_NODES:
if (v3d->drawtype == OB_TEXTURE)
ED_area_tag_redraw_regiontype(sa, RGN_TYPE_WINDOW);
break;
}
break;
}
}
const char *view3d_context_dir[] = {
"selected_objects", "selected_bases", "selected_editable_objects",
"selected_editable_bases", "visible_objects", "visible_bases", "selectable_objects", "selectable_bases",
"active_base", "active_object", NULL
};
static int view3d_context(const bContext *C, const char *member, bContextDataResult *result)
{
/* fallback to the scene layer, allows duplicate and other object operators to run outside the 3d view */
if (CTX_data_dir(member)) {
CTX_data_dir_set(result, view3d_context_dir);
}
else if (CTX_data_equals(member, "selected_objects") || CTX_data_equals(member, "selected_bases")) {
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
const unsigned int lay = v3d ? v3d->lay : scene->lay;
Base *base;
const bool selected_objects = CTX_data_equals(member, "selected_objects");
for (base = scene->base.first; base; base = base->next) {
if ((base->flag & SELECT) && (base->lay & lay)) {
if ((base->object->restrictflag & OB_RESTRICT_VIEW) == 0) {
if (selected_objects)
CTX_data_id_list_add(result, &base->object->id);
else
CTX_data_list_add(result, &scene->id, &RNA_ObjectBase, base);
}
}
}
CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
return 1;
}
else if (CTX_data_equals(member, "selected_editable_objects") || CTX_data_equals(member, "selected_editable_bases")) {
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
const unsigned int lay = v3d ? v3d->lay : scene->lay;
Base *base;
const bool selected_editable_objects = CTX_data_equals(member, "selected_editable_objects");
for (base = scene->base.first; base; base = base->next) {
if ((base->flag & SELECT) && (base->lay & lay)) {
if ((base->object->restrictflag & OB_RESTRICT_VIEW) == 0) {
if (0 == BKE_object_is_libdata(base->object)) {
if (selected_editable_objects)
CTX_data_id_list_add(result, &base->object->id);
else
CTX_data_list_add(result, &scene->id, &RNA_ObjectBase, base);
}
}
}
}
CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
return 1;
}
else if (CTX_data_equals(member, "visible_objects") || CTX_data_equals(member, "visible_bases")) {
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
const unsigned int lay = v3d ? v3d->lay : scene->lay;
Base *base;
const bool visible_objects = CTX_data_equals(member, "visible_objects");
for (base = scene->base.first; base; base = base->next) {
if (base->lay & lay) {
if ((base->object->restrictflag & OB_RESTRICT_VIEW) == 0) {
if (visible_objects)
CTX_data_id_list_add(result, &base->object->id);
else
CTX_data_list_add(result, &scene->id, &RNA_ObjectBase, base);
}
}
}
CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
return 1;
}
else if (CTX_data_equals(member, "selectable_objects") || CTX_data_equals(member, "selectable_bases")) {
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
const unsigned int lay = v3d ? v3d->lay : scene->lay;
Base *base;
const bool selectable_objects = CTX_data_equals(member, "selectable_objects");
for (base = scene->base.first; base; base = base->next) {
if (base->lay & lay) {
if ((base->object->restrictflag & OB_RESTRICT_VIEW) == 0 && (base->object->restrictflag & OB_RESTRICT_SELECT) == 0) {
if (selectable_objects)
CTX_data_id_list_add(result, &base->object->id);
else
CTX_data_list_add(result, &scene->id, &RNA_ObjectBase, base);
}
}
}
CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
return 1;
}
else if (CTX_data_equals(member, "active_base")) {
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
const unsigned int lay = v3d ? v3d->lay : scene->lay;
if (scene->basact && (scene->basact->lay & lay)) {
Object *ob = scene->basact->object;
/* if hidden but in edit mode, we still display, can happen with animation */
if ((ob->restrictflag & OB_RESTRICT_VIEW) == 0 || (ob->mode & OB_MODE_EDIT))
CTX_data_pointer_set(result, &scene->id, &RNA_ObjectBase, scene->basact);
}
return 1;
}
else if (CTX_data_equals(member, "active_object")) {
View3D *v3d = CTX_wm_view3d(C);
Scene *scene = CTX_data_scene(C);
const unsigned int lay = v3d ? v3d->lay : scene->lay;
if (scene->basact && (scene->basact->lay & lay)) {
Object *ob = scene->basact->object;
if ((ob->restrictflag & OB_RESTRICT_VIEW) == 0 || (ob->mode & OB_MODE_EDIT))
CTX_data_id_pointer_set(result, &scene->basact->object->id);
}
return 1;
}
else {
return 0; /* not found */
}
return -1; /* found but not available */
}
static void view3d_id_remap(ScrArea *sa, SpaceLink *slink, ID *old_id, ID *new_id)
{
View3D *v3d;
ARegion *ar;
bool is_local = false;
if (!ELEM(GS(old_id->name), ID_OB, ID_MA, ID_IM, ID_MC)) {
return;
}
for (v3d = (View3D *)slink; v3d; v3d = v3d->localvd, is_local = true) {
if ((ID *)v3d->camera == old_id) {
v3d->camera = (Object *)new_id;
if (!new_id) {
/* 3D view might be inactive, in that case needs to use slink->regionbase */
ListBase *regionbase = (slink == sa->spacedata.first) ? &sa->regionbase : &slink->regionbase;
for (ar = regionbase->first; ar; ar = ar->next) {
if (ar->regiontype == RGN_TYPE_WINDOW) {
RegionView3D *rv3d = is_local ? ((RegionView3D *)ar->regiondata)->localvd : ar->regiondata;
if (rv3d && (rv3d->persp == RV3D_CAMOB)) {
rv3d->persp = RV3D_PERSP;
}
}
}
}
}
/* Values in local-view aren't used, see: T52663 */
if (is_local == false) {
/* Skip 'v3d->defmaterial', it's not library data. */
if ((ID *)v3d->ob_centre == old_id) {
v3d->ob_centre = (Object *)new_id;
/* Otherwise, bonename may remain valid... We could be smart and check this, too? */
if (new_id == NULL) {
v3d->ob_centre_bone[0] = '\0';
}
}
if (ELEM(GS(old_id->name), ID_IM, ID_MC)) {
for (BGpic *bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
if ((ID *)bgpic->ima == old_id) {
bgpic->ima = (Image *)new_id;
id_us_min(old_id);
id_us_plus(new_id);
}
if ((ID *)bgpic->clip == old_id) {
bgpic->clip = (MovieClip *)new_id;
id_us_min(old_id);
id_us_plus(new_id);
}
}
}
}
if (is_local) {
break;
}
}
}
/* only called once, from space/spacetypes.c */
void ED_spacetype_view3d(void)
{
SpaceType *st = MEM_callocN(sizeof(SpaceType), "spacetype view3d");
ARegionType *art;
st->spaceid = SPACE_VIEW3D;
strncpy(st->name, "View3D", BKE_ST_MAXNAME);
st->new = view3d_new;
st->free = view3d_free;
st->init = view3d_init;
st->listener = space_view3d_listener;
st->duplicate = view3d_duplicate;
st->operatortypes = view3d_operatortypes;
st->keymap = view3d_keymap;
st->dropboxes = view3d_dropboxes;
st->context = view3d_context;
st->id_remap = view3d_id_remap;
/* regions: main window */
art = MEM_callocN(sizeof(ARegionType), "spacetype view3d main region");
art->regionid = RGN_TYPE_WINDOW;
art->keymapflag = ED_KEYMAP_GPENCIL;
art->draw = view3d_main_region_draw;
art->init = view3d_main_region_init;
art->exit = view3d_main_region_exit;
art->free = view3d_main_region_free;
art->duplicate = view3d_main_region_duplicate;
art->listener = view3d_main_region_listener;
art->cursor = view3d_main_region_cursor;
art->lock = 1; /* can become flag, see BKE_spacedata_draw_locks */
BLI_addhead(&st->regiontypes, art);
/* regions: listview/buttons */
art = MEM_callocN(sizeof(ARegionType), "spacetype view3d buttons region");
art->regionid = RGN_TYPE_UI;
art->prefsizex = 180; /* XXX */
art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES;
art->listener = view3d_buttons_region_listener;
art->init = view3d_buttons_region_init;
art->draw = view3d_buttons_region_draw;
BLI_addhead(&st->regiontypes, art);
view3d_buttons_register(art);
/* regions: tool(bar) */
art = MEM_callocN(sizeof(ARegionType), "spacetype view3d tools region");
art->regionid = RGN_TYPE_TOOLS;
art->prefsizex = 160; /* XXX */
art->prefsizey = 50; /* XXX */
art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES;
art->listener = view3d_buttons_region_listener;
art->init = view3d_tools_region_init;
art->draw = view3d_tools_region_draw;
BLI_addhead(&st->regiontypes, art);
#if 0
/* unfinished still */
view3d_toolshelf_register(art);
#endif
/* regions: tool properties */
art = MEM_callocN(sizeof(ARegionType), "spacetype view3d tool properties region");
art->regionid = RGN_TYPE_TOOL_PROPS;
art->prefsizex = 0;
art->prefsizey = 120;
art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES;
art->listener = view3d_props_region_listener;
art->init = view3d_tools_region_init;
art->draw = view3d_tools_region_draw;
BLI_addhead(&st->regiontypes, art);
view3d_tool_props_register(art);
/* regions: header */
art = MEM_callocN(sizeof(ARegionType), "spacetype view3d header region");
art->regionid = RGN_TYPE_HEADER;
art->prefsizey = HEADERY;
art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D | ED_KEYMAP_FRAMES | ED_KEYMAP_HEADER;
art->listener = view3d_header_region_listener;
art->init = view3d_header_region_init;
art->draw = view3d_header_region_draw;
BLI_addhead(&st->regiontypes, art);
BKE_spacetype_register(st);
}
| 26.846004 | 121 | 0.683464 | [
"mesh",
"object",
"3d"
] |
99662b819aebbeef1a714a746f722e4af35f15b3 | 49,479 | c | C | Dmf/Framework/DmfUtility.c | rajeshbg/DriverModuleFramework | 2e8b8c78c5217b21a45192890f92c8fc581b0b0e | [
"MIT"
] | null | null | null | Dmf/Framework/DmfUtility.c | rajeshbg/DriverModuleFramework | 2e8b8c78c5217b21a45192890f92c8fc581b0b0e | [
"MIT"
] | null | null | null | Dmf/Framework/DmfUtility.c | rajeshbg/DriverModuleFramework | 2e8b8c78c5217b21a45192890f92c8fc581b0b0e | [
"MIT"
] | null | null | null | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT license.
Module Name:
DmfUtility.c
Abstract:
DMF Implementation.
This Module contains general utility functions that perform commonly needed tasks
by clients.
Environment:
Kernel-mode Driver Framework
User-mode Driver Framework
--*/
#include "DmfIncludeInternal.h"
#include "DmfUtility.tmh"
#include <initguid.h>
DEFINE_GUID(GUID_SURFACE_FIRMWARE_MODE_SETTINGS,
0x3811BE0C, 0x6AEF, 0x44DD, 0x93, 0x82, 0xCD, 0x99, 0xA2, 0x4C, 0x66, 0x19);
#pragma warning (disable : 4100 4131)
int __cdecl
_purecall (
VOID
)
/*++
Routine Description:
In case there is a problem with undefined virtual functions.
Arguments:
None
Return Value:
Zero.
--*/
{
FuncEntry(DMF_TRACE);
TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "Invalid Code Path");
ASSERT(FALSE);
FuncExitVoid(DMF_TRACE);
return 0;
}
_Must_inspect_result_
NTSTATUS
DMF_Utility_UserModeAccessCreate(
_In_ WDFDEVICE Device,
_In_opt_ const GUID* DeviceInterfaceGuid,
_In_opt_ WCHAR* SymbolicLinkName
)
/*++
Routine Description:
Create a device interface and/or symbolic link.
Arguments:
Device: Client Driver's WDFDEVICE
DeviceInterfaceGuid: The Device Interface GUID of the interface to expose.
SymbolicLinkName: Name of the symbolic link to create.
Return Value:
STATUS_SUCCESS on success, or Error Status Code on failure.
--*/
{
NTSTATUS ntStatus;
FuncEntry(DMF_TRACE);
TraceInformation(DMF_TRACE, "%!FUNC!");
ASSERT(Device != NULL);
ASSERT((DeviceInterfaceGuid != NULL) || (SymbolicLinkName != NULL));
if (DeviceInterfaceGuid != NULL)
{
// Create a device interface so that applications can find and talk send requests to this driver.
//
ntStatus = WdfDeviceCreateDeviceInterface(Device,
DeviceInterfaceGuid,
NULL);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "WdfDeviceCreateDeviceInterface fails: ntStatus=%!STATUS!", ntStatus);
goto Exit;
}
}
if (SymbolicLinkName != NULL)
{
UNICODE_STRING symbolicLinkName;
// This is for legacy code.
//
RtlInitUnicodeString(&symbolicLinkName,
SymbolicLinkName);
ntStatus = WdfDeviceCreateSymbolicLink(Device,
&symbolicLinkName);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "WdfDeviceCreateSymbolicLink fails: ntStatus=%!STATUS!", ntStatus);
goto Exit;
}
}
ntStatus = STATUS_SUCCESS;
Exit:
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
BOOLEAN
DMF_Utility_IsEqualGUID(
_In_ GUID* Guid1,
_In_ GUID* Guid2
)
/*++
Routine Description:
Determines whether the two GUIds are equal.
Arguments:
Guid1 - The first GUID.
Guid2 - The second GUID.
Return Value:
TRUE - If the GUIDs are equal.
FALSE - Otherwise.
--*/
{
BOOLEAN returnValue;
#if defined(__cplusplus)
if (IsEqualGUID(*Guid1,
*Guid2))
#else
if (IsEqualGUID(Guid1,
Guid2))
#endif // defined(__cplusplus)
{
returnValue = TRUE;
}
else
{
returnValue = FALSE;
}
return returnValue;
}
#if defined(DMF_USER_MODE)
VOID
DMF_Utility_DelayMilliseconds(
_In_ ULONG Milliseconds
)
/*++
Routine Description:
Cause the current User-mode thread to Sleep for a certain time.
Arguments:
Milliseconds: Time to sleep in milliseconds.
Return Value:
None
--*/
{
FuncEntryArguments(DMF_TRACE, "Milliseconds=%d", Milliseconds);
Sleep(Milliseconds);
FuncExitVoid(DMF_TRACE);
}
#else
VOID
DMF_Utility_DelayMilliseconds(
_In_ ULONG Milliseconds
)
/*++
Routine Description:
Cause the current Kernel-mode thread to Sleep for a certain time.
Arguments:
Milliseconds: Time to sleep in milliseconds.
Return Value:
None
--*/
{
LARGE_INTEGER intervalMs;
FuncEntryArguments(DMF_TRACE, "Milliseconds=%d", Milliseconds);
intervalMs.QuadPart = WDF_REL_TIMEOUT_IN_MS(Milliseconds);
KeDelayExecutionThread(KernelMode,
FALSE,
&intervalMs);
FuncExitVoid(DMF_TRACE);
}
#endif // defined(DMF_USER_MODE)
#if !defined(DMF_USER_MODE)
#pragma code_seg("PAGE")
_Must_inspect_result_
_IRQL_requires_same_
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DMF_Utility_AclPropagateInDeviceStack(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
Attempts to propagate our ACL's from the device to the FDO.
Arguments:
Device -- WDFDEVICE object.
Return Value:
NTSTATUS
--*/
{
NTSTATUS ntStatus;
PDEVICE_OBJECT wdmDeviceObject;
HANDLE fileHandle;
PAGED_CODE();
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
fileHandle = NULL;
// Get the FDO from our WDFDEVICE.
//
wdmDeviceObject = WdfDeviceWdmGetDeviceObject(Device);
// Given the pointer to the FDO, get a handle.
//
ntStatus = ObOpenObjectByPointer(wdmDeviceObject,
OBJ_KERNEL_HANDLE,
NULL,
WRITE_DAC,
0,
KernelMode,
&fileHandle);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "ObOpenObjectByPointer() fails: ntStatus=%!STATUS!", ntStatus);
goto Exit;
}
// Set the security that's already in the FDO onto the file handle thus setting
// the security Access Control Layer (ACL) up and down the device stack.
//
#pragma warning(suppress:28175)
ntStatus = ZwSetSecurityObject(fileHandle,
DACL_SECURITY_INFORMATION,
wdmDeviceObject->SecurityDescriptor);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "ZwSetSecurityObject() fails: ntStatus=%!STATUS!", ntStatus);
goto Exit;
}
Exit:
// Cleanup...
//
if (fileHandle != NULL)
{
ZwClose(fileHandle);
fileHandle = NULL;
}
FuncExit(DMF_TRACE, "ntStatus=%!STATUS!", ntStatus);
return ntStatus;
}
#pragma code_seg()
#endif // !defined(DMF_USER_MODE)
#pragma code_seg("PAGE")
VOID
DMF_Utility_EventLoggingNamesGet(
_In_ WDFDEVICE Device,
_Out_ PCWSTR* DeviceName,
_Out_ PCWSTR* Location
)
/*++
Routine Description:
Get the device name and location for a given WDFDEVICE.
Arguments:
Device -- The given WDFDEVICE.
Return Value:
None
--*/
{
NTSTATUS ntStatus;
WDF_OBJECT_ATTRIBUTES objectAttributes;
PAGED_CODE();
FuncEntry(DMF_TRACE);
WDFMEMORY deviceNameMemory = NULL;
WDFMEMORY locationMemory = NULL;
// We want both memory objects to be children of the device so they will
// be deleted automatically when the device is removed.
//
WDF_OBJECT_ATTRIBUTES_INIT(&objectAttributes);
objectAttributes.ParentObject = Device;
// First get the length of the string. If the FriendlyName is not there then get the
// length of device description.
//
ntStatus = WdfDeviceAllocAndQueryProperty(Device,
DevicePropertyFriendlyName,
NonPagedPoolNx,
&objectAttributes,
&deviceNameMemory);
if (!NT_SUCCESS(ntStatus))
{
ntStatus = WdfDeviceAllocAndQueryProperty(Device,
DevicePropertyDeviceDescription,
NonPagedPoolNx,
&objectAttributes,
&deviceNameMemory);
}
if (NT_SUCCESS(ntStatus))
{
*DeviceName = (PCWSTR)WdfMemoryGetBuffer(deviceNameMemory,
NULL);
}
else
{
*DeviceName = L"(error retrieving name)";
}
// Retrieve the device location string.
//
ntStatus = WdfDeviceAllocAndQueryProperty(Device,
DevicePropertyLocationInformation,
NonPagedPoolNx,
WDF_NO_OBJECT_ATTRIBUTES,
&locationMemory);
if (NT_SUCCESS(ntStatus))
{
*Location = (PCWSTR)WdfMemoryGetBuffer(locationMemory,
NULL);
}
else
{
*Location = L"(error retrieving location)";
}
FuncExitVoid(DMF_TRACE);
}
#pragma code_seg()
#if !defined(DMF_USER_MODE)
typedef
NTSTATUS
(*PFN_IO_GET_ACTIVITY_ID_IRP) (
_In_ PIRP Irp,
_Out_ LPGUID Guid
);
// Global function pointer set in DriverEntry.
//
PFN_IO_GET_ACTIVITY_ID_IRP g_DMF_IoGetActivityIdIrp;
GUID
DMF_Utility_ActivityIdFromRequest(
_In_ WDFREQUEST Request
)
/*++
Routine Description:
Given a WDFREQUEST, get its corresponding Activity Id. If it cannot be retrieved use the
handle of the given WDFREQUEST.
Arguments:
Request - The given WDFREQUEST.
Return Value:
GUID that represents the returned Activity Id.
--*/
{
GUID activityId = {0};
NTSTATUS ntstatus;
// Only try to get the function pointer if it has not been retrieved yet.
//
if (NULL == g_DMF_IoGetActivityIdIrp)
{
UNICODE_STRING functionName;
// IRP activity ID functions are available on some versions, save them into
// globals (or NULL if not available)
//
RtlInitUnicodeString(&functionName,
L"IoGetActivityIdIrp");
g_DMF_IoGetActivityIdIrp = (PFN_IO_GET_ACTIVITY_ID_IRP) (ULONG_PTR)MmGetSystemRoutineAddress(&functionName);
}
if (g_DMF_IoGetActivityIdIrp != NULL)
{
IRP* irp;
// Use activity ID generated by application (or IO manager)
//
irp = WdfRequestWdmGetIrp(Request);
ntstatus = g_DMF_IoGetActivityIdIrp(irp,
&activityId);
}
else
{
ntstatus = STATUS_UNSUCCESSFUL;
}
if (! NT_SUCCESS(ntstatus))
{
// Fall back to using the WDFREQUEST handle as the Activity Id.
//
RtlCopyMemory(&activityId,
&Request,
sizeof(WDFREQUEST));
}
return activityId;
}
#endif // !defined(DMF_USER_MODE)
GUID
DMF_Utility_ActivityIdFromDevice(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
Given a WDFDEVICE, get its corresponding Activity Id.
Arguments:
Request - The given WDFREQUEST.
Return Value:
GUID that represents the returned Activity Id.
--*/
{
GUID activity;
RtlCopyMemory(&activity,
&Device,
sizeof(WDFDEVICE));
return activity;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Event Log Definitions
//
// Definitions used by the Event Log functions.
//
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Identifiers for format specifiers supported in DMF Eventlogs.
//
typedef enum
{
FormatSize_INVALID,
FormatSize_CHAR,
FormatSize_SHORT,
FormatSize_INT,
FormatSize_POINTER
} DMF_EventLogFormatSizeType;
// The table of insertion strings.
//
typedef struct
{
// The insertion string data to write to event log = null terminated 16 bit wide character strings.
//
WCHAR ArrayOfInsertionStrings[DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS][DMF_EVENTLOG_MAXIMUM_INSERTION_STRING_LENGTH];
// The number of insertion strings.
//
ULONG NumberOfInsertionStrings;
} EVENTLOG_INSERTION_STRING_TABLE;
static
_IRQL_requires_max_(PASSIVE_LEVEL)
DMF_EventLogFormatSizeType
DMF_DMF_EventLogFormatSizeTypeGet(
_Inout_ PWCHAR FormatString
)
/*++
Routine Description:
This routine takes extracts the format specifier from a format string and returns a unique identifier based on it.
Arguments:
FormatString - The format string
Return Value:
DMF_EventLogFormatSizeType - A unique identifier based on the format specifier.
--*/
{
DMF_EventLogFormatSizeType returnValue;
ASSERT(FormatString != NULL);
returnValue = FormatSize_INVALID;
while ((*FormatString != L'\0') &&
(FormatSize_INVALID == returnValue))
{
if ((L'%' == *FormatString) &&
(*(FormatString + 1) != L'\0'))
{
WCHAR nextCharacter;
nextCharacter = *(FormatString + 1);
switch (nextCharacter)
{
case L'%':
{
break;
}
case L'c':
{
returnValue = FormatSize_CHAR;
break;
}
case L'd':
case L'u':
case L'x':
case L'X':
{
returnValue = FormatSize_INT;
break;
}
case L'p':
// Support for Wide strings.
//
case L's':
// Support for Ansi strings.
//
case L'S':
{
returnValue = FormatSize_POINTER;
break;
}
default:
{
ASSERT(FALSE);
goto Exit;
}
}
}
FormatString++;
}
Exit:
return returnValue;
}
static
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DMF_EventLogInsertionStringTableAllocate(
_Out_ EVENTLOG_INSERTION_STRING_TABLE** EventLogInsertionStringTable,
_Out_ WDFMEMORY* EventLogInsertionStringTableMemory,
_In_ INT NumberOfInsertionStrings,
_In_ va_list ArgumentList,
_In_ INT NumberOfFormatStrings,
_In_ PWCHAR* FormatStrings
)
/*++
Routine Description:
This routine allocates an event log insertion string table and assigns it with entries formed from
the Format strings and Argument list passed to it.
Arguments:
EventLogInsertionStringTable - Pointer to a location that receives a handle to EventLogInsertionStringTable.
EventLogInsertionStringTableMemory - Pointer to a location that receives a handle to memory associated with EventLogInsertionStringTable.
NumberOfInsertionStrings - Number of insertion strings.
ArgumentList - List of arguments (integers / characters / strings / pointers).
NumberOfFormatStrings - Number of format strings.
FormatStrings - Format strings with format specifiers for the arguments passed in ArgumentList.
Return Value:
NTSTATUS - the status of the allocate operation.
--*/
{
INT stringIndex;
NTSTATUS ntStatus;
WDF_OBJECT_ATTRIBUTES attributes;
EVENTLOG_INSERTION_STRING_TABLE* eventLogInsertionStringTable;
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
ASSERT(NumberOfFormatStrings == NumberOfInsertionStrings);
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
ntStatus = WdfMemoryCreate(&attributes,
NonPagedPoolNx,
DMF_TAG,
sizeof(EVENTLOG_INSERTION_STRING_TABLE),
EventLogInsertionStringTableMemory,
(VOID**)EventLogInsertionStringTable);
if (! NT_SUCCESS(ntStatus))
{
TraceEvents(TRACE_LEVEL_ERROR, DMF_TRACE, "Unable to allocate eventLogStringTable");
*EventLogInsertionStringTable = NULL;
*EventLogInsertionStringTableMemory = NULL;
goto Exit;
}
ASSERT(NULL != *EventLogInsertionStringTable);
ASSERT(NULL != *EventLogInsertionStringTableMemory);
eventLogInsertionStringTable = *EventLogInsertionStringTable;
RtlZeroMemory(eventLogInsertionStringTable,
sizeof(EVENTLOG_INSERTION_STRING_TABLE));
ASSERT(NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
for (stringIndex = 0; stringIndex < NumberOfFormatStrings; stringIndex++)
{
WCHAR* formatString;
DMF_EventLogFormatSizeType formatSize;
formatString = FormatStrings[stringIndex];
ASSERT(formatString != NULL);
ASSERT(wcslen(FormatStrings[stringIndex]) < DMF_EVENTLOG_MAXIMUM_INSERTION_STRING_LENGTH);
formatSize = DMF_DMF_EventLogFormatSizeTypeGet(formatString);
switch (formatSize)
{
case FormatSize_CHAR:
{
CHAR argument;
argument = va_arg(ArgumentList,
CHAR);
swprintf_s(eventLogInsertionStringTable->ArrayOfInsertionStrings[stringIndex],
DMF_EVENTLOG_MAXIMUM_INSERTION_STRING_LENGTH,
formatString,
argument);
break;
}
case FormatSize_INT:
{
INT argument;
argument = va_arg(ArgumentList,
INT);
swprintf_s(eventLogInsertionStringTable->ArrayOfInsertionStrings[stringIndex],
DMF_EVENTLOG_MAXIMUM_INSERTION_STRING_LENGTH,
formatString,
argument);
break;
}
case FormatSize_POINTER:
{
VOID* argument;
argument = va_arg(ArgumentList,
VOID*);
swprintf_s(eventLogInsertionStringTable->ArrayOfInsertionStrings[stringIndex],
DMF_EVENTLOG_MAXIMUM_INSERTION_STRING_LENGTH,
formatString,
argument);
break;
}
default:
{
ASSERT(FALSE);
ASSERT(0 == eventLogInsertionStringTable->NumberOfInsertionStrings);
goto Exit;
}
}
}
eventLogInsertionStringTable->NumberOfInsertionStrings = NumberOfInsertionStrings;
ASSERT(eventLogInsertionStringTable->NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
Exit:
FuncExit(DMF_TRACE, "eventLogStringTable=0x%p", *EventLogInsertionStringTable);
return ntStatus;
}
static
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_EventLogInsertionStringTableDeallocate(
_In_ WDFMEMORY EventLogInsertionStringTableMemory
)
/*++
Routine Description:
This routine deallocates memory allocated to the insertion string table.
Arguments:
EventLogInsertionStringTableMemory - Memory handle associated with the insertion string table.
Return Value:
None. If there is an error, no error is logged.
--*/
{
FuncEntry(DMF_TRACE);
WdfObjectDelete(EventLogInsertionStringTableMemory);
FuncExitNoReturn(DMF_TRACE);
}
static
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DMF_Utility_InsertionStringTableCreate(
_Out_ EVENTLOG_INSERTION_STRING_TABLE** EventLogInsertionStringTable,
_Out_ WDFMEMORY* EventLogInsertionStringTableMemory,
_In_ INT NumberOfInsertionStrings,
_In_ va_list ArgumentList,
_In_ INT NumberOfFormatStrings,
_In_opt_ PWCHAR* FormatStrings
)
/*++
Routine Description:
This routine creates the insertion string table.
Arguments:
EventLogInsertionStringTable - Pointer to a location that receives a handle to EventLogInsertionStringTable.
EventLogInsertionStringTableMemory - Pointer to a location that receives a handle to memory associated with EventLogInsertionStringTable.
NumberOfInsertionStrings - Number of insertion strings.
ArgumentList - List of arguments (integers / characters / strings / pointers).
NumberOfFormatStrings - Number of format strings.
FormatStrings - Format strings with format specifiers for the arguments passed in ArgumentList.
Return Value:
ntStatus - status of the create operation.
--*/
{
NTSTATUS ntStatus;
ntStatus = STATUS_SUCCESS;
ASSERT(NumberOfInsertionStrings == NumberOfFormatStrings);
ASSERT(NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
if (0 == NumberOfInsertionStrings)
{
ASSERT(NULL == FormatStrings);
*EventLogInsertionStringTable = NULL;
*EventLogInsertionStringTableMemory = NULL;
goto Exit;
}
ASSERT(FormatStrings != NULL);
// FormatStrings must not be NULL. But it is not because we have asserted above.
//
#pragma warning(suppress:6387)
ntStatus = DMF_EventLogInsertionStringTableAllocate(EventLogInsertionStringTable,
EventLogInsertionStringTableMemory,
NumberOfInsertionStrings,
ArgumentList,
NumberOfFormatStrings,
FormatStrings);
if (NT_SUCCESS(ntStatus))
{
ASSERT(NULL != *EventLogInsertionStringTable);
ASSERT(NULL != *EventLogInsertionStringTableMemory);
}
else
{
ASSERT(NULL == *EventLogInsertionStringTable);
ASSERT(NULL == *EventLogInsertionStringTableMemory);
}
Exit:
return ntStatus;
}
#if !defined(DMF_USER_MODE)
// Eventlog support for Kernel-mode Drivers.
//
static
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_Utility_EventLogEntryWriteToEventLogFile(
_In_ PDRIVER_OBJECT DriverObject,
_In_ NTSTATUS ErrorCode,
_In_ NTSTATUS FinalNtStatus,
_In_ ULONG UniqueId,
_In_ ULONG TextLength,
_In_opt_ PCWSTR Text,
_In_opt_ EVENTLOG_INSERTION_STRING_TABLE* EventLogInsertionStringTable
)
/*++
Routine Description:
This routine allocates an error log entry, copies the supplied data
to it, and requests that it be written to the event log file. This is the root
function that writes all logging entries.
Arguments:
DriverObject - WDM Driver object.
ErrorCode - ErrorCode from header generated by mc compiler.
FinalNtStatus - The final NTSTATUS for the error being logged.
UniqueId - A unique long word that identifies the particular
call to this function.
NumberOfInsertionStrings - Number of insertion strings.
TextLength - The length in bytes (including the terminating NULL)
of the Text string.
Text - Additional data to add to be included in the error log.
EventLogInsertionStringTable - A structure containing a table of insertion strings
and the number of insertion strings.
Return Value:
None. If there is an error, no error is logged.
--*/
{
PIO_ERROR_LOG_PACKET errorLogEntry;
SIZE_T totalLength;
SIZE_T textOffset;
SIZE_T insertionStringOffset;
ULONG stringIndex;
ULONG numberOfInsertionStrings;
FuncEntry(DMF_TRACE);
ASSERT(DriverObject != NULL);
textOffset = 0;
insertionStringOffset = 0;
numberOfInsertionStrings = 0;
totalLength = sizeof(IO_ERROR_LOG_PACKET);
// Determine if we need space for the text.
//
if (NULL != Text)
{
ASSERT(TextLength > 0);
// Calculate how big the error log packet needs to be to hold everything.
// Get offset for text data.
//
textOffset = totalLength;
// Add one for NULL terminating character.
//
totalLength += ((TextLength + 1) * sizeof(WCHAR));
}
else
{
ASSERT(TextLength == 0);
}
if (EventLogInsertionStringTable != NULL)
{
insertionStringOffset = totalLength;
numberOfInsertionStrings = EventLogInsertionStringTable->NumberOfInsertionStrings;
ASSERT(numberOfInsertionStrings > 0);
ASSERT(numberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
for (stringIndex = 0; stringIndex < numberOfInsertionStrings; stringIndex++)
{
// Add one for NULL terminating character.
//
totalLength += (wcslen(EventLogInsertionStringTable->ArrayOfInsertionStrings[stringIndex]) + 1) * (sizeof(WCHAR));
}
}
// Determine if the text will fit into the error log packet.
//
if (totalLength > ERROR_LOG_MAXIMUM_SIZE)
{
ASSERT(FALSE);
totalLength = sizeof(IO_ERROR_LOG_PACKET);
}
errorLogEntry = (PIO_ERROR_LOG_PACKET)IoAllocateErrorLogEntry(DriverObject,
(UCHAR)totalLength);
// If errorLogEntry in NULL, this is not considered an error situation. Just return.
//
if (errorLogEntry != NULL)
{
// Initialize the error log packet.
//
errorLogEntry->MajorFunctionCode = 0;
errorLogEntry->RetryCount = 0;
errorLogEntry->EventCategory = 0;
errorLogEntry->ErrorCode = ErrorCode;
errorLogEntry->UniqueErrorValue = UniqueId;
errorLogEntry->FinalStatus = FinalNtStatus;
errorLogEntry->SequenceNumber = 0;
errorLogEntry->IoControlCode = 0;
if ((totalLength > textOffset) && (NULL != Text))
{
// Able to include text
//
errorLogEntry->DumpDataSize = (USHORT)TextLength;
RtlCopyMemory(errorLogEntry->DumpData,
Text,
(totalLength - textOffset));
}
// Write the insertion strings.
//
if ((totalLength > insertionStringOffset) && (numberOfInsertionStrings > 0))
{
ASSERT(numberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
// Able to include insertion strings.
//
errorLogEntry->NumberOfStrings = (USHORT)numberOfInsertionStrings;
errorLogEntry->StringOffset = (USHORT)insertionStringOffset;
for (stringIndex = 0; stringIndex < numberOfInsertionStrings; stringIndex++)
{
size_t stringLength;
UCHAR* targetAddress;
WCHAR* sourceString;
// Add one for NULL terminator.
//
sourceString = EventLogInsertionStringTable->ArrayOfInsertionStrings[stringIndex];
stringLength = (wcslen(sourceString) + 1) * (sizeof(WCHAR));
targetAddress = (UCHAR*)errorLogEntry + insertionStringOffset;
RtlCopyMemory(targetAddress,
sourceString,
stringLength);
insertionStringOffset += stringLength;
}
}
else
{
// Couldn't include or caller didn't specify a text string.
//
errorLogEntry->NumberOfStrings = 0;
errorLogEntry->StringOffset = 0;
}
// Request that the error log packet be written to the error log file.
//
IoWriteErrorLogEntry(errorLogEntry);
}
FuncExitNoReturn(DMF_TRACE);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_Utility_EventLogEntryWriteDriverObject(
_In_ PDRIVER_OBJECT DriverObject,
_In_ NTSTATUS ErrorCode,
_In_ NTSTATUS FinalNtStatus,
_In_ ULONG UniqueId,
_In_ ULONG TextLength,
_In_opt_ PCWSTR Text,
_In_ INT NumberOfFormatStrings,
_In_opt_ PWCHAR* FormatStrings,
_In_ INT NumberOfInsertionStrings,
...
)
/*++
Routine Description:
This routine creates an insertion string table and requests the arguments and the table be written to event log file.
Arguments:
DriverObject - WDM Driver object.
ErrorCode - ErrorCode from header generated by mc compiler.
FinalNtStatus - The final NTSTATUS for the error being logged.
UniqueId - A unique long word that identifies the particular
call to this function.
TextLength - The length in bytes (including the terminating NULL)
of the Text string.
Text - Additional data to add to be included in the error log.
NumberOfFormatStrings - Number of format strings.
FormatStrings - An array of format specifiers for each argument passed below.
NumberOfInsertionStrings - Number of insertion strings.
... - Variable list of insertion strings.
Return Value:
None. If there is an error, no error is logged.
--*/
{
EVENTLOG_INSERTION_STRING_TABLE* eventLogStringTable;
va_list argumentList;
WDFMEMORY eventLogStringTableMemory;
NTSTATUS ntStatus;
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
eventLogStringTable = NULL;
eventLogStringTableMemory = NULL;
ASSERT(NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
va_start(argumentList,
NumberOfInsertionStrings);
ntStatus = DMF_Utility_InsertionStringTableCreate(&eventLogStringTable,
&eventLogStringTableMemory,
NumberOfInsertionStrings,
argumentList,
NumberOfFormatStrings,
FormatStrings);
va_end(argumentList);
DMF_Utility_EventLogEntryWriteToEventLogFile(DriverObject,
ErrorCode,
FinalNtStatus,
UniqueId,
TextLength,
Text,
eventLogStringTable);
if (eventLogStringTableMemory)
{
DMF_EventLogInsertionStringTableDeallocate(eventLogStringTableMemory);
eventLogStringTableMemory = NULL;
eventLogStringTable = NULL;
}
FuncExitNoReturn(DMF_TRACE);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_Utility_EventLogEntryWriteDriver(
_In_ WDFDRIVER Driver,
_In_ NTSTATUS ErrorCode,
_In_ NTSTATUS FinalNtStatus,
_In_ ULONG UniqueId,
_In_ ULONG TextLength,
_In_opt_ PCWSTR Text,
_In_ INT NumberOfFormatStrings,
_In_opt_ PWCHAR* FormatStrings,
_In_ INT NumberOfInsertionStrings,
...
)
/*++
Routine Description:
This routine creates an insertion string table and requests the arguments and the table be
written to event log file.
This function requires a WDFDRIVER object. It is designed to be called from Client Driver
when a WDFDEVICE object is not available.
Arguments:
Driver - WDF Driver.
ErrorCode - ErrorCode from header generated by mc compiler.
FinalNtStatus - The final NTSTATUS for the error being logged.
UniqueId - A unique long word that identifies the particular
call to this function.
TextLength - The length in bytes (including the terminating NULL)
of the Text string.
Text - Additional data to add to be included in the error log.
NumberOfFormatStrings - Number of format strings.
FormatStrings - An array of format specifiers for each argument passed below.
NumberOfInsertionStrings - Number of insertion strings.
... - Variable list of insertion strings.
Return Value:
None. If there is an error, no error is logged.
--*/
{
PDRIVER_OBJECT driverObject;
EVENTLOG_INSERTION_STRING_TABLE* eventLogStringTable;
va_list argumentList;
WDFMEMORY eventLogStringTableMemory;
NTSTATUS ntStatus;
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
eventLogStringTable = NULL;
eventLogStringTableMemory = NULL;
ASSERT(NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
va_start(argumentList,
NumberOfInsertionStrings);
ntStatus = DMF_Utility_InsertionStringTableCreate(&eventLogStringTable,
&eventLogStringTableMemory,
NumberOfInsertionStrings,
argumentList,
NumberOfFormatStrings,
FormatStrings);
va_end(argumentList);
// Get the associated WDM Driver Object.
//
driverObject = WdfDriverWdmGetDriverObject(Driver);
DMF_Utility_EventLogEntryWriteToEventLogFile(driverObject,
ErrorCode,
FinalNtStatus,
UniqueId,
TextLength,
Text,
eventLogStringTable);
if (eventLogStringTableMemory)
{
DMF_EventLogInsertionStringTableDeallocate(eventLogStringTableMemory);
eventLogStringTableMemory = NULL;
eventLogStringTable = NULL;
}
FuncExitNoReturn(DMF_TRACE);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_Utility_EventLogEntryWriteDevice(
_In_ WDFDEVICE Device,
_In_ NTSTATUS ErrorCode,
_In_ NTSTATUS Status,
_In_ ULONG UniqueId,
_In_ ULONG TextLength,
_In_opt_ PCWSTR Text,
_In_ INT NumberOfFormatStrings,
_In_opt_ PWCHAR* FormatStrings,
_In_ INT NumberOfInsertionStrings,
...
)
/*++
Routine Description:
This routine creates an insertion string table and requests
the arguments and the table be written to event log file.
This function requires a WDFDEVICE object.
Arguments:
Device - WDF Device.
ErrorCode - ErrorCode from header generated by mc compiler.
FinalNtStatus - The final NTSTATUS for the error being logged.
UniqueId - A unique long word that identifies the particular
call to this function.
TextLength - The length in bytes (including the terminating NULL)
of the Text string.
Text - Additional data to add to be included in the error log.
NumberOfFormatStrings - Number of format strings.
FormatStrings - An array of format specifiers for each argument passed below.
NumberOfInsertionStrings - Number of insertion strings.
... - Variable list of insertion strings.
Return Value:
None. If there is an error, no error is logged.
--*/
{
EVENTLOG_INSERTION_STRING_TABLE* eventLogStringTable;
va_list argumentList;
WDFDRIVER driver;
PDRIVER_OBJECT driverObject;
WDFMEMORY eventLogStringTableMemory;
NTSTATUS ntStatus;
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
eventLogStringTable = NULL;
eventLogStringTableMemory = NULL;
ASSERT(NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
ASSERT(Device != NULL);
va_start(argumentList,
NumberOfInsertionStrings);
ntStatus = DMF_Utility_InsertionStringTableCreate(&eventLogStringTable,
&eventLogStringTableMemory,
NumberOfInsertionStrings,
argumentList,
NumberOfFormatStrings,
FormatStrings);
va_end(argumentList);
// Get the associated Wdf Driver.
//
driver = WdfDeviceGetDriver(Device);
ASSERT(driver != NULL);
// Get the associated WDM Driver Object.
//
driverObject = WdfDriverWdmGetDriverObject(driver);
DMF_Utility_EventLogEntryWriteToEventLogFile(driverObject,
ErrorCode,
Status,
UniqueId,
TextLength,
Text,
eventLogStringTable);
if (eventLogStringTableMemory)
{
DMF_EventLogInsertionStringTableDeallocate(eventLogStringTableMemory);
eventLogStringTableMemory = NULL;
eventLogStringTable = NULL;
}
FuncExitNoReturn(DMF_TRACE);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_Utility_EventLogEntryWriteDmfModule(
_In_ DMFMODULE DmfModule,
_In_ NTSTATUS ErrorCode,
_In_ NTSTATUS FinalNtStatus,
_In_ ULONG UniqueId,
_In_ ULONG TextLength,
_In_opt_ PCWSTR Text,
_In_ INT NumberOfFormatStrings,
_In_opt_ PWCHAR* FormatStrings,
_In_ INT NumberOfInsertionStrings,
...
)
/*++
Routine Description:
This routine creates an insertion string table and requests
the arguments and the table be written to event log file.
This function requires a DMF_OBJECT* object.
Arguments:
DmfModule - This Module's handle.
ErrorCode - ErrorCode from header generated by mc compiler.
FinalNtStatus - The final NTSTATUS for the error being logged.
UniqueId - A unique long word that identifies the particular
call to this function.
TextLength - The length in bytes (including the terminating NULL)
of the Text string.
Text - Additional data to add to be included in the error log.
NumberOfFormatStrings - Number of format strings.
FormatStrings - An array of format specifiers for each argument passed below.
NumberOfInsertionStrings - Number of insertion strings.
... - Variable list of insertion strings.
Return Value:
None. If there is an error, no error is logged.
--*/
{
WDFDEVICE device;
WDFDRIVER driver;
PDRIVER_OBJECT driverObject;
EVENTLOG_INSERTION_STRING_TABLE* eventLogStringTable;
va_list argumentList;
WDFMEMORY eventLogStringTableMemory;
NTSTATUS ntStatus;
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
eventLogStringTable = NULL;
eventLogStringTableMemory = NULL;
ASSERT(NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
ASSERT(NumberOfInsertionStrings == NumberOfFormatStrings);
va_start(argumentList,
NumberOfInsertionStrings);
ntStatus = DMF_Utility_InsertionStringTableCreate(&eventLogStringTable,
&eventLogStringTableMemory,
NumberOfInsertionStrings,
argumentList,
NumberOfFormatStrings,
FormatStrings);
va_end(argumentList);
// Get the associated WDM Device.
//
device = DMF_ParentDeviceGet(DmfModule);
// Get the associated WDM Driver.
//
driver = WdfDeviceGetDriver(device);
ASSERT(driver != NULL);
// Get the associated WDM Driver Object.
//
driverObject = WdfDriverWdmGetDriverObject(driver);
DMF_Utility_EventLogEntryWriteToEventLogFile(driverObject,
ErrorCode,
FinalNtStatus,
UniqueId,
TextLength,
Text,
eventLogStringTable);
if (eventLogStringTableMemory)
{
DMF_EventLogInsertionStringTableDeallocate(eventLogStringTableMemory);
eventLogStringTableMemory = NULL;
eventLogStringTable = NULL;
}
FuncExitNoReturn(DMF_TRACE);
}
#else
// Eventlog support for User-mode Drivers.
//
// The table of insertion strings.
//
typedef struct
{
// The insertion string data to write to event log = null terminated 16 bit wide character strings.
//
LPWSTR* InsertionStrings;
// The number of insertion strings.
//
ULONG NumberOfInsertionStrings;
} DMF_INSERTION_STRING_LIST;
NTSTATUS
DMF_Utility_InsertionStringListCreate(
_In_ EVENTLOG_INSERTION_STRING_TABLE* EventLogInsertionStringTable,
_Out_ DMF_INSERTION_STRING_LIST** InsertionStringList
)
/*++
Routine Description:
This routine creates a closely packed insertion string list.
Arguments:
EventLogInsertionStringTable - the insertion string table containing the insertion strings that will be part of the list.
InsertionStringList - Pointer to a location that receives a handle to DMF_INSERTION_STRING_LIST.
Return Value:
NTSTATUS - status of the Create operation.
--*/
{
ULONG stringIndex;
ULONG numberOfInsertionStrings;
NTSTATUS ntStatus;
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
*InsertionStringList = NULL;
if (NULL == EventLogInsertionStringTable)
{
goto Exit;
}
numberOfInsertionStrings = EventLogInsertionStringTable->NumberOfInsertionStrings;
ASSERT(numberOfInsertionStrings > 0);
ASSERT(numberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
// Allocate memory for the DMF_INSERTION_STRING_LIST structure.
//
*InsertionStringList = (DMF_INSERTION_STRING_LIST*)malloc(sizeof(DMF_INSERTION_STRING_LIST));
if (NULL == *InsertionStringList)
{
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
(*InsertionStringList)->InsertionStrings = NULL;
(*InsertionStringList)->NumberOfInsertionStrings = 0;
// Allocate memory to store a pointer to each Insertion String.
//
(*InsertionStringList)->InsertionStrings = (LPWSTR*)malloc(sizeof(LPWSTR) * numberOfInsertionStrings);
if (NULL == (*InsertionStringList)->InsertionStrings)
{
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
free(*InsertionStringList);
*InsertionStringList = NULL;
goto Exit;
}
for (stringIndex = 0; stringIndex < numberOfInsertionStrings; stringIndex++)
{
// Allocate memory for each insertion string to NULL.
//
// 'warning C6386: Buffer overrun while writing to '((*InsertionStringList))->InsertionStrings': the writable size is 'sizeof(WCHAR *)*numberOfInsertionStrings' bytes, but '16' bytes might be written.'
//
#pragma warning(suppress:6386)
(*InsertionStringList)->InsertionStrings[stringIndex] = (LPWSTR)malloc(sizeof(WCHAR) * (wcslen(EventLogInsertionStringTable->ArrayOfInsertionStrings[stringIndex]) + 1));
}
// Copy the insertion strings from the table to the memory allocated.
//
for (stringIndex = 0; stringIndex < numberOfInsertionStrings; stringIndex++)
{
size_t stringLength;
WCHAR* sourceString;
// Add one for NULL terminator.
//
sourceString = EventLogInsertionStringTable->ArrayOfInsertionStrings[stringIndex];
stringLength = (wcslen(sourceString) + 1) * (sizeof(WCHAR));
// 'warning C6386: Buffer overrun while writing to '((*InsertionStringList))->InsertionStrings': the writable size is 'sizeof(WCHAR *)*numberOfInsertionStrings' bytes, but '16' bytes might be written.'
//
#pragma warning(suppress:6385)
RtlCopyMemory((*InsertionStringList)->InsertionStrings[stringIndex],
sourceString,
stringLength);
}
(*InsertionStringList)->NumberOfInsertionStrings = numberOfInsertionStrings;
Exit:
FuncExitNoReturn(DMF_TRACE);
return ntStatus;
}
void
DMF_Utility_InsertionStringListDestroy(
_In_ DMF_INSERTION_STRING_LIST* InsertionStringList
)
/*++
Routine Description:
This routine destroys the insertion string list.
Arguments:
InsertionStringList - Pointer to a handle to DMF_INSERTION_STRING_LIST.
Return Value:
NTSTATUS - status of the Destroy operation.
--*/
{
ULONG stringIndex;
ULONG numberOfInsertionStrings;
ASSERT(NULL != InsertionStringList);
ASSERT(NULL != (InsertionStringList)->InsertionStrings);
numberOfInsertionStrings = (InsertionStringList)->NumberOfInsertionStrings;
ASSERT(numberOfInsertionStrings > 0);
// Free memory associated with each string.
//
for (stringIndex = 0; stringIndex < numberOfInsertionStrings; stringIndex++)
{
free((InsertionStringList)->InsertionStrings[stringIndex]);
(InsertionStringList)->InsertionStrings[stringIndex] = NULL;
}
// Free memory associated with the pointer to strings.
//
free((InsertionStringList)->InsertionStrings);
(InsertionStringList)->InsertionStrings = NULL;
(InsertionStringList)->NumberOfInsertionStrings = 0;
// Free memory associated with the DMF_INSERTION_STRING_LIST structure.
//
free(InsertionStringList);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DMF_Utility_EventLogEntryWriteUserMode(
_In_ PWSTR Provider,
_In_ WORD EventType,
_In_ DWORD EventId,
_In_ INT NumberOfFormatStrings,
_In_opt_ PWCHAR* FormatStrings,
_In_ INT NumberOfInsertionStrings,
...
)
/*++
Routine Description:
This routine writes an event from a User-mode driver to the system event log file.
Arguments:
Provider - Provider of the event.
EventType - Type of the event: EVENTLOG_SUCCESS/EVENTLOG_ERROR_TYPE/EVENTLOG_INFORMATION_TYPE/EVENTLOG_WARNING_TYPE
EventId - EventId from header generated by mc compiler.
NumberOfFormatStrings - Number of format strings.
FormatStrings - An array of format specifiers for each argument passed below.
NumberOfInsertionStrings - Number of insertion strings.
... - Variable list of insertion strings.
Return Value:
None. If there is an error, no error is logged.
--*/
{
EVENTLOG_INSERTION_STRING_TABLE* eventLogStringTable;
DMF_INSERTION_STRING_LIST* insertionStringList;
va_list argumentList;
HANDLE eventSource;
WDFMEMORY eventLogStringTableMemory;
NTSTATUS ntStatus;
LPWSTR* insertionStrings;
FuncEntry(DMF_TRACE);
ntStatus = STATUS_SUCCESS;
eventSource = NULL;
eventLogStringTable = NULL;
eventLogStringTableMemory = NULL;
insertionStrings = NULL;
ASSERT(Provider != NULL);
ASSERT(NumberOfInsertionStrings <= DMF_EVENTLOG_MAXIMUM_NUMBER_OF_INSERTION_STRINGS);
ASSERT(NumberOfInsertionStrings == NumberOfFormatStrings);
// Create the insertion string table.
//
va_start(argumentList,
NumberOfInsertionStrings);
ntStatus = DMF_Utility_InsertionStringTableCreate(&eventLogStringTable,
&eventLogStringTableMemory,
NumberOfInsertionStrings,
argumentList,
NumberOfFormatStrings,
FormatStrings);
va_end(argumentList);
// Create the closely packed insertion string list.
//
ntStatus = DMF_Utility_InsertionStringListCreate(eventLogStringTable,
&insertionStringList);
if (! NT_SUCCESS(ntStatus))
{
ASSERT(NULL == insertionStringList);
NumberOfInsertionStrings = 0;
}
else if (NumberOfInsertionStrings > 0)
{
insertionStrings = insertionStringList->InsertionStrings;
}
// 'Banned Crimson API Usage: RegisterEventSourceW is a Banned Crimson API'.
//
#pragma warning(suppress: 28735)
eventSource = RegisterEventSource(NULL,
Provider);
if (NULL == eventSource)
{
goto Exit;
}
ReportEvent(eventSource,
EventType,
0,
EventId,
NULL,
(WORD)NumberOfInsertionStrings,
0,
(LPCWSTR*)insertionStrings,
NULL);
Exit:
if (eventSource)
{
DeregisterEventSource(eventSource);
}
// Destroy the closely packed insertion string list.
//
if (insertionStringList)
{
DMF_Utility_InsertionStringListDestroy(insertionStringList);
insertionStringList = NULL;
}
// Destroy the insertion string table.
//
if (eventLogStringTableMemory)
{
DMF_EventLogInsertionStringTableDeallocate(eventLogStringTableMemory);
eventLogStringTableMemory = NULL;
eventLogStringTable = NULL;
}
FuncExitNoReturn(DMF_TRACE);
}
#endif // !defined(DMF_USER_MODE)
// eof: DmfUtility.c
//
| 28.419874 | 210 | 0.623699 | [
"object"
] |
99671d5b1632ac94ed1007027f4aad92e88a2354 | 1,514 | h | C | ProfessionalC++/RoundRobin/RoundRobin.h | zzragida/CppExamples | d627b097efc04209aa4012f7b7f9d82858da3f2d | [
"Apache-2.0"
] | null | null | null | ProfessionalC++/RoundRobin/RoundRobin.h | zzragida/CppExamples | d627b097efc04209aa4012f7b7f9d82858da3f2d | [
"Apache-2.0"
] | null | null | null | ProfessionalC++/RoundRobin/RoundRobin.h | zzragida/CppExamples | d627b097efc04209aa4012f7b7f9d82858da3f2d | [
"Apache-2.0"
] | null | null | null | #include <stdexcept>
#include <vector>
template <typename T>
class RoundRobin
{
public:
RoundRobin(int numExpected = 0);
virtual ~RoundRobin();
void add(const T& elem);
void remove(const T& elem);
T& getNext() throw(std::out_of_range);
protected:
std::vector<T> mElems;
typename std::vector<T>::iterator mCurElem;
private:
RoundRobin(const RoundRobin& src);
RoundRobin& operator=(const RoundRobin& rhs);
};
template <typename T>
RoundRobin<T>::RoundRobin(int numExpected)
{
mElems.reserve(numExpected);
mCurElem = mElems.begin();
}
template <typename T>
RoundRobin<T>::~RoundRobin()
{
}
template <typename T>
void RoundRobin<T>::add(const T& elem)
{
int pos = mCurElem - mElems.begin();
mElems.push_back(elem);
mCurElem = mElems.begin() + pos;
}
template <typename T>
void RoundRobin<T>::remove(const T& elem)
{
for (auto it = mElems.begin(); it != mElems.end(); ++it)
{
if (*it == elem)
{
int newPos;
if (mCurElem <= it)
{
newPos = mCurElem - mElems.begin();
}
else
{
newPos = mCurElem - mElems.begin() - 1;
}
mElems.erase(it);
mCurElem = mElems.begin() + newPos;
if (mCurElem == mElems.end())
{
mCurElem = mElems.begin();
}
return;
}
}
}
template <typename T>
T& RoundRobin<T>::getNext() throw(std::out_of_range)
{
if (mElems.empty())
{
throw std::out_of_range("No elements in the list");
}
T& retVal = *mCurElem;
++mCurElem;
if (mCurElem == mElems.end())
{
mCurElem = mElems.begin();
}
return retVal;
}
| 16.106383 | 57 | 0.64465 | [
"vector"
] |
9972bd04e09fc236649b33447c7f3a0f7b66d92c | 29,454 | h | C | pcommon/pcomn_meta.h | ymarkovitch/libpcomn | e8d20cbb5ce6f181913e6c5ee15431b0f45758cf | [
"Zlib"
] | 6 | 2015-02-18T17:10:15.000Z | 2019-01-01T13:48:05.000Z | pcommon/pcomn_meta.h | ymarkovitch/libpcomn | e8d20cbb5ce6f181913e6c5ee15431b0f45758cf | [
"Zlib"
] | null | null | null | pcommon/pcomn_meta.h | ymarkovitch/libpcomn | e8d20cbb5ce6f181913e6c5ee15431b0f45758cf | [
"Zlib"
] | 3 | 2018-06-24T15:59:12.000Z | 2021-02-15T09:21:39.000Z | /*-*- mode:c++;tab-width:3;indent-tabs-mode:nil;c-file-style:"ellemtel";c-file-offsets:((innamespace . 0)(inclass . ++)) -*-*/
#ifndef __PCOMN_META_H
#define __PCOMN_META_H
/*******************************************************************************
FILE : pcomn_meta.h
COPYRIGHT : Yakov Markovitch, 2006-2020. All rights reserved.
See LICENSE for information on usage/redistribution.
DESCRIPTION : Basic template metaprogramming support.
PROGRAMMED BY: Yakov Markovitch
CREATION DATE: 14 Nov 2006
*******************************************************************************/
/** @file Basic template metaprogramming support
The template metaprogramming support in e.g. Boost is _indisputably_ much more
extensive, but PCommon library should not depend on Boost.
Besides, pcommon @em requires C++14 support to the extent of at least Visual Studio 2015
compiler in order to keep its own code as simple and clean as possible, in contrast to
Boost and other "industrial-grade" libraries that are much more portable at the cost of
cryptic workarounds and bloated portability layers.
*******************************************************************************/
#include <pcomn_platform.h>
#include <pcomn_macros.h>
#include <pcomn_assert.h>
#include <limits>
#include <utility>
#include <type_traits>
#ifndef PCOMN_STL_CXX17
#include <experimental/type_traits>
#endif /* PCOMN_STL_CXX17 */
// Avoid including the whole <string>
#if defined(__GLIBCXX__)
#include <bits/stringfwd.h>
#endif
#include <stdlib.h>
#include <stddef.h>
#ifndef PCOMN_STL_CXX17
namespace std {
template<class C>
inline constexpr auto size(const C &container) -> decltype(container.size()) { return container.size() ; }
template<typename T, size_t N>
inline constexpr size_t size(const T (&)[N]) noexcept { return N ; }
template<class C>
inline constexpr auto empty(const C &container) -> decltype(container.empty()) { return container.empty() ; }
template<typename T, size_t N>
inline constexpr bool empty(const T (&)[N]) noexcept { return false ; }
template<typename E>
inline constexpr bool empty(std::initializer_list<E> v) noexcept { return v.size() == 0 ; }
template<typename C, size_t n>
inline constexpr C *data(C (&arr)[n]) { return arr ; }
template<typename C, typename R, typename A>
inline constexpr C *data(std::basic_string<C, R, A> &s)
{
return const_cast<C *>(s.data()) ;
}
template<typename T>
inline constexpr auto data(T &&container) -> decltype(std::forward<T>(container).data())
{
return std::forward<T>(container).data() ;
}
template<bool v>
using bool_constant = std::integral_constant<bool, v> ;
template<typename...> using void_t = void ;
using std::experimental::is_void_v ;
using std::experimental::is_null_pointer_v ;
using std::experimental::is_integral_v ;
using std::experimental::is_floating_point_v ;
using std::experimental::is_array_v ;
using std::experimental::is_pointer_v ;
using std::experimental::is_lvalue_reference_v ;
using std::experimental::is_rvalue_reference_v ;
using std::experimental::is_member_object_pointer_v ;
using std::experimental::is_member_function_pointer_v ;
using std::experimental::is_enum_v ;
using std::experimental::is_union_v ;
using std::experimental::is_class_v ;
using std::experimental::is_function_v ;
using std::experimental::is_reference_v ;
using std::experimental::is_arithmetic_v ;
using std::experimental::is_fundamental_v ;
using std::experimental::is_object_v ;
using std::experimental::is_scalar_v ;
using std::experimental::is_compound_v ;
using std::experimental::is_member_pointer_v ;
using std::experimental::is_const_v ;
using std::experimental::is_volatile_v ;
using std::experimental::is_trivial_v ;
using std::experimental::is_trivially_copyable_v ;
using std::experimental::is_standard_layout_v ;
using std::experimental::is_pod_v ;
using std::experimental::is_empty_v ;
using std::experimental::is_polymorphic_v ;
using std::experimental::is_abstract_v ;
using std::experimental::is_final_v ;
using std::experimental::is_signed_v ;
using std::experimental::is_unsigned_v ;
using std::experimental::is_constructible_v ;
using std::experimental::is_trivially_constructible_v ;
using std::experimental::is_nothrow_constructible_v ;
using std::experimental::is_default_constructible_v ;
using std::experimental::is_trivially_default_constructible_v ;
using std::experimental::is_nothrow_default_constructible_v ;
using std::experimental::is_copy_constructible_v ;
using std::experimental::is_trivially_copy_constructible_v ;
using std::experimental::is_nothrow_copy_constructible_v ;
using std::experimental::is_move_constructible_v ;
using std::experimental::is_trivially_move_constructible_v ;
using std::experimental::is_nothrow_move_constructible_v ;
using std::experimental::is_assignable_v ;
using std::experimental::is_trivially_assignable_v ;
using std::experimental::is_nothrow_assignable_v ;
using std::experimental::is_copy_assignable_v ;
using std::experimental::is_trivially_copy_assignable_v ;
using std::experimental::is_nothrow_copy_assignable_v ;
using std::experimental::is_move_assignable_v ;
using std::experimental::is_trivially_move_assignable_v ;
using std::experimental::is_nothrow_move_assignable_v ;
using std::experimental::is_destructible_v ;
using std::experimental::is_trivially_destructible_v ;
using std::experimental::is_nothrow_destructible_v ;
using std::experimental::has_virtual_destructor_v ;
using std::experimental::alignment_of_v ;
using std::experimental::rank_v;
using std::experimental::extent_v ;
using std::experimental::is_same_v ;
using std::experimental::is_base_of_v ;
using std::experimental::is_convertible_v ;
} // end of namespace std
#endif /* PCOMN_STL_CXX17 */
#ifndef PCOMN_STL_CXX20
namespace std {
template<typename T>
using remove_cvref = std::remove_cv<std::remove_reference_t<T>> ;
template<typename T>
using remove_cvref_t = typename remove_cvref<T>::type ;
template<typename T> struct type_identity { typedef T type ; } ;
template<typename T>
using type_identity_t = typename type_identity<T>::type ;
} // end of namespace std
#endif /* PCOMN_STL_CXX20 */
namespace pcomn {
inline namespace traits {
using std::bool_constant ;
template<uint8_t v>
using byte_constant = std::integral_constant<uint8_t, v> ;
template<int v>
using int_constant = std::integral_constant<int, v> ;
template<unsigned v>
using uint_constant = std::integral_constant<unsigned, v> ;
template<long v>
using long_constant = std::integral_constant<long, v> ;
template<unsigned long v>
using ulong_constant = std::integral_constant<unsigned long, v> ;
template<long long v>
using longlong_constant = std::integral_constant<long long, v> ;
template<unsigned long long v>
using ulonglong_constant = std::integral_constant<unsigned long long, v> ;
template<size_t v>
using size_constant = std::integral_constant<size_t, v> ;
/***************************************************************************//**
@name TypeTraits
Type properties checks that are evaluated to std::bool_constant<>.
While many (most?) implementations of STL implement type traits classes by deriving
from std::integral_constant<bool, ...>, it is not mandated by the Standard.
So, if protable code needs to get bool_constant<> as a result of type trait check,
it has to use `typename is_xxx<T>::type`.
So we provide corresponding template typedefs to reduce such verbosity.
*******************************************************************************/
/**@{*/
template<typename T> using is_abstract_t = typename std::is_abstract<T>::type ;
template<typename T> using is_arithmetic_t = typename std::is_arithmetic<T>::type ;
template<typename T> using is_array_t = typename std::is_array<T>::type ;
template<typename T> using is_class_t = typename std::is_class<T>::type ;
template<typename T> using is_compound_t = typename std::is_compound<T>::type ;
template<typename T> using is_const_t = typename std::is_const<T>::type ;
template<typename T> using is_empty_t = typename std::is_empty<T>::type ;
template<typename T> using is_enum_t = typename std::is_enum<T>::type ;
template<typename T> using is_floating_point_t = typename std::is_floating_point<T>::type ;
template<typename T> using is_function_t = typename std::is_function<T>::type ;
template<typename T> using is_fundamental_t = typename std::is_fundamental<T>::type ;
template<typename T> using is_integral_t = typename std::is_integral<T>::type ;
template<typename T> using is_lvalue_reference_t = typename std::is_lvalue_reference<T>::type ;
template<typename T> using is_member_function_pointer_t = typename std::is_member_function_pointer<T>::type ;
template<typename T> using is_member_object_pointer_t = typename std::is_member_object_pointer<T>::type ;
template<typename T> using is_member_pointer_t = typename std::is_member_pointer<T>::type ;
template<typename T> using is_object_t = typename std::is_object<T>::type ;
template<typename T> using is_pod_t = typename std::is_pod<T>::type ;
template<typename T> using is_pointer_t = typename std::is_pointer<T>::type ;
template<typename T> using is_polymorphic_t = typename std::is_polymorphic<T>::type ;
template<typename T> using is_reference_t = typename std::is_reference<T>::type ;
template<typename T> using is_rvalue_reference_t = typename std::is_rvalue_reference<T>::type ;
template<typename T> using is_scalar_t = typename std::is_scalar<T>::type ;
template<typename T> using is_signed_t = typename std::is_signed<T>::type ;
template<typename T> using is_standard_layout_t = typename std::is_standard_layout<T>::type ;
template<typename T> using is_trivial_t = typename std::is_trivial<T>::type ;
template<typename T> using is_trivially_copyable_t = typename std::is_trivially_copyable<T>::type ;
template<typename T> using is_trivially_destructible_t = typename std::is_trivially_destructible<T>::type ;
template<typename T> using is_union_t = typename std::is_union<T>::type ;
template<typename T> using is_unsigned_t = typename std::is_unsigned<T>::type ;
template<typename T> using is_void_t = typename std::is_void<T>::type ;
template<typename T> using is_volatile_t = typename std::is_volatile<T>::type ;
/**@}*/
} // end of inline namespace pcomn::traits
template<typename To, typename From>
constexpr __forceinline To bit_cast(const From &from) noexcept
{
PCOMN_STATIC_CHECK(sizeof(To) == sizeof(From)) ;
PCOMN_STATIC_CHECK(alignof(To) <= alignof(From)) ;
PCOMN_STATIC_CHECK(std::is_trivially_copyable_v<From> && std::is_trivially_copyable_v<To>) ;
const union { const From *src ; const To *dst ; } result = {&from} ;
return *result.dst ;
}
/***************************************************************************//**
Function for getting T value in unevaluated context for e.g. passsing
to functions in SFINAE context without the need to go through constructors
Differs from std::declval in that it does not converts T to rvalue reference
*******************************************************************************/
template<typename T>
T autoval() ;
/***************************************************************************//**
disable_if is a complement to std::enable_if
*******************************************************************************/
template<bool disabled, typename T = void>
using disable_if = std::enable_if<!disabled, T> ;
template<bool disabled, typename T = void>
using disable_if_t = typename disable_if<disabled, T>::type ;
template<bool enabled>
using instance_if_t = std::enable_if_t<enabled, Instantiate> ;
/***************************************************************************//**
Utility metafunction that maps a sequence of any types to the type specified
as its first argument.
This metafunction is like void_t used in template metaprogramming to detect
ill-formed types in SFINAE context. It differs from std::void_t in that it maps
to some specified type intead of void, facilitating specification of function
argument and/or type types.
*******************************************************************************/
template<typename T, typename...> using type_t = T ;
/*******************************************************************************
Template compile-time logic operations.
*******************************************************************************/
template<class L, class R>
using ct_and = bool_constant<L::value && R::value> ;
template<class L, class R>
using ct_or = bool_constant<L::value || R::value> ;
template<class L, class R>
using ct_xor = bool_constant<!L::value != !R::value> ;
template<class L>
using ct_not = bool_constant<!L::value> ;
// While we can express ct_nand, ct_nor and ct_nxor in terms of already
// defined templates (using public inheritance), I prefer to define their
// 'value' member directly (to take some burden from the compiler)
template<class L, class R>
using ct_nand = bool_constant<!(L::value && R::value)> ;
template<class L, class R>
using ct_nor = bool_constant<!(L::value || R::value)> ;
template<class L, class R>
using ct_nxor = bool_constant<!L::value == !R::value> ;
/*******************************************************************************
Compile-time min/max.
*******************************************************************************/
template<typename T, T...> struct ct_min ;
template<typename T, T...> struct ct_max ;
template<typename T, T x> struct ct_min<T, x> :
std::integral_constant<T, x> {} ;
template<typename T, T x, T...y> struct ct_min<T, x, y...> :
std::integral_constant<T, (x < ct_min<T, y...>::value ? x : ct_min<T, y...>::value)> {} ;
template<typename T, T x> struct ct_max<T, x> :
std::integral_constant<T, x> {} ;
template<typename T, T x, T...y> struct ct_max<T, x, y...> :
std::integral_constant<T, (ct_max<T, y...>::value < x ? x : ct_max<T, y...>::value)> {} ;
/*******************************************************************************
Folding, until C++17 is the baseline standard
*******************************************************************************/
template<typename F, typename T>
constexpr inline T fold_left(F &&, T a1) { return a1 ; }
template<typename F, typename T, typename... TN>
constexpr inline T fold_left(F &&monoid, T a1, T a2, TN ...aN)
{
return fold_left<F, T>(std::forward<F>(monoid), std::forward<F>(monoid)(a1, a2), aN...) ;
}
template<typename T>
constexpr inline T fold_bitor(T a1) { return a1 ; }
template<typename T, typename... TN>
constexpr inline T fold_bitor(T a1, T a2, TN ...aN)
{
return fold_bitor<T>(a1 | a2, aN...) ;
}
/***************************************************************************//**
Creates unique type from another type.
This allows to completely separate otherwise compatible types (e.g. pointer to derived
and pointer to base, etc.)
*******************************************************************************/
template<typename T> using identity_type = std::type_identity<T> ;
/***************************************************************************//**
Transfer cv-qualifiers of the source type to the target type.
So, e.g.
- `transfer_cv_t<const int, double>` is `const double`
- `transfer_cv_t<const int, volatile double>` is `const volatile double`
- `transfer_cv_t<const volatile int, double>` is `const volatile double`
- `transfer_cv_t<const volatile int, volatile double>` is `const volatile double`
@Note `transfer_cv_t<const int, double*>` is `double* const`, _not_ 'const double*'
*******************************************************************************/
/**@{*/
template<typename S, typename T>
struct transfer_cv { typedef T type ; } ;
template<typename S, typename T>
struct transfer_cv<const S, T> : transfer_cv<S, const T> {} ;
template<typename S, typename T>
struct transfer_cv<volatile S, T> : transfer_cv<S, volatile T> {} ;
template<typename S, typename T>
struct transfer_cv<const volatile S, T> : transfer_cv<S, const volatile T> {} ;
/**@}*/
template<typename S, typename T>
using transfer_cv_t = typename transfer_cv<S,T>::type ;
/***************************************************************************//**
Provides globally placed default-constructed value of its parameter type.
*******************************************************************************/
template<typename T>
struct default_constructed {
typedef T type ;
static const type value ;
} ;
template<typename T>
const T default_constructed<T>::value = {} ;
/***************************************************************************//**
Callable object to construct an object of its template parameter type.
*******************************************************************************/
template<typename T>
struct make {
typedef T type ;
template<typename... Args>
type operator() (Args && ...args) const
{
return type(std::forward<Args>(args)...) ;
}
} ;
/*******************************************************************************
Type testers
*******************************************************************************/
template<typename Base, typename Derived>
struct is_base_of_strict :
bool_constant<!(std::is_same_v<Base, Derived> ||
std::is_same_v<const volatile Base*, const volatile void*>) &&
std::is_convertible_v<const volatile Derived*, const volatile Base*>> {} ;
template<typename T, typename U>
using is_same_unqualified = std::is_same<std::remove_cv_t<T>, std::remove_cv_t<U>> ;
template<typename To, typename... From>
struct is_all_convertible : std::true_type {} ;
template<typename To, typename F1, typename... Fn>
struct is_all_convertible<To, F1, Fn...> :
std::bool_constant<(std::is_convertible<F1, To>::value && is_all_convertible<To, Fn...>::value)>
{} ;
template<typename T, typename To, typename... From>
struct if_all_convertible : std::enable_if<is_all_convertible<To, From...>::value, T> {} ;
template<typename T, typename To, typename... From>
using if_all_convertible_t = typename if_all_convertible<T, To, From...>::type ;
template<typename T, typename... Types>
struct is_one_of : std::true_type {} ;
template<typename T, typename T1, typename... Tn>
struct is_one_of<T, T1, Tn...> :
std::bool_constant<(std::is_same_v<T, T1> || is_one_of<T, Tn...>::value)>
{} ;
template<typename T, typename... Types>
constexpr bool is_one_of_v = is_one_of<T, Types...>::value ;
template<typename To, typename... From>
constexpr bool is_all_convertible_v = is_all_convertible<To, From...>::value ;
/***************************************************************************//**
Check if the type can be trivially swapped, i.e. by simply swapping raw memory
contents.
*******************************************************************************/
template<typename T>
struct is_trivially_swappable :
std::is_trivially_copyable<T>
{} ;
template<typename T1, typename T2>
struct is_trivially_swappable<std::pair<T1, T2>> :
ct_and<is_trivially_swappable<T1>, is_trivially_swappable<T2>>
{} ;
/***************************************************************************//**
Type trait for types that allow memcpy()/memmove() construction and assignment.
This is the equivalent of `std::is_trivially_copyable` - and, by default,
is implemented as `std::is_trivially_copyable` - except that it can be overloaded
to return `true` for types that _are_, in fact, trivially copyable, but for which
`std::is_trivially_copyable` returns `false` due to collateral restrictions,
e.g. `std::pair<int,unsigned>`
*******************************************************************************/
template<typename T>
struct is_memmovable : std::bool_constant<std::is_trivially_copyable<T>::value> {} ;
template<typename T, typename U>
struct is_memmovable<std::pair<T, U>> : ct_and<is_memmovable<T>, is_memmovable<U> > {} ;
template<typename T>
constexpr bool is_trivially_swappable_v = is_trivially_swappable<T>::value ;
template<typename T>
constexpr bool is_memmovable_v = is_memmovable<T>::value ;
template<typename T>
struct is_literal_type : std::bool_constant<std::is_trivial<T>::value &&
!std::is_reference<T>::value &&
!std::is_void<T>::value> {} ;
template<typename T>
constexpr bool is_literal_type_v = is_literal_type<T>::value ;
template<typename T1, typename T2>
struct is_literal_type<std::pair<T1, T2>> :
ct_and<is_literal_type<T1>, is_literal_type<T2>>
{} ;
/*******************************************************************************
Parameter type
*******************************************************************************/
template<typename T>
using lvref_t = typename std::add_lvalue_reference<T>::type ;
template<typename T>
using clvref_t = lvref_t<typename std::add_const<T>::type> ;
template<typename T>
using parmtype_t = std::conditional_t<std::is_scalar<std::decay_t<T>>::value,
std::decay_t<T>, clvref_t<T>> ;
template<typename T>
inline std::conditional_t<std::is_scalar<std::decay_t<T>>::value,
std::decay_t<const T>,
std::reference_wrapper<const T>>
inparm(const T &v) { return v ; }
/******************************************************************************/
/** Deduce the return type of a function call expression at compile time @em and,
if the deduced type is a reference type, provides the member typedef type which
is the type referred to, otherwise deduced type itself.
*******************************************************************************/
template<typename> struct noref_result_of ;
template<typename F, typename... ArgTypes>
struct noref_result_of<F(ArgTypes...)> :
std::remove_reference<std::result_of_t<F(ArgTypes...)> > {} ;
template<typename T>
using noref_result_of_t = typename noref_result_of<T>::type ;
template<typename T>
using valtype_t = std::remove_cvref_t<T> ;
template<typename T, typename... A>
struct rebind___t {
template<template<typename...> class Template, typename A1, typename... Args>
static Template<T, A...> eval(Template<A1, Args...> *) ;
} ;
template<typename C, typename T, typename... A>
using rebind_t = decltype(rebind___t<T, A...>::eval(autoval<C *>())) ;
/***************************************************************************//**
Facilitates specifying the default parameters-types for a template with type `void`;
i.e., the possibility to use void as a tag "use the default type for this parameter".
There are lots of templates with several defaulted type parameters, e.g.:
@code
template<class Key, class T,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>>
class unordered_map ;
@endcode
If we need to specify a non-default value for one of the defaulted parameters, there is
a problem: if the parameter to be specified is not the first in the sequence of
parameters with defaults, all the previous parameters must be specified explicitly,
even if you want to keep using their default values.
*******************************************************************************/
/**@{*/
template<typename Specified, typename Default>
struct select_type {
typedef Specified type ;
} ;
template<typename Default>
struct select_type<void, Default> {
typedef Default type ;
} ;
template<typename Functor, typename Argtype, template<class> class Default>
struct select_functor {
typedef Functor type ;
} ;
template<typename Argtype, template<class> class Default>
struct select_functor<void, Argtype, Default> {
typedef Default<Argtype> type ;
} ;
template<typename Specified, typename Default>
using select_type_t = typename select_type<Specified, Default>::type ;
template<typename Functor, typename Argtype, template<class> class Default>
using select_functor_t = typename select_functor<Functor, Argtype, Default>::type ;
/**@}*/
/***************************************************************************//**
Macro to define member type metatesters
*******************************************************************************/
#define PCOMN_DEFINE_TYPE_MEMBER_TEST(type) \
template<typename T, typename=void> \
struct has_##type : std::false_type {} ; \
template<typename T> \
struct has_##type<T,std::void_t<typename T::type>> : std::true_type {}
/*******************************************************************************
Define member type metatests for std:: member typedefs
*******************************************************************************/
PCOMN_DEFINE_TYPE_MEMBER_TEST(key_type) ;
PCOMN_DEFINE_TYPE_MEMBER_TEST(mapped_type) ;
PCOMN_DEFINE_TYPE_MEMBER_TEST(value_type) ;
PCOMN_DEFINE_TYPE_MEMBER_TEST(element_type) ;
PCOMN_DEFINE_TYPE_MEMBER_TEST(iterator) ;
PCOMN_DEFINE_TYPE_MEMBER_TEST(const_iterator) ;
PCOMN_DEFINE_TYPE_MEMBER_TEST(pointer) ;
// Intentionally create an inconsistent name pcomn::has_type_type
// has_type is too generic a name, even for pcomn namespace.
namespace detail { PCOMN_DEFINE_TYPE_MEMBER_TEST(type) ; }
template<typename T>
struct has_type_type : detail::has_type<T> {} ;
/*******************************************************************************
Check whether the derived class overloads base class member or not
*******************************************************************************/
namespace detail {
template<typename C, typename R, typename... Args>
std::integral_constant<bool, true> is_derived_mem_fn_(R (C::*)(Args...) const) ;
template<typename C, typename R, typename... Args>
std::integral_constant<bool, true> is_derived_mem_fn_(R (C::*)(Args...)) ;
template<typename C>
std::integral_constant<bool, false> is_derived_mem_fn_(...) ;
template<typename C, typename T>
std::integral_constant<bool, true> is_derived_mem_(T C::*) ;
template<typename C>
std::integral_constant<bool, false> is_derived_mem_(...) ;
}
/******************************************************************************/
/** Metafunction: check if the member function of a derived class is derived from
the base class or overloaded in the derived class.
@return std::integral_constant<bool,true> if derived, std::integral_constant<bool,false>
if overloaded.
*******************************************************************************/
template<typename Base, typename Member>
constexpr decltype(detail::is_derived_mem_fn_<Base>(std::declval<Member>()))
is_derived_mem_fn(Member &&) { return {} ; }
/***************************************************************************//**
Metafunction: is the member of a derived class is derived from the base class
or overloaded in the derived class.
@return std::integral_constant<bool,true> if derived, std::integral_constant<bool,false>
if overloaded.
*******************************************************************************/
template<typename Base, typename Member>
constexpr decltype(detail::is_derived_mem_<Base>(std::declval<Member>()))
is_derived_mem(Member &&) { return {} ; }
/***************************************************************************//**
Uniform pair (i.e. pair<T,T>)
*******************************************************************************/
template<typename T>
using unipair = std::pair<T, T> ;
/***************************************************************************//**
Count types that satisfy a meta-predicate in the arguments pack
*******************************************************************************/
template<template<typename> class Predicate, typename... Types>
struct count_types_if ;
template<template<typename> class F>
struct count_types_if<F> : std::integral_constant<int, 0> {} ;
template<template<typename> class F, typename H, typename... T>
struct count_types_if<F, H, T...> :
std::integral_constant<int, ((int)!!F<H>::value + count_types_if<F, T...>::value)> {} ;
/****************************************************************************//**
Convert an enum value into the value of underlying integral type, or pass
through the paramter if it is already of interal type.
*******************************************************************************/
template<typename T, int mode = (int)std::is_enum<T>::value - (int)std::is_integral<T>::value>
struct underlying_integral ;
template<typename E>
struct underlying_integral<E, 1> : std::underlying_type<E> {} ;
template<typename I>
struct underlying_integral<I, -1> { typedef I type ; } ;
template<typename T>
using underlying_integral_t = typename underlying_integral<T>::type ;
template<typename E>
constexpr inline std::enable_if_t<std::is_enum<E>::value, underlying_integral_t<E>>
underlying_int(E value)
{
return static_cast<std::underlying_type_t<E>>(value) ;
}
template<typename I>
constexpr inline std::enable_if_t<std::is_integral<I>::value, I>
underlying_int(I value)
{
return value ;
}
} // end of namespace pcomn
#endif /* __PCOMN_META_H */
| 41.660537 | 126 | 0.628845 | [
"object"
] |
997a73d34e4ae2c395b22fde16ea4200a9ea4451 | 3,074 | h | C | oneflow/core/ndarray/ndarray_apply_broadcast_unary.h | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 2 | 2021-09-10T00:19:49.000Z | 2021-11-16T11:27:20.000Z | oneflow/core/ndarray/ndarray_apply_broadcast_unary.h | duijiudanggecl/oneflow | d2096ae14cf847509394a3b717021e2bd1d72f62 | [
"Apache-2.0"
] | 1 | 2021-06-16T08:37:50.000Z | 2021-06-16T08:37:50.000Z | oneflow/core/ndarray/ndarray_apply_broadcast_unary.h | duijiudanggecl/oneflow | d2096ae14cf847509394a3b717021e2bd1d72f62 | [
"Apache-2.0"
] | 1 | 2021-01-17T03:34:39.000Z | 2021-01-17T03:34:39.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ONEFLOW_CORE_NDARRAY_NDARRAY_APPLY_BROADCAST_UNARY_H_
#define ONEFLOW_CORE_NDARRAY_NDARRAY_APPLY_BROADCAST_UNARY_H_
#include "oneflow/core/ndarray/ndarray_apply_broadcast_unary_core.h"
#include "oneflow/core/common/util.h"
namespace oneflow {
template<DeviceType device_type, typename T, template<typename> class unary_func,
typename Enable = void>
struct NdarrayApplyBroadcastUnary;
template<DeviceType device_type, typename T, template<typename> class unary_func>
struct NdarrayApplyBroadcastUnary<
device_type, T, unary_func,
typename std::enable_if<std::is_same<T, typename DevDType<device_type, T>::type>::value>::type>
final {
static void Apply(DeviceCtx* ctx, const XpuVarNdarray<T>& y, const XpuVarNdarray<const T>& x) {
CheckBroadcastable(y, x);
DimVector simplified_y_dim;
DimVector simplified_x_dim;
SimplifyBroadcastShapes(y.shape(), x.shape(), &simplified_y_dim, &simplified_x_dim);
SwitchApply(SwitchCase(simplified_y_dim.size()), ctx,
XpuVarNdarray<T>(Shape(simplified_y_dim), y.ptr()),
XpuVarNdarray<const T>(Shape(simplified_x_dim), x.ptr()));
}
private:
#define DEFINE_NDARRAY_BROADCAST_UNARY(func_name, NDIMS) \
NdarrayApplyBroadcastUnaryCoreWrapper<device_type, T, NDIMS, unary_func>::func_name
DEFINE_STATIC_SWITCH_FUNC(void, Apply, DEFINE_NDARRAY_BROADCAST_UNARY,
MAKE_NDIM_CTRV_SEQ(DIM_SEQ));
#undef DEFINE_NDARRAY_BROADCAST_UNARY
static void CheckBroadcastable(const XpuVarNdarray<T>& y, const XpuVarNdarray<const T>& x) {
CHECK_EQ(y.shape().NumAxes(), x.shape().NumAxes());
for (int i = 0; i < y.shape().NumAxes(); ++i) {
CHECK(x.shape().At(i) == 1 || x.shape().At(i) == y.shape().At(i));
}
}
};
template<DeviceType device_type, typename T, template<typename> class unary_func>
struct NdarrayApplyBroadcastUnary<
device_type, T, unary_func,
typename std::enable_if<!std::is_same<T, typename DevDType<device_type, T>::type>::value>::type>
final {
static void Apply(DeviceCtx* ctx, const XpuVarNdarray<T>& y, const XpuVarNdarray<const T>& x) {
using NewT = typename DevDType<device_type, T>::type;
return NdarrayApplyBroadcastUnary<device_type, NewT, unary_func>::Apply(
ctx, reinterpret_cast<const XpuVarNdarray<NewT>&>(y),
reinterpret_cast<const XpuVarNdarray<const NewT>&>(x));
}
};
} // namespace oneflow
#endif // ONEFLOW_CORE_NDARRAY_NDARRAY_APPLY_BROADCAST_UNARY_H_
| 42.109589 | 100 | 0.745934 | [
"shape"
] |
48ca0887f6b3498203f997f11c3a5fd726ec42fd | 622 | h | C | src/Cube.h | HandsAndKeyboards/AppointmentProblem | dc0aedb88316546781a68876650c24e5d034522c | [
"MIT"
] | null | null | null | src/Cube.h | HandsAndKeyboards/AppointmentProblem | dc0aedb88316546781a68876650c24e5d034522c | [
"MIT"
] | null | null | null | src/Cube.h | HandsAndKeyboards/AppointmentProblem | dc0aedb88316546781a68876650c24e5d034522c | [
"MIT"
] | null | null | null | #ifndef CUBE_H
#define CUBE_H
#include <QVector>
#include "Line.h"
#include "IRenderable.h"
class Cube final : public IRenderable
{
// Вершины куба - точки трехмерного графа
QVector<QVector3D> vertices;
// Ребра куба
std::vector<std::unique_ptr<IRenderable>> edges;
public:
/* Конструктор класса
* Принимает параметр edgeLength - длину ребра куба
* Затем инициализирует вершины куба
*/
Cube(int edgeLength);
// Отрисовка объекта на сцене
void Render(Qt3DCore::QEntity *scene) override;
// Удаление объекта со сцены
void Remove() override;
};
#endif // CUBE_H
| 19.4375 | 55 | 0.684887 | [
"render",
"vector"
] |
48ca7b266322ef0dd0dad2e48f1a466e61bf4a3b | 3,928 | h | C | install/include/moar/6model/reprs/MVMCompUnit.h | tony-o/deb-rakudodaily | 7c7c0b29c133d90fbe98472030baa2efb98125ac | [
"Artistic-2.0"
] | null | null | null | install/include/moar/6model/reprs/MVMCompUnit.h | tony-o/deb-rakudodaily | 7c7c0b29c133d90fbe98472030baa2efb98125ac | [
"Artistic-2.0"
] | null | null | null | install/include/moar/6model/reprs/MVMCompUnit.h | tony-o/deb-rakudodaily | 7c7c0b29c133d90fbe98472030baa2efb98125ac | [
"Artistic-2.0"
] | null | null | null | struct MVMExtOpRecord {
/* Used to query the extop registry. */
MVMString *name;
/* Resolved by the validator. */
MVMOpInfo *info;
/* The actual function executed by the interpreter.
* Resolved by the validator. */
MVMExtOpFunc *func;
/* Tells the interpreter by how much to increment
* the instruction pointer. */
MVMuint16 operand_bytes;
/* Indicates the JIT should not emit a call to this op, because it needs
* to be used in an interpreter context. */
MVMuint16 no_jit;
/* Indicates the extop allocates and that its output is some allocated
* object. Used by allocation profiling. */
MVMuint16 allocating;
/* Read from the bytecode stream. */
MVMuint8 operand_descriptor[MVM_MAX_OPERANDS];
/* Specialization function. */
MVMExtOpSpesh *spesh;
/* Discover facts for spesh. */
MVMExtOpFactDiscover *discover;
};
/* How to release memory. */
typedef enum {
MVM_DEALLOCATE_NOOP,
MVM_DEALLOCATE_FREE,
MVM_DEALLOCATE_UNMAP
} MVMDeallocate;
/* Representation for a compilation unit in the VM. */
struct MVMCompUnitBody {
/* The start and size of the raw data for this compilation unit. */
MVMuint8 *data_start;
MVMuint32 data_size;
/* The various static frames in the compilation unit, along with a
* code object for each one. */
MVMStaticFrame **frames;
MVMObject **coderefs;
MVMuint32 num_frames; /* Total, inc. added by inliner. */
MVMuint32 orig_frames; /* Original from loading comp unit. */
/* Special frames. */
MVMStaticFrame *main_frame;
MVMStaticFrame *load_frame;
MVMStaticFrame *deserialize_frame;
/* The callsites in the compilation unit. */
MVMCallsite **callsites;
MVMuint32 num_callsites;
MVMuint32 orig_callsites;
MVMuint16 max_callsite_size;
/* The extension ops used by the compilation unit. */
MVMuint16 num_extops;
MVMExtOpRecord *extops;
/* The string heap and number of strings. */
MVMString **strings;
MVMuint32 num_strings;
MVMuint32 orig_strings;
/* Serialized data, if any. */
MVMint32 serialized_size;
MVMuint8 *serialized;
/* Array of the resolved serialization contexts, and how many we
* have. A null in the list indicates not yet resolved */
MVMSerializationContext **scs;
MVMuint32 num_scs;
/* How we should deallocate data_start. */
MVMDeallocate deallocate;
/* List of serialization contexts in need of resolution. This is an
* array of string handles; its length is determined by num_scs above.
* once an SC has been resolved, the entry on this list is NULLed. If
* all are resolved, this pointer itself becomes NULL. */
MVMSerializationContextBody **scs_to_resolve;
/* List of SC handle string indexes. */
MVMint32 *sc_handle_idxs;
/* HLL configuration for this compilation unit. */
MVMHLLConfig *hll_config;
MVMString *hll_name;
/* Filename, if any, that we loaded it from. */
MVMString *filename;
/* Handle, if any, associated with a mapped file. */
void *handle;
/* MVMReentrantLock to be taken if we want to add extra string,
* callsite, or coderef constants to the pools (done during
* inlining) or when we finish deserializing a frame, thus
* vivifying its lexicals. */
MVMObject *update_mutex;
/* Version of the bytecode format we deserialized this comp unit from. */
MVMuint16 bytecode_version;
};
struct MVMCompUnit {
MVMObject common;
MVMCompUnitBody body;
};
struct MVMLoadedCompUnitName {
/* Loaded filename. */
MVMString *filename;
/* Inline handle to the loaded filenames hash (in MVMInstance). */
UT_hash_handle hash_handle;
};
/* Function for REPR setup. */
const MVMREPROps * MVMCompUnit_initialize(MVMThreadContext *tc);
| 30.449612 | 77 | 0.680499 | [
"object"
] |
48d48a31d948f3d92f2eeb3cea4f12f9aa38f946 | 2,352 | h | C | quic/core/quic_datagram_queue.h | linjunmian/quiche | 4b63155d124a94c1505233de72b4123bb5858b6c | [
"BSD-3-Clause"
] | null | null | null | quic/core/quic_datagram_queue.h | linjunmian/quiche | 4b63155d124a94c1505233de72b4123bb5858b6c | [
"BSD-3-Clause"
] | null | null | null | quic/core/quic_datagram_queue.h | linjunmian/quiche | 4b63155d124a94c1505233de72b4123bb5858b6c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 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 QUICHE_QUIC_CORE_QUIC_DATAGRAM_QUEUE_H_
#define QUICHE_QUIC_CORE_QUIC_DATAGRAM_QUEUE_H_
#include "quic/core/quic_circular_deque.h"
#include "quic/core/quic_time.h"
#include "quic/core/quic_types.h"
#include "quic/platform/api/quic_mem_slice.h"
#include "common/platform/api/quiche_optional.h"
namespace quic {
class QuicSession;
// Provides a way to buffer QUIC datagrams (messages) in case they cannot
// be sent due to congestion control. Datagrams are buffered for a limited
// amount of time, and deleted after that time passes.
class QUIC_EXPORT_PRIVATE QuicDatagramQueue {
public:
// |session| is not owned and must outlive this object.
explicit QuicDatagramQueue(QuicSession* session);
// Adds the datagram to the end of the queue. May send it immediately; if
// not, MESSAGE_STATUS_BLOCKED is returned.
MessageStatus SendOrQueueDatagram(QuicMemSlice datagram);
// Attempts to send a single datagram from the queue. Returns the result of
// SendMessage(), or nullopt if there were no unexpired datagrams to send.
quiche::QuicheOptional<MessageStatus> TrySendingNextDatagram();
// Sends all of the unexpired datagrams until either the connection becomes
// write-blocked or the queue is empty. Returns the number of datagrams sent.
size_t SendDatagrams();
// Returns the amount of time a datagram is allowed to be in the queue before
// it is dropped. If not set explicitly using SetMaxTimeInQueue(), an
// RTT-based heuristic is used.
QuicTime::Delta GetMaxTimeInQueue() const;
void SetMaxTimeInQueue(QuicTime::Delta max_time_in_queue) {
max_time_in_queue_ = max_time_in_queue;
}
size_t queue_size() { return queue_.size(); }
bool empty() { return queue_.empty(); }
private:
struct QUIC_EXPORT_PRIVATE Datagram {
QuicMemSlice datagram;
QuicTime expiry;
};
// Removes expired datagrams from the front of the queue.
void RemoveExpiredDatagrams();
QuicSession* session_; // Not owned.
const QuicClock* clock_;
QuicTime::Delta max_time_in_queue_ = QuicTime::Delta::Zero();
QuicCircularDeque<Datagram> queue_;
};
} // namespace quic
#endif // QUICHE_QUIC_CORE_QUIC_DATAGRAM_QUEUE_H_
| 33.6 | 80 | 0.761905 | [
"object"
] |
48f88fbea31c762710705ec843e1c2c7c7420249 | 2,685 | h | C | Extern/JUCE/extras/the jucer/src/ui/jucer_ResourceEditorPanel.h | vinniefalco/SimpleDJ | 30cf1929eaaf0906a1056a33378e8b330062c691 | [
"MIT"
] | 27 | 2015-05-07T02:10:39.000Z | 2021-06-22T14:52:50.000Z | Extern/JUCE/extras/the jucer/src/ui/jucer_ResourceEditorPanel.h | JoseDiazRohena/SimpleDJ | 30cf1929eaaf0906a1056a33378e8b330062c691 | [
"MIT"
] | null | null | null | Extern/JUCE/extras/the jucer/src/ui/jucer_ResourceEditorPanel.h | JoseDiazRohena/SimpleDJ | 30cf1929eaaf0906a1056a33378e8b330062c691 | [
"MIT"
] | 14 | 2015-09-12T12:00:22.000Z | 2022-03-08T22:24:24.000Z | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#ifndef __JUCER_RESOURCEEDITORPANEL_JUCEHEADER__
#define __JUCER_RESOURCEEDITORPANEL_JUCEHEADER__
#include "../model/jucer_JucerDocument.h"
//==============================================================================
/**
*/
class ResourceEditorPanel : public Component,
private TableListBoxModel,
private ChangeListener,
private ButtonListener
{
public:
//==============================================================================
ResourceEditorPanel (JucerDocument& document);
~ResourceEditorPanel();
void resized();
void visibilityChanged();
void changeListenerCallback (ChangeBroadcaster*);
void buttonClicked (Button*);
int getNumRows();
void paintRowBackground (Graphics& g, int rowNumber, int width, int height, bool rowIsSelected);
void paintCell (Graphics& g, int rowNumber, int columnId, int width, int height, bool rowIsSelected);
Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected, Component* existingComponentToUpdate);
int getColumnAutoSizeWidth (int columnId);
void sortOrderChanged (int newSortColumnId, bool isForwards);
void selectedRowsChanged (int lastRowSelected);
private:
JucerDocument& document;
TableListBox* listBox;
TextButton* addButton;
TextButton* reloadAllButton;
TextButton* delButton;
};
#endif // __JUCER_RESOURCEEDITORPANEL_JUCEHEADER__
| 37.816901 | 128 | 0.58175 | [
"model"
] |
48fa0be799b182b5e134f1ddbba2ccb652925f39 | 24,920 | h | C | src/ios/IDTech.framework/Versions/A/Headers/IDT_UniPay.h | fasteroko/cordova-plugin-unimagII-swiper | 7f5e3fdd2c369306d016b826a1ab1eb3283868bc | [
"Apache-2.0"
] | null | null | null | src/ios/IDTech.framework/Versions/A/Headers/IDT_UniPay.h | fasteroko/cordova-plugin-unimagII-swiper | 7f5e3fdd2c369306d016b826a1ab1eb3283868bc | [
"Apache-2.0"
] | null | null | null | src/ios/IDTech.framework/Versions/A/Headers/IDT_UniPay.h | fasteroko/cordova-plugin-unimagII-swiper | 7f5e3fdd2c369306d016b826a1ab1eb3283868bc | [
"Apache-2.0"
] | null | null | null | //
// IDT_UniPay.h
// IDTech
//
// Created by Randy Palermo on 7/2/14.
// Copyright (c) 2014 IDTech Products. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "IDTCommon.h"
#import "IDTMSRData.h"
#import "APDUResponse.h"
#import "IDT_Device.h"
/** Protocol methods established for IDT_UniPay class **/
@protocol IDT_UniPay_Delegate <NSObject>
@optional
-(void) deviceConnected; //!<Fires when device connects. If a connection is established before the delegate is established (no delegate to send initial connection notification to), this method will fire upon establishing the delegate.
-(void) deviceDisconnected; //!<Fires when device disconnects.
- (void) plugStatusChange:(BOOL)deviceInserted; //!<Monitors the headphone jack for device insertion/removal.
//!< @param deviceInserted TRUE = device inserted, FALSE = device removed
- (void) dataInOutMonitor:(NSData*)data incoming:(BOOL)isIncoming; //!<All incoming/outgoing data going to the device can be monitored through this delegate.
//!< @param data The serial data represented as a NSData object
//!< @param isIncoming The direction of the data
//!<- <c>TRUE</c> specifies data being received from the device,
//!<- <c>FALSE</c> indicates data being sent to the device.
- (void) swipeMSRData:(IDTMSRData*)cardData;//!<Receives card data from MSR swipe.
//!< @param cardData Captured card data from MSR swipe
- (void) deviceMessage:(NSString*)message;//!<Receives messages from the framework
//!< @param message String message transmitted by framework
/**
UniPay ICC Event
This function will be called when an ICC is attached or detached from reader. Applies to UniPay only
@param nICC_Attached Can be one of the following values:
- 0x01: ICC attached while reader is idle
- 0x00: ICC detached while reader is idle
- 0x11: ICC attached while reader is in MSR mode
- 0x10: After ICC Powered On, ICC Card Removal,Power off ICC
@code
-(void) eventFunctionICC: (Byte) nICC_Attached
{
switch (nICC_Attached) {
case 0x01:
case 0x11:
{
LOGI(@"ICC event: ICC attached.");
}
break;
case 0x00:
case 0x10:
{
LOGI(@"ICC event: ICC detached.");
}
break;
}
}
@endcode
*/
-(void) eventFunctionICC: (Byte) nICC_Attached;
@end
/**
Class to drive the IDT_UniPay device
*/
@interface IDT_UniPay : NSObject<IDT_Device_Delegate>{
id<IDT_UniPay_Delegate> delegate;
}
@property(strong) id<IDT_UniPay_Delegate> delegate; //!<- Reference to IDT_UniPay_Delegate.
/**
* SDK Version
- All Devices
*
Returns the current version of IDTech.framework
@retval Framework version
*/
+(NSString*) SDK_version;
/**
* Singleton Instance
- All Devices
*
Establishes an singleton instance of IDT_UniPay class.
@retval Instance of IDT_UniPay
*/
+(IDT_UniPay*) sharedController;
/**
* Polls device for Model Number
*
* @param response Returns Model Number
*
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*
*/
-(RETURN_CODE) config_getModelNumber:(NSString**)response;
/**
* Polls device for Serial Number
*
* @param response Returns Serial Number
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*
*/
-(RETURN_CODE) config_getSerialNumber:(NSString**)response;
/**
* Command Acknowledgement Timout
*
* Sets the amount of seconds to wait for an {ACK} to a command before a timeout. Responses should normally be received under one second. Default is 3 seconds
*
* @param nSecond Timout value. Valid range 1 - 60 seconds
* @retval Success flag. Determines if value was set and in range.
*/
-(BOOL) config_setCmdTimeOutDuration: (int) nSecond;
/**
* Set Serial Number
*
Set device's serial number and Bluetooth name, then reboots device. Bluetooth name will be set as IDT_UniPay + Space + Serial number
*
@param strSN Device serial number
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) config_setSerialNumber:(NSString*)strSN;
/**
* Cancel Connect To Audio Reader
* @retval RETURN_CODE
*
Cancels a connection attempt to an IDTech MSR device connected via the audio port.
*/
-(RETURN_CODE) device_cancelConnectToAudioReader;
/**
* Connect To Audio Reader
* @retval RETURN_CODE
*
Attemps to recognize and connect to an IDTech MSR device connected via the audio port.
*/
-(RETURN_CODE) device_connectToAudioReader;
/**
* Polls device for Battery Voltage
*
* @param response Returns Battery Voltage as 4-chararacter string * 100. Example: "0186" = 1.86v. "1172" = 11.72v.
* @retval RETURN_CODE:
- 0x0000: Success: no error - RETURN_CODE_DO_SUCCESS
- 0x0001: Disconnect: no response from reader - RETURN_CODE_ERR_DISCONNECT
- 0x0002: Invalid Response: invalid response data - RETURN_CODE_ERR_CMD_RESPONSE
- 0x0003: Timeout: time out for task or CMD - RETURN_CODE_ERR_TIMEDOUT
- 0x0004: Invalid Parameter: wrong parameter - RETURN_CODE_ERR_INVALID_PARAMETER
- 0x0005: MSR Busy: SDK is doing MSR or ICC task - RETURN_CODE_SDK_BUSY_MSR
- 0x0006: PINPad Busy: SDK is doing PINPad task - RETURN_CODE_SDK_BUSY_PINPAD
- 0x0007: Unknown: Unknown error - RETURN_CODE_ERR_OTHER
- 0x0100 through 0xFFFF refer to IDT_Device::getResponseCodeString:()
*
*/
-(RETURN_CODE) device_getBatteryVoltage:(NSString**)response;
/**
* Polls device for Firmware Version
*
* @param response Response returned of Firmware Version
*
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*
*/
-(RETURN_CODE) device_getFirmwareVersion:(NSString**)response;
/**
* Get Level and Baude
*
@param response The Baud Rate and Audio Level.
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
- 0x0100 through 0xFFFF refer to IDT_Device::getResponseCodeString:()
*/
-(RETURN_CODE) device_getLevelAndBaud:(NSString**)response;
/**
* Get Response Code String
*
Interpret a IDT_UniPay response code and return string description.
@param errorCode Error code, range 0x0000 - 0xFFFF, example 0x0300
* @retval Verbose error description
HEX VALUE | Description
------- | -------
0x0000 | No error, beginning task
0x0001 | No response from reader
0x0002 | Invalid response data
0x0003 | Time out for task or CMD
0x0004 | Wrong parameter
0x0005 | SDK is doing MSR or ICC task
0x0006 | SDK is doing PINPad task
0x0007 | SDK is doing Other task
0x0300 | Key Type(TDES) of Session Key is not same as the related Master Key.
0x0400 | Related Key was not loaded.
0x0500 | Key Same.
0x0702 | PAN is Error Key.
0x0D00 | This Key had been loaded.
0x0E00 | Base Time was loaded.
0x1800 | Send “Cancel Command” after send “Get Encrypted PIN” &”Get Numeric “& “Get Amount”
0x1900 | Press “Cancel” key after send “Get Encrypted PIN” &”Get Numeric “& “Get Amount”
0x30FF | Security Chip is not connect
0x3000 | Security Chip is deactivation & Device is In Removal Legally State.
0x3101 | Security Chip is activation & Device is In Removal Legally State.
0x5500 | No Admin DUKPT Key.
0x5501 | Admin DUKPT Key STOP.
0x5502 | Admin DUKPT Key KSN is Error.
0x5503 | Get Authentication Code1 Failed.
0x5504 | Validate Authentication Code Error.
0x5505 | Encrypt or Decrypt data failed.
0x5506 | Not Support the New Key Type.
0x5507 | New Key Index is Error.
0x5508 | Step Error.
0x550F | Other Error.
0x6000 | Save or Config Failed / Or Read Config Error.
0x6200 | No Serial Number.
0x6900 | Invalid Command - Protocol is right, but task ID is invalid.
0x6A00 | Unsupported Command - Protocol and task ID are right, but command is invalid.
0x6B00 | Unknown parameter in command - Protocol task ID and command are right, but parameter is invalid.
0x7200 | Device is suspend (MKSK suspend or press password suspend).
0x7300 | PIN DUKPT is STOP (21 bit 1).
0x7400 | Device is Busy.
0xE100 | Can not enter sleep mode.
0xE200 | File has existed.
0xE300 | File has not existed.
0xE400 | Open File Error.
0xE500 | SmartCard Error.
0xE600 | Get MSR Card data is error.
0xE700 | Command time out.
0xE800 | File read or write is error.
0xE900 | Active 1850 error!
0xEA00 | Load bootloader error.
0xEF00 | Protocol Error- STX or ETX or check error.
0xEB00 | Picture is not exist.
0x2C06 | no card seated to request ATR
0x2D01 | Card Not Supported,
0x2D03 | Card Not Supported, wants CRC
0x690D | Command not supported on reader without ICC support
0x8100 | ICC error time out on power-up
0x8200 | invalid TS character received
0x8500 | pps confirmation error
0x8600 | Unsupported F, D, or combination of F and D
0x8700 | protocol not supported EMV TD1 out of range
0x8800 | power not at proper level
0x8900 | ATR length too long
0x8B01 | EMV invalid TA1 byte value
0x8B02 | EMV TB1 required
0x8B03 | EMV Unsupported TB1 only 00 allowed
0x8B04 | EMV Card Error, invalid BWI or CWI
0x8B06 | EMV TB2 not allowed in ATR
0x8B07 | EMV TC2 out of range
0x8B08 | EMV TC2 out of range
0x8B09 | per EMV96 TA3 must be > 0xF
0x8B10 | ICC error on power-up
0x8B11 | EMV T=1 then TB3 required
0x8B12 | Card Error, invalid BWI or CWI
0x8B13 | Card Error, invalid BWI or CWI
0x8B17 | EMV TC1/TB3 conflict*
0x8B20 | EMV TD2 out of range must be T=1
0x8C00 | TCK error
0xA304 | connector has no voltage setting
0xA305 | ICC error on power-up invalid (SBLK(IFSD) exchange
0xE301 | ICC error after session star
0xFF00 | EMV: Request to go online
0xFF01 | EMV: Accept the offline transaction
0xFF02 | EMV: Decline the offline transaction
0xFF03 | EMV: Accept the online transaction
0xFF04 | EMV: Decline the online transaction
0xFF05 | EMV: Application may fallback to magstripe technology
0xFF06 | EMV: ICC detected that the conditions of use are not satisfied
0xFF07 | EMV: ICC didn't accept transaction
0xFF08 | EMV: Transaction was cancelled
0xFF09 | EMV: Application was not selected by kernel or ICC format error or ICC missing data error
0xFF0A | EMV: Transaction is terminated
0xFF0B | EMV: Other EMV Error
*/
-(NSString *) device_getResponseCodeString: (int) errorCode;
/**
* Is Audio Reader Connected
*
Returns value on device connection status when device is an audio-type connected to headphone plug.
@retval BOOL True = Connected, False = Disconnected
*/
-(BOOL) device_isAudioReaderConnected;
/**
Is Device Connected
Returns the connection status of the requested device
@param device Check connectivity of device type
@code
typedef enum{
IDT_DEVICE_UniPay_IOS = 3,
IDT_DEVICE_UniPay_OSX_USB = 4
}IDT_DEVICE_Types;
@endcode
*/
-(bool) device_isConnected:(IDT_DEVICE_Types)device;
/**
* Reboot Device
*
Executes a command to restart the device.
*
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) device_rebootDevice;
/**
* Send a NSData object to device
*
* Sends a command represented by the provide NSData object to the device through the accessory protocol.
*
* @param cmd NSData representation of command to execute
* @param lrc If <c>TRUE</c>, this will wrap command with start/length/lrc/sum/end: '{STX}{Len_Low}{Len_High} data {CheckLRC} {CheckSUM} {ETX}'
@param response Response data
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:())
*/
-(RETURN_CODE) device_sendDataCommand:(NSData*)cmd calcLRC:(BOOL)lrc response:(NSData**)response;
/**
* Set Volume To Audio Reader
*
Set the iPhone’s volume for command communication with audio-based readers. The the range of iPhone’s volume is from 0.1 to 1.0.
@param val Volume level from 0.1 to 1.0
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) device_setAudioVolume:(float)val;
/**
* Exchange APDU
*
* Sends an APDU packet to the ICC. If successful, response is returned in APDUResult class instance in response parameter.
@param dataAPDU APDU data packet
@param encrypted Send data encrypted for special case
@param response Unencrypted/encrypted parsed APDU response
*
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:())
*/
-(RETURN_CODE) icc_exchangeAPDU:(NSData*)dataAPDU encrypted:(BOOL)encrypted response:(APDUResponse**)response;
/**
* Exchange Encrypted APDU
- UniPay
*
* Sends an encrypted APDU packet to the ICC. If successful, response is returned in APDUResult class instance in response parameter.
@param dataAPDU APDU data packet
@param response encrypted parsed APDU response
*
* @retval RETURN_CODE:
- 0x0000: Success: no error - RETURN_CODE_DO_SUCCESS
- 0x0001: Disconnect: no response from reader - RETURN_CODE_ERR_DISCONNECT
- 0x0002: Invalid Response: invalid response data - RETURN_CODE_ERR_CMD_RESPONSE
- 0x0003: Timeout: time out for task or CMD - RETURN_CODE_ERR_TIMEDOUT
- 0x0004: Invalid Parameter: wrong parameter - RETURN_CODE_ERR_INVALID_PARAMETER
- 0x0005: MSR Busy: SDK is doing MSR or ICC task - RETURN_CODE_SDK_BUSY_MSR
- 0x0006: PINPad Busy: SDK is doing PINPad task - RETURN_CODE_SDK_BUSY_PINPAD
- 0x0007: Unknown: Unknown error - RETURN_CODE_ERR_OTHER
- 0x0100 through 0xFFFF refer to IDT_Device::getResponseCodeString:()
*/
-(RETURN_CODE) icc_exchangeEncryptedAPDU:(NSData*)dataAPDU response:(APDUResponse**)response;
/**
* Exchange Multi APDU
*
Sends multiple APDU commands within on command
@param dataAPDU An array of NSData APDU commands
@param response The combined response of the multiple APDU commands
* @retval RETURN_CODE:
- 0x0000: Success: no error - RETURN_CODE_DO_SUCCESS
- 0x0001: Disconnect: no response from reader - RETURN_CODE_ERR_DISCONNECT
- 0x0002: Invalid Response: invalid response data - RETURN_CODE_ERR_CMD_RESPONSE
- 0x0003: Timeout: time out for task or CMD - RETURN_CODE_ERR_TIMEDOUT
- 0x0004: Invalid Parameter: wrong parameter - RETURN_CODE_ERR_INVALID_PARAMETER
- 0x0005: MSR Busy: SDK is doing MSR or ICC task - RETURN_CODE_SDK_BUSY_MSR
- 0x0006: PINPad Busy: SDK is doing PINPad task - RETURN_CODE_SDK_BUSY_PINPAD
- 0x0007: Unknown: Unknown error - RETURN_CODE_ERR_OTHER
- 0x0100 through 0xFFFF refer to IDT_Device::getResponseCodeString:()
*/
-(RETURN_CODE) icc_exchangeMultiAPDU:(NSArray*)dataAPDU response:(NSData**)response;
/**
* Get APDU KSN
*
* Retrieves the KSN used in ICC Encypted APDU usage
* @param ksn Returns the encrypted APDU packet KSN
*
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE
*/
-(RETURN_CODE) icc_getAPDU_KSN:(NSData**)ksn;
/**
* Get Reader Status
*
Returns the reader status
@param readerStatus Pointer that will return with the ICCReaderStatus results.
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
@code
ICCReaderStatus readerStatus;
RETURN_CODE rt = [[IDT_UniPay sharedController] icc_getICCReaderStatus:&readerStatus];
if(RETURN_CODE_DO_SUCCESS != rt){
LOGI(@"Fail");
}
else{
NSString *sta;
if(readerStatus.iccPower)
sta =@"[ICC Powered]";
else
sta = @"[ICC Power not Ready]";
if(readerStatus.cardSeated)
sta =[NSString stringWithFormat:@"%@,[Card Seated]", sta];
else
sta =[NSString stringWithFormat:@"%@,[Card not Seated]", sta];
LOGI(@"Card Status = %@",sta);
}
@endcode
*/
-(RETURN_CODE) icc_getICCReaderStatus:(ICCReaderStatus**)readerStatus;
/**
* Get Key Format For ICC DUKPT
*
* Specifies how data will be encrypted with Data Key or PIN key (if DUKPT key loaded)
*
* @param response Response returned from method:
- 'TDES': Encrypted card data with TDES if DUKPT Key had been loaded.(default)
- 'AES': Encrypted card data with AES if DUKPT Key had been loaded.
- 'NONE': No Encryption.
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) icc_getKeyFormatForICCDUKPT:(NSString**)response;
/**
* Get Key Type for ICC DUKPT
*
* Specifies the key type used for ICC DUKPT encryption
*
* @param response Response returned from method:
- 'DATA': Encrypted card data with Data Key DUKPT Key had been loaded.(default)
- 'PIN': Encrypted card data with PIN Key if DUKPT Key had been loaded.
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) icc_getKeyTypeForICCDUKPT:(NSString**)response;
/**
* Power Off ICC
*
* Powers down the ICC
* @param error Returns the error, if any
*
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
If Success, empty
If Failure, ASCII encoded data of error string
*/
-(RETURN_CODE) icc_powerOffICC:(NSString**)error;
/**
* Power On ICC
*
* Power up the currently selected microprocessor card in the ICC reader
*
* @param response Response returned. If Success, ATR String. If Failure, ASCII encoded data of error string
*
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) icc_powerOnICC:(NSData**)response;
/**
* Set ICC Notifications
*
Determins if card insert/remove events are captured and sent to delegate UniPay_EventFunctionICC
@param turnON TRUE = monitor ICC card events, FALSE = ignore ICC card events. Default value is FALSE/OFF.
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) icc_setICCNotification:(BOOL)turnON;
/**
* Set Key Format for ICC DUKPT
*
* Sets how data will be encrypted, with either TDES or AES (if DUKPT key loaded)
*
@param encryption Encryption Type
- 00: Encrypt with TDES
- 01: Encrypt with AES
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) icc_setKeyFormatForICCDUKPT:(int)encryption;
/**
* Set Key Type for ICC DUKPT Key
*
* Sets which key the data will be encrypted with, with either Data Key or PIN key (if DUKPT key loaded)
*
@param encryption Encryption Type
- 00: Encrypt with Data Key
- 01: Encrypt with PIN Key
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:())
*/
-(RETURN_CODE) icc_setKeyTypeForICCDUKPT:(int)encryption;
/**
* Disable MSR Swipe
Cancels MSR swipe request.
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_cancelMSRSwipe;
/**
* Get Clear PAN Digits
*
* Returns the number of digits that begin the PAN that will be in the clear
*
* @param response Number of digits in clear. Values are ASCII '0' - '6':
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_getClearPANID:(NSString**)response;
/**
* Get Expiration Masking
*
* Get the flag that determines if to mask the expiration date
*
* @param response '0' = masked, '1' = not-masked
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_getExpirationMask:(NSString**)response;
/**
* Get Swipe Data Encryption
*
* Returns the encryption used for sweip data
*
* @param response 'TDES', 'AES', 'NONE'
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_getSwipeEncryption:(NSString**)response;
/**
* Get Swipe Data Encryption
*
* Gets the swipe force encryption options
*
* @param response A string with for flags separated by PIPE character f1|f2|f3|f4, example "1|0|0|1" where:
- f1 = Track 1 Force Encrypt
- f2 = Track 2 Force Encrypt
- f3 = Track 3 Force Encrypt
- f4 = Track 3 Force Encrypt when card type is 0
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_getSwipeForcedEncryptionOption:(NSString**)response;
/**
* Get Swipe Mask Option
*
* Gets the swipe mask/clear data sending option
*
* @param response A string with for flags separated by PIPE character f1|f2|f3, example "1|0|0" where:
- f1 = Track 1 Mask Allowed
- f2 = Track 2 Mask Allowed
- f3 = Track 3 Mask Allowed
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_getSwipeMaskOption:(NSString**)response;
/**
* Set Clear PAN Digits
*
* Sets the amount of digits shown in the clear (not masked) at the beginning of the returned PAN value
*
@param digits Number of digits to show in clear. Range 0-6.
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_setClearPANID:(int)digits;
/**
* Set Expiration Masking
*
* Sets the flag to mask the expiration date
*
@param masked TRUE = mask expiration
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_setExpirationMask:(BOOL)masked;
/**
* Set Swipe Data Encryption
*
* Sets the swipe encryption method
*
@param encryption 1 = TDES, 2 = AES
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_setSwipeEncryption:(int)encryption;
/**
* Set Swipe Force Encryption
*
* Sets the swipe force encryption options
*
@param track1 Force encrypt track 1
@param track2 Force encrypt track 2
@param track3 Force encrypt track 3
@param track3card0 Force encrypt track 3 when card type is 0
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_setSwipeForcedEncryptionOption:(BOOL)track1 track2:(BOOL)track2 track3:(BOOL)track3 track3card0:(BOOL)track3card0;
/**
* Set Swipe Mask Option
*
* Sets the swipe mask/clear data sending option
*
@param track1 Mask track 1 allowed
@param track2 Mask track 2 allowed
@param track3 Mask track 3 allowed
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_setSwipeMaskOption:(BOOL)track1 track2:(BOOL)track2 track3:(BOOL)track3;
/**
* Enable MSR Swipe
*
Enables MSR, waiting for swipe to occur. Allows track selection. Returns IDTMSRData instance to deviceDelegate::swipeMSRData:()
@param track Track Selection Option
Track Selection Option | Val
------------ | ------------
Any Track | 0
Track 1 Only | 1
Track 2 Only | 2
Track 1 & Track 2 | 3
Track 3 Only | 4
Track 1 & Track 3 | 5
Track 2 & Track 3 | 6
All three Tracks | 7
* @retval RETURN_CODE: Return codes listed as typedef enum in IDTCommon:RETURN_CODE. Values can be parsed with IDT_UniPay::device_getResponseCodeString:()
*/
-(RETURN_CODE) msr_startMSRSwipe:(int)track;
/**
Device Connected
@retval isConnected Boolean indicated if UniPay is connected
*/
-(bool) isConnected;
/**
* Attempt connection
*
Requests a connection attempt
*/
-(void) attemptConnect;
@end
| 28.909513 | 235 | 0.742817 | [
"object",
"model"
] |
48fc56e92e48135c7a5936f08a69d0cd34cc21a1 | 18,277 | h | C | SofaKernel/modules/SofaRigid/JointSpringForceField.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/modules/SofaRigid/JointSpringForceField.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | SofaKernel/modules/SofaRigid/JointSpringForceField.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_COMPONENT_INTERACTIONFORCEFIELD_JOINTSPRINGFORCEFIELD_H
#define SOFA_COMPONENT_INTERACTIONFORCEFIELD_JOINTSPRINGFORCEFIELD_H
#include "config.h"
#include <sofa/core/behavior/PairInteractionForceField.h>
#include <sofa/core/behavior/MechanicalState.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/defaulttype/Mat.h>
#include <vector>
#include <sofa/core/MechanicalParams.h>
#include <sofa/core/objectmodel/DataFileName.h>
namespace sofa
{
namespace component
{
namespace interactionforcefield
{
template<typename DataTypes>
class JointSpring
{
public:
typedef typename DataTypes::Coord Coord ;
typedef typename Coord::value_type Real ;
typedef typename DataTypes::Deriv Deriv ;
typedef typename DataTypes::VecCoord VecCoord;
typedef typename DataTypes::VecDeriv VecDeriv;
enum { N=DataTypes::spatial_dimensions };
typedef defaulttype::Mat<N,N,Real> Mat;
typedef defaulttype::Vec<N,Real> Vector;
int m1, m2; /// the two extremities of the spring: masses m1 and m2
Real kd; /// damping factor
Vector torsion; /// torsion of the springs in axis/angle format
Vector lawfulTorsion; /// projected torsion in allowed angles
Vector KT; // linear stiffness
Vector KR; // angular stiffness
defaulttype::Quat ref; // referential of the spring (p1) to use it in addSpringDForce()
Vector initTrans; /// offset length of the spring
defaulttype::Quat initRot; /// offset orientation of the spring
sofa::defaulttype::Vec<6,bool> freeMovements; ///defines the axis where the movements is free. (0,1,2)--> translation axis (3,4,5)-->rotation axis
Real softStiffnessTrans; ///stiffness to apply on axis where the translations are free (default 0.0)
Real hardStiffnessTrans; ///stiffness to apply on axis where the translations are forbidden (default 10000.0)
Real softStiffnessRot; ///stiffness to apply on axis where the rotations are free (default 0.0)
Real hardStiffnessRot; ///stiffness to apply on axis where the rotations are forbidden (default 10000.0)
Real blocStiffnessRot; ///stiffness to apply on axis where the rotations are bloqued (=hardStiffnessRot/100)
bool needToInitializeTrans;
bool needToInitializeRot;
sofa::defaulttype::Vec<6,Real> limitAngles; ///limit angles on rotation axis (default no limit)
///constructors
JointSpring()
: m1(0), m2(0), kd(0), torsion(0,0,0) , lawfulTorsion(0,0,0), KT(0,0,0) , KR(0,0,0)
, softStiffnessTrans(0), hardStiffnessTrans(10000), softStiffnessRot(0), hardStiffnessRot(10000), blocStiffnessRot(100), needToInitializeTrans(true), needToInitializeRot(true)
//, freeMovements(0,0,0,1,1,1), limitAngles(-100000, 100000, -100000, 100000, -100000, 100000)
{
freeMovements = sofa::defaulttype::Vec<6,bool>(0,0,0,1,1,1);
limitAngles = sofa::defaulttype::Vec<6,Real>(-100000, 100000, -100000, 100000, -100000, 100000);
initTrans = Vector(0,0,0);
initRot = defaulttype::Quat(0,0,0,1);
}
JointSpring(int m1, int m2)
: m1(m1), m2(m2), kd(0), torsion(0,0,0), lawfulTorsion(0,0,0), KT(0,0,0) , KR(0,0,0)
, softStiffnessTrans(0), hardStiffnessTrans(10000), softStiffnessRot(0), hardStiffnessRot(10000), blocStiffnessRot(100), needToInitializeTrans(true), needToInitializeRot(true)
//, freeMovements(0,0,0,1,1,1), limitAngles(-100000, 100000, -100000, 100000, -100000, 100000)
{
freeMovements = sofa::defaulttype::Vec<6,bool>(0,0,0,1,1,1);
limitAngles = sofa::defaulttype::Vec<6,Real>(-100000, 100000, -100000, 100000, -100000, 100000);
initTrans = Vector(0,0,0);
initRot = defaulttype::Quat(0,0,0,1);
}
JointSpring(int m1, int m2, Real softKst, Real hardKst, Real softKsr, Real hardKsr, Real blocKsr, Real axmin, Real axmax, Real aymin, Real aymax, Real azmin, Real azmax, Real kd)
: m1(m1), m2(m2), kd(kd), torsion(0,0,0), lawfulTorsion(0,0,0), KT(0,0,0) , KR(0,0,0)
//,limitAngles(axmin,axmax,aymin,aymax,azmin,azmax)
, softStiffnessTrans(softKst), hardStiffnessTrans(hardKst), softStiffnessRot(softKsr), hardStiffnessRot(hardKsr), blocStiffnessRot(blocKsr), needToInitializeTrans(true), needToInitializeRot(true)
{
limitAngles = sofa::defaulttype::Vec<6,Real>(axmin,axmax,aymin,aymax,azmin,azmax);
freeMovements = sofa::defaulttype::Vec<6,bool>(false, false, false, true, true, true);
for (unsigned int i=0; i<3; i++)
{
if(limitAngles[2*i]==limitAngles[2*i+1])
freeMovements[3+i] = false;
}
initTrans = Vector(0,0,0);
initRot = defaulttype::Quat(0,0,0,1);
}
//accessors
Real getHardStiffnessRotation() {return hardStiffnessRot;}
Real getSoftStiffnessRotation() {return softStiffnessRot;}
Real getHardStiffnessTranslation() {return hardStiffnessTrans;}
Real getSoftStiffnessTranslation() {return softStiffnessTrans;}
Real getBlocStiffnessRotation() { return blocStiffnessRot; }
sofa::defaulttype::Vec<6,Real> getLimitAngles() { return limitAngles;}
sofa::defaulttype::Vec<6,bool> getFreeAxis() { return freeMovements;}
Vector getInitLength() { return initTrans; }
defaulttype::Quat getInitOrientation() { return initRot; }
//affectors
void setHardStiffnessRotation(Real ksr) { hardStiffnessRot = ksr; }
void setSoftStiffnessRotation(Real ksr) { softStiffnessRot = ksr; }
void setHardStiffnessTranslation(Real kst) { hardStiffnessTrans = kst; }
void setSoftStiffnessTranslation(Real kst) { softStiffnessTrans = kst; }
void setBlocStiffnessRotation(Real ksb) { blocStiffnessRot = ksb; }
void setLimitAngles(const sofa::defaulttype::Vec<6,Real>& lims)
{
limitAngles = lims;
if(lims[0]==lims[1]) freeMovements[3]=false;
if(lims[2]==lims[3]) freeMovements[4]=false;
if(lims[4]==lims[5]) freeMovements[5]=false;
}
void setLimitAngles(Real minx, Real maxx, Real miny, Real maxy, Real minz, Real maxz)
{
limitAngles = sofa::defaulttype::Vec<6,Real>(minx, maxx, miny, maxy, minz, maxz);
if(minx==maxx) freeMovements[3]=false;
if(miny==maxy) freeMovements[4]=false;
if(minz==maxz) freeMovements[5]=false;
}
void setInitLength( const Vector& l) { initTrans=l; }
void setInitOrientation( const defaulttype::Quat& o) { initRot=o; }
void setInitOrientation( const Vector& o) { initRot=defaulttype::Quat::createFromRotationVector(o); }
void setFreeAxis(const sofa::defaulttype::Vec<6,bool>& axis) { freeMovements = axis; }
void setFreeAxis(bool isFreeTx, bool isFreeTy, bool isFreeTz, bool isFreeRx, bool isFreeRy, bool isFreeRz)
{
freeMovements = sofa::defaulttype::Vec<6,bool>(isFreeTx, isFreeTy, isFreeTz, isFreeRx, isFreeRy, isFreeRz);
}
void setDamping(Real _kd) { kd = _kd; }
inline friend std::istream& operator >> ( std::istream& in, JointSpring<DataTypes>& s )
{
//default joint is a free rotation joint --> translation is bloqued, rotation is free
s.freeMovements = sofa::defaulttype::Vec<6,bool>(false, false, false, true, true, true);
s.initTrans = Vector(0,0,0);
s.initRot = defaulttype::Quat(0,0,0,1);
s.blocStiffnessRot = 0.0;
//by default no angle limitation is set (bi values for initialisation)
s.limitAngles = sofa::defaulttype::Vec<6,Real>(-100000., 100000., -100000., 100000., -100000., 100000.);
bool initTransFound=false;
// bool initRotFound=false;
std::string str;
in>>str;
if(str == "BEGIN_SPRING")
{
in>>s.m1>>s.m2; //read references
in>>str;
while(str != "END_SPRING")
{
if(str == "FREE_AXIS")
in>>s.freeMovements;
else if(str == "KS_T")
in>>s.softStiffnessTrans>>s.hardStiffnessTrans;
else if(str == "KS_R")
in>>s.softStiffnessRot>>s.hardStiffnessRot;
else if(str == "KS_B")
in>>s.blocStiffnessRot;
else if(str == "KD")
in>>s.kd;
else if(str == "R_LIM_X")
in>>s.limitAngles[0]>>s.limitAngles[1];
else if(str == "R_LIM_Y")
in>>s.limitAngles[2]>>s.limitAngles[3];
else if(str == "R_LIM_Z")
in>>s.limitAngles[4]>>s.limitAngles[5];
else if(str == "REST_T")
{
in>>s.initTrans;
initTransFound=true;
}
else if(str == "REST_R")
{
in>>s.initRot;
// initRotFound=true;
}
else
{
std::cerr<<"Error parsing Spring : Unknown Attribute "<<str<<std::endl;
return in;
}
in>>str;
}
}
s.needToInitializeTrans = initTransFound;
s.needToInitializeRot = initTransFound;
//if no blocStiffnessRot was specified (typically 0), we use hardStiffnessRot/100
if(s.blocStiffnessRot == 0.0)
s.blocStiffnessRot = s.hardStiffnessRot/100;
//if limit angle were specified, free rotation axis are set from them
for (unsigned int i=0; i<3; i++)
{
if(s.limitAngles[2*i]==s.limitAngles[2*i+1])
s.freeMovements[3+i] = false;
}
return in;
}
friend std::ostream& operator << ( std::ostream& out, const JointSpring<DataTypes>& s )
{
out<<"BEGIN_SPRING "<<s.m1<<" "<<s.m2<<" ";
if (s.freeMovements[0]!=false || s.freeMovements[1]!=false || s.freeMovements[2]!=false || s.freeMovements[3]!=true || s.freeMovements[4]!=true || s.freeMovements[5]!=true)
out<<"FREE_AXIS "<<s.freeMovements<<" ";
if (s.softStiffnessTrans != 0.0 || s.hardStiffnessTrans != 10000.0)
out<<"KS_T "<<s.softStiffnessTrans<<" "<<s.hardStiffnessTrans<<" ";
if (s.softStiffnessRot != 0.0 || s.hardStiffnessRot != 10000.0)
out<<"KS_R "<<s.softStiffnessRot<<" "<<s.hardStiffnessRot<<" ";
if (s.blocStiffnessRot != s.hardStiffnessRot/100)
out<<"KS_B "<<s.blocStiffnessRot<<" ";
if (s.kd != 0.0)
out<<"KD "<<s.kd<<" ";
if (s.limitAngles[0]!=-100000 || s.limitAngles[1] != 100000)
out<<"R_LIM_X "<<s.limitAngles[0]<<" "<<s.limitAngles[1]<<" ";
if (s.limitAngles[2]!=-100000 || s.limitAngles[3] != 100000)
out<<"R_LIM_Y "<<s.limitAngles[2]<<" "<<s.limitAngles[3]<<" ";
if (s.limitAngles[4]!=-100000 || s.limitAngles[5] != 100000)
out<<"R_LIM_Z "<<s.limitAngles[4]<<" "<<s.limitAngles[5]<<" ";
if (s.initTrans!= Vector(0,0,0))
out<<"REST_T "<<s.initTrans<<" ";
if (s.initRot[3]!= 1)
out<<"REST_R "<<s.initRot<<" ";
out<<"END_SPRING"<<std::endl;
return out;
}
};
// end class JointSpring
template<class DataTypes>
class JointSpringForceFieldInternalData
{
public:
};
/** JointSpringForceField simulates 6D springs between Rigid DOFS
Use kst vector to specify the directionnal stiffnesses (on each local axe)
Use ksr vector to specify the rotational stiffnesses (on each local axe)
*/
template<class DataTypes>
class JointSpringForceField : public core::behavior::PairInteractionForceField<DataTypes>
{
public:
SOFA_CLASS(SOFA_TEMPLATE(JointSpringForceField, DataTypes), SOFA_TEMPLATE(core::behavior::PairInteractionForceField, DataTypes));
typedef typename core::behavior::PairInteractionForceField<DataTypes> Inherit;
typedef typename DataTypes::VecCoord VecCoord;
typedef typename DataTypes::VecDeriv VecDeriv;
typedef typename DataTypes::Coord Coord;
typedef typename DataTypes::Deriv Deriv;
typedef typename Coord::value_type Real;
typedef core::objectmodel::Data<VecDeriv> DataVecDeriv;
typedef core::objectmodel::Data<VecCoord> DataVecCoord;
typedef core::behavior::MechanicalState<DataTypes> MechanicalState;
enum { N=DataTypes::spatial_dimensions };
typedef defaulttype::Mat<N,N,Real> Mat;
typedef defaulttype::Vec<N,Real> Vector;
typedef JointSpring<DataTypes> Spring;
protected:
SReal m_potentialEnergy;
std::ifstream* infile;
std::ofstream* outfile;
JointSpringForceFieldInternalData<DataTypes> data;
friend class JointSpringForceFieldInternalData<DataTypes>;
/// Accumulate the spring force and compute and store its stiffness
void addSpringForce(SReal& potentialEnergy, VecDeriv& f1, const VecCoord& p1, const VecDeriv& v1, VecDeriv& f2, const VecCoord& p2, const VecDeriv& v2, int i, /*const*/ Spring& spring);
/// Apply the stiffness, i.e. accumulate df given dx
void addSpringDForce(VecDeriv& df1, const VecDeriv& dx1, VecDeriv& df2, const VecDeriv& dx2, int i, /*const*/ Spring& spring, Real kFactor);
// project torsion to Lawfulltorsion according to limitangles
void projectTorsion(Spring& spring);
JointSpringForceField(MechanicalState* object1, MechanicalState* object2);
JointSpringForceField();
virtual ~JointSpringForceField();
public:
core::behavior::MechanicalState<DataTypes>* getObject1() { return this->mstate1; }
core::behavior::MechanicalState<DataTypes>* getObject2() { return this->mstate2; }
virtual void init();
virtual void bwdInit();
virtual void addForce(const core::MechanicalParams* mparams, DataVecDeriv& data_f1, DataVecDeriv& data_f2, const DataVecCoord& data_x1, const DataVecCoord& data_x2, const DataVecDeriv& data_v1, const DataVecDeriv& data_v2 );
virtual void addDForce(const core::MechanicalParams* mparams, DataVecDeriv& data_df1, DataVecDeriv& data_df2, const DataVecDeriv& data_dx1, const DataVecDeriv& data_dx2);
virtual SReal getPotentialEnergy(const core::MechanicalParams*, const DataVecCoord&, const DataVecCoord& ) const { return m_potentialEnergy; }
sofa::helper::vector<Spring> * getSprings() { return springs.beginEdit(); }
void draw(const core::visual::VisualParams* vparams);
void computeBBox(const core::ExecParams* params, bool /*onlyVisible*/);
// -- Modifiers
void clear(int reserve=0)
{
helper::vector<Spring>& springs = *this->springs.beginEdit();
springs.clear();
if (reserve) springs.reserve(reserve);
this->springs.endEdit();
}
void addSpring(const Spring& s)
{
springs.beginEdit()->push_back(s);
springs.endEdit();
}
void addSpring(int m1, int m2, Real softKst, Real hardKst, Real softKsr, Real hardKsr, Real blocKsr, Real axmin, Real axmax, Real aymin, Real aymax, Real azmin, Real azmax, Real kd)
{
Spring s(m1,m2,softKst,hardKst,softKsr,hardKsr, blocKsr, axmin, axmax, aymin, aymax, azmin, azmax, kd);
const VecCoord& x1= this->mstate1->read(core::ConstVecCoordId::position())->getValue();
const VecCoord& x2= this->mstate2->read(core::ConstVecCoordId::position())->getValue();
s.initTrans = x2[m2].getCenter() - x1[m1].getCenter();
s.initRot = x2[m2].getOrientation()*x1[m1].getOrientation().inverse();
springs.beginEdit()->push_back(s);
springs.endEdit();
}
/// the list of the springs
Data<sofa::helper::vector<Spring> > springs;
sofa::core::objectmodel::DataFileName f_outfilename;
sofa::core::objectmodel::DataFileName f_infilename;
Data < Real > f_period;
Data<bool> f_reinit;
Real lastTime;
/// bool to allow the display of the 2 parts of springs torsions
Data<bool> showLawfulTorsion;
Data<bool> showExtraTorsion;
Data<Real> showFactorSize;
virtual void updateForceMask();
};
#if defined(SOFA_EXTERN_TEMPLATE) && !defined(SOFA_COMPONENT_FORCEFIELD_JOINTSPRINGFORCEFIELD_CPP)
#ifndef SOFA_FLOAT
extern template class SOFA_RIGID_API JointSpring<defaulttype::Rigid3dTypes>;
extern template class SOFA_RIGID_API JointSpringForceField<defaulttype::Rigid3dTypes>;
#endif
#ifndef SOFA_DOUBLE
extern template class SOFA_RIGID_API JointSpring<defaulttype::Rigid3fTypes>;
extern template class SOFA_RIGID_API JointSpringForceField<defaulttype::Rigid3fTypes>;
#endif
#endif
} // namespace interactionforcefield
} // namespace component
} // namespace sofa
#endif /* SOFA_COMPONENT_INTERACTIONFORCEFIELD_JOINTSPRINGFORCEFIELD_H */
| 44.469586 | 228 | 0.636428 | [
"vector"
] |
48fd656b9b9b49e0bb630ab40805fe3d19cb2065 | 10,086 | h | C | pic32/cores/pic32/flow/core/pageinfo.h | IMG-FlowCloud/flowcloud-mpide | 0614ed39ba3df2a5d30e5dcd738ae3ebab49f15a | [
"BSD-3-Clause"
] | null | null | null | pic32/cores/pic32/flow/core/pageinfo.h | IMG-FlowCloud/flowcloud-mpide | 0614ed39ba3df2a5d30e5dcd738ae3ebab49f15a | [
"BSD-3-Clause"
] | null | null | null | pic32/cores/pic32/flow/core/pageinfo.h | IMG-FlowCloud/flowcloud-mpide | 0614ed39ba3df2a5d30e5dcd738ae3ebab49f15a | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
Copyright (c) 2014, Imagination Technologies Limited
All rights reserved.
Redistribution and use of the Software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. The Software (including after any modifications that you make to it) must support the FlowCloud Web Service API provided by Licensor and accessible at http://ws-uat.flowworld.com and/or some other location(s) that we specify.
2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
3. 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.
4. 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.
*****************************************************************************/
/** @file */
#ifndef FLOW_CORE_PAGEINFO_H_
#define FLOW_CORE_PAGEINFO_H_
#include "flow/core/base_types.h"
#include "flow/core/flow_httpmethod.h"
#include "flow/core/flow_memorymanager.h"
#include "flow/core/flow_memorymanager_methods.h"
#include "flow/core/flow_object.h"
#include "flow/core/flow_object_methods.h"
#include "flow/core/pageinfo_type.h"
#include "flow/core/xml_serialisation.h"
/**
* \memberof FlowPageInfo
* \brief Creates a new FlowPageInfo.
*
* You should use the result of this method whenever you need to submit a Object as a \a data parameter.
* \param memoryManager Memory manager on which the method will be applied
*/
static inline FlowPageInfo FlowPageInfo_New(FlowMemoryManager memoryManager){ return (FlowPageInfo)FlowMemoryManager_NewObject(memoryManager, 4, 4, FlowType_PageInfo);}
/**
* \memberof FlowPageInfo
* \brief Registers meta data used for (de)serialising FlowPageInfo to XML.
*
* You should this if you are going to use this type in application code.
*/
static inline void FlowPageInfo_RegisterType()
{
if(!FlowXMLDeserialiser_IsRegisteredType(FlowType_PageInfo))
{
FlowXMLDeserialiser_RegisterType(FlowType_PageInfo, "PageInfo", 4, 4);
FlowXMLDeserialiser_RegisterTypeProperty(FlowType_PageInfo, _FlowPageInfo_TotalCount, FlowType_Integer, "TotalCount", true);
FlowXMLDeserialiser_RegisterTypeProperty(FlowType_PageInfo, _FlowPageInfo_ItemsCount, FlowType_Integer, "ItemsCount", true);
FlowXMLDeserialiser_RegisterTypeProperty(FlowType_PageInfo, _FlowPageInfo_StartIndex, FlowType_Integer, "StartIndex", true);
FlowXMLDeserialiser_RegisterTypeProperty(FlowType_PageInfo, _FlowPageInfo_AlphaIndex, FlowType_String, "AlphaIndex", true);
FlowXMLDeserialiser_RegisterTypeLink(FlowType_PageInfo, _FlowPageInfo_rel_First, "first");
FlowXMLDeserialiser_RegisterTypeLink(FlowType_PageInfo, _FlowPageInfo_rel_Last, "last");
FlowXMLDeserialiser_RegisterTypeLink(FlowType_PageInfo, _FlowPageInfo_rel_Next, "next");
FlowXMLDeserialiser_RegisterTypeLink(FlowType_PageInfo, _FlowPageInfo_rel_Previous, "previous");
}
}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property TotalCount is set on this object.
*
* Can be used to check whether TotalCount is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasTotalCount(FlowPageInfo self) { return FlowObject_HasProperty(self, _FlowPageInfo_TotalCount);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline int FlowPageInfo_GetTotalCount(FlowPageInfo self) { return FlowObject_GetIntegerProperty(self, _FlowPageInfo_TotalCount);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
* \param value new value for this property
*/
static inline void FlowPageInfo_SetTotalCount(FlowPageInfo self, int value) { FlowObject_SetIntegerProperty(self, _FlowPageInfo_TotalCount, value);}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property ItemsCount is set on this object.
*
* Can be used to check whether ItemsCount is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasItemsCount(FlowPageInfo self) { return FlowObject_HasProperty(self, _FlowPageInfo_ItemsCount);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline int FlowPageInfo_GetItemsCount(FlowPageInfo self) { return FlowObject_GetIntegerProperty(self, _FlowPageInfo_ItemsCount);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
* \param value new value for this property
*/
static inline void FlowPageInfo_SetItemsCount(FlowPageInfo self, int value) { FlowObject_SetIntegerProperty(self, _FlowPageInfo_ItemsCount, value);}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property StartIndex is set on this object.
*
* Can be used to check whether StartIndex is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasStartIndex(FlowPageInfo self) { return FlowObject_HasProperty(self, _FlowPageInfo_StartIndex);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline int FlowPageInfo_GetStartIndex(FlowPageInfo self) { return FlowObject_GetIntegerProperty(self, _FlowPageInfo_StartIndex);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
* \param value new value for this property
*/
static inline void FlowPageInfo_SetStartIndex(FlowPageInfo self, int value) { FlowObject_SetIntegerProperty(self, _FlowPageInfo_StartIndex, value);}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property AlphaIndex is set on this object.
*
* Can be used to check whether AlphaIndex is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasAlphaIndex(FlowPageInfo self) { return FlowObject_HasProperty(self, _FlowPageInfo_AlphaIndex);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline char *FlowPageInfo_GetAlphaIndex(FlowPageInfo self) { return FlowObject_GetStringProperty(self, _FlowPageInfo_AlphaIndex);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
* \param value new value for this property
*/
static inline void FlowPageInfo_SetAlphaIndex(FlowPageInfo self, char *value) { FlowObject_SetStringProperty(self, _FlowPageInfo_AlphaIndex, value);}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property First is set on this object.
*
* Can be used to check whether First is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasFirst(FlowPageInfo self) { return FlowObject_HasLink(self, _FlowPageInfo_rel_First);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline char *FlowPageInfo_GetFirst(FlowPageInfo self) { return FlowObject_GetLink(self, _FlowPageInfo_rel_First);}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property Last is set on this object.
*
* Can be used to check whether Last is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasLast(FlowPageInfo self) { return FlowObject_HasLink(self, _FlowPageInfo_rel_Last);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline char *FlowPageInfo_GetLast(FlowPageInfo self) { return FlowObject_GetLink(self, _FlowPageInfo_rel_Last);}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property Next is set on this object.
*
* Can be used to check whether Next is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasNext(FlowPageInfo self) { return FlowObject_HasLink(self, _FlowPageInfo_rel_Next);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline char *FlowPageInfo_GetNext(FlowPageInfo self) { return FlowObject_GetLink(self, _FlowPageInfo_rel_Next);}
/**
* \memberof FlowPageInfo
* \brief Indicates whether the property Previous is set on this object.
*
* Can be used to check whether Previous is available on this object without making an HTTP call.
* \param self Object on which the method will be applied
*/
static inline bool FlowPageInfo_HasPrevious(FlowPageInfo self) { return FlowObject_HasLink(self, _FlowPageInfo_rel_Previous);}
/**
* \memberof FlowPageInfo
* \param self Object on which the method will be applied
*/
static inline char *FlowPageInfo_GetPrevious(FlowPageInfo self) { return FlowObject_GetLink(self, _FlowPageInfo_rel_Previous);}
#endif /* FLOW_CORE_PAGEINFO_H_ */
| 53.935829 | 756 | 0.785643 | [
"object"
] |
5b0085f0c8645cc68bfdec266070ae56079377ee | 1,342 | h | C | include/retdec/loader/utils/overlap_resolver.h | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 521 | 2019-03-29T15:44:08.000Z | 2022-03-22T09:46:19.000Z | include/retdec/loader/utils/overlap_resolver.h | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 30 | 2019-06-04T17:00:49.000Z | 2021-09-08T20:44:19.000Z | include/retdec/loader/utils/overlap_resolver.h | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 99 | 2019-03-29T16:04:13.000Z | 2022-03-28T16:59:34.000Z | /**
* @file include/retdec/loader/utils/overlap_resolver.h
* @brief Declaration of overlap resolver.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_LOADER_UTILS_OVERLAP_RESOLVER_H
#define RETDEC_LOADER_UTILS_OVERLAP_RESOLVER_H
#include <cstdint>
#include <functional>
#include <vector>
#include "retdec/utils/range.h"
#include "retdec/loader/utils/range.h"
namespace retdec {
namespace loader {
/**
* Defines different type of overlaps that can happen.
*/
enum class Overlap
{
None, ///< No overlap.
OverStart, ///< Overlap over starting value.
InMiddle, ///< Overlap somewhere in the middle of the range.
OverEnd, ///< Overlap over ending value.
Full ///< Full overlap of one range over another.
};
class OverlapResolver
{
public:
class Result
{
public:
Result(Overlap overlapType, const std::vector<retdec::utils::Range<std::uint64_t>>& ranges);
Overlap getOverlap() const;
const std::vector<retdec::utils::Range<std::uint64_t>>& getRanges() const;
private:
Overlap _overlap;
std::vector<retdec::utils::Range<std::uint64_t>> _ranges;
};
OverlapResolver() = delete;
static OverlapResolver::Result resolve(const retdec::utils::Range<std::uint64_t>& first, const retdec::utils::Range<std::uint64_t>& second);
};
} // namespace loader
} // namespace retdec
#endif
| 23.54386 | 141 | 0.732489 | [
"vector"
] |
5b097ec108c39a72311159628c3fa71dd69e9024 | 851 | h | C | ports/www/chromium-legacy/newport/files/patch-media_base_scopedfd__helper.h | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2022-02-08T02:24:08.000Z | 2022-02-08T02:24:08.000Z | ports/www/chromium-legacy/newport/files/patch-media_base_scopedfd__helper.h | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ports/www/chromium-legacy/newport/files/patch-media_base_scopedfd__helper.h | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | --- media/base/scopedfd_helper.h.orig 2019-09-09 21:55:20 UTC
+++ media/base/scopedfd_helper.h
@@ -11,17 +11,17 @@
namespace media {
// Theoretically, we can test on defined(OS_POSIX) || defined(OS_FUCHSIA), but
-// since the only current user is V4L2 we are limiting the scope to OS_LINUX so
+// since the only current user is V4L2 we are limiting the scope to OS_LINUX || OS_BSD so
// the binary size does not inflate on non-using systems. Feel free to adapt
// this and BUILD.gn as our needs evolve.
-#if defined(OS_LINUX)
+#if defined(OS_LINUX) || defined(OS_BSD)
// Return a new vector containing duplicates of |fds|, or PCHECKs in case of an
// error.
MEDIA_EXPORT std::vector<base::ScopedFD> DuplicateFDs(
const std::vector<base::ScopedFD>& fds);
-#endif // OS_LINUX
+#endif // OS_LINUX || OS_BSD
} // namespace media
| 35.458333 | 90 | 0.708578 | [
"vector"
] |
5b12b261a4d10626b34760ccd6ad0505620f1683 | 4,361 | c | C | kubernetes/model/apiextensions_v1_webhook_client_config.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | null | null | null | kubernetes/model/apiextensions_v1_webhook_client_config.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | null | null | null | kubernetes/model/apiextensions_v1_webhook_client_config.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "apiextensions_v1_webhook_client_config.h"
apiextensions_v1_webhook_client_config_t *apiextensions_v1_webhook_client_config_create(
char ca_bundle,
apiextensions_v1_service_reference_t *service,
char *url
) {
apiextensions_v1_webhook_client_config_t *apiextensions_v1_webhook_client_config_local_var = malloc(sizeof(apiextensions_v1_webhook_client_config_t));
if (!apiextensions_v1_webhook_client_config_local_var) {
return NULL;
}
apiextensions_v1_webhook_client_config_local_var->ca_bundle = ca_bundle;
apiextensions_v1_webhook_client_config_local_var->service = service;
apiextensions_v1_webhook_client_config_local_var->url = url;
return apiextensions_v1_webhook_client_config_local_var;
}
void apiextensions_v1_webhook_client_config_free(apiextensions_v1_webhook_client_config_t *apiextensions_v1_webhook_client_config) {
if(NULL == apiextensions_v1_webhook_client_config){
return ;
}
listEntry_t *listEntry;
if (apiextensions_v1_webhook_client_config->service) {
apiextensions_v1_service_reference_free(apiextensions_v1_webhook_client_config->service);
apiextensions_v1_webhook_client_config->service = NULL;
}
if (apiextensions_v1_webhook_client_config->url) {
free(apiextensions_v1_webhook_client_config->url);
apiextensions_v1_webhook_client_config->url = NULL;
}
free(apiextensions_v1_webhook_client_config);
}
cJSON *apiextensions_v1_webhook_client_config_convertToJSON(apiextensions_v1_webhook_client_config_t *apiextensions_v1_webhook_client_config) {
cJSON *item = cJSON_CreateObject();
// apiextensions_v1_webhook_client_config->ca_bundle
if(apiextensions_v1_webhook_client_config->ca_bundle) {
if(cJSON_AddNumberToObject(item, "caBundle", apiextensions_v1_webhook_client_config->ca_bundle) == NULL) {
goto fail; //Byte
}
}
// apiextensions_v1_webhook_client_config->service
if(apiextensions_v1_webhook_client_config->service) {
cJSON *service_local_JSON = apiextensions_v1_service_reference_convertToJSON(apiextensions_v1_webhook_client_config->service);
if(service_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "service", service_local_JSON);
if(item->child == NULL) {
goto fail;
}
}
// apiextensions_v1_webhook_client_config->url
if(apiextensions_v1_webhook_client_config->url) {
if(cJSON_AddStringToObject(item, "url", apiextensions_v1_webhook_client_config->url) == NULL) {
goto fail; //String
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
apiextensions_v1_webhook_client_config_t *apiextensions_v1_webhook_client_config_parseFromJSON(cJSON *apiextensions_v1_webhook_client_configJSON){
apiextensions_v1_webhook_client_config_t *apiextensions_v1_webhook_client_config_local_var = NULL;
// apiextensions_v1_webhook_client_config->ca_bundle
cJSON *ca_bundle = cJSON_GetObjectItemCaseSensitive(apiextensions_v1_webhook_client_configJSON, "caBundle");
if (ca_bundle) {
if(!cJSON_IsNumber(ca_bundle))
{
goto end; //Byte
}
}
// apiextensions_v1_webhook_client_config->service
cJSON *service = cJSON_GetObjectItemCaseSensitive(apiextensions_v1_webhook_client_configJSON, "service");
apiextensions_v1_service_reference_t *service_local_nonprim = NULL;
if (service) {
service_local_nonprim = apiextensions_v1_service_reference_parseFromJSON(service); //nonprimitive
}
// apiextensions_v1_webhook_client_config->url
cJSON *url = cJSON_GetObjectItemCaseSensitive(apiextensions_v1_webhook_client_configJSON, "url");
if (url) {
if(!cJSON_IsString(url))
{
goto end; //String
}
}
apiextensions_v1_webhook_client_config_local_var = apiextensions_v1_webhook_client_config_create (
ca_bundle ? ca_bundle->valueint : 0,
service ? service_local_nonprim : NULL,
url ? strdup(url->valuestring) : NULL
);
return apiextensions_v1_webhook_client_config_local_var;
end:
if (service_local_nonprim) {
apiextensions_v1_service_reference_free(service_local_nonprim);
service_local_nonprim = NULL;
}
return NULL;
}
| 34.888 | 154 | 0.768631 | [
"model"
] |
5b17bee9bc02c2ae94b346b0545288447d59d6c8 | 23,964 | h | C | src/utils/ans_utils.h | RReverser/libwebp2 | c90b5b476004c9a98731ae1c175cebab5de50fbf | [
"Apache-2.0"
] | 4 | 2020-11-10T17:46:57.000Z | 2022-03-22T06:24:17.000Z | src/utils/ans_utils.h | RReverser/libwebp2 | c90b5b476004c9a98731ae1c175cebab5de50fbf | [
"Apache-2.0"
] | null | null | null | src/utils/ans_utils.h | RReverser/libwebp2 | c90b5b476004c9a98731ae1c175cebab5de50fbf | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 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
//
// https://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.
// -----------------------------------------------------------------------------
//
// Assymetric Numeral System helper functions.
//
// Author: Skal (pascal.massimino@gmail.com)
#ifndef WP2_UTILS_ANS_UTILS_H_
#define WP2_UTILS_ANS_UTILS_H_
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include "src/dsp/math.h"
#include "src/utils/ans.h"
namespace WP2 {
//------------------------------------------------------------------------------
// Header bit I/O helpers.
// class for reading small header.
class HeaderDec {
public:
HeaderDec(const uint8_t* const buf, size_t size)
: buf_(buf), max_pos_(8 * size), bit_pos_(0), error_(false) {}
// Read next bits. 'nb_bits' must be in range [1, 24].
uint32_t ReadBits(int nb_bits, WP2_OPT_LABEL) {
const uint32_t value = ReadBitsInternal(nb_bits);
WP2Trace("%s: value=%u nb_bits=%d", debug_prefix_, label, value, nb_bits);
return value;
}
// Reads a signed value in [-2^(nb_bits-1):2^(nb_bits-1)-1].
int32_t ReadSBits(int nb_bits, WP2_OPT_LABEL) {
const uint32_t value = ReadBitsInternal(nb_bits);
WP2Trace("%s: value=%u nb_bits=%d", debug_prefix_, label, value, nb_bits);
return (int32_t)value - (1 << (nb_bits - 1));
}
// Returns the number of bytes read so far.
size_t Used() const { return (bit_pos_ + 7) >> 3; }
// Should be checked before using the above methods.
bool Ok() const { return !error_; }
// Set the prefix that will appear when adding bits.
void SetDebugPrefix(const char prefix[]) {
#if defined(WP2_BITTRACE) || defined(WP2_TRACE) || defined(WP2_ENC_DEC_MATCH)
debug_prefix_ = prefix;
#else
(void)prefix;
#endif
}
private:
uint32_t ReadBitsInternal(int nb_bits); // internal
const uint8_t* buf_;
size_t max_pos_;
size_t bit_pos_;
bool error_;
#if defined(WP2_BITTRACE) || defined(WP2_TRACE) || defined(WP2_ENC_DEC_MATCH)
std::string debug_prefix_;
#endif
};
// class for writing small header
class HeaderEnc {
public:
HeaderEnc(uint8_t* buf, size_t size)
: buf_(buf), max_pos_(size * 8), bit_pos_(0), error_(false) {
memset(buf, 0, size);
}
// Write next bits. 'nb_bits' must be in range [1, 24].
void PutBits(uint32_t value, int nb_bits, WP2_OPT_LABEL) {
WP2Trace("%s: value=%u nb_bits=%d", debug_prefix_, label, value, nb_bits);
PutBitsInternal(value, nb_bits);
}
// Writes a signed 'value' in [-2^(nb_bits-1):2^(nb_bits-1)-1].
void PutSBits(int32_t value, int nb_bits, WP2_OPT_LABEL) {
assert(value >= -(1 << (nb_bits - 1)));
PutBits((uint32_t)(value + (1 << (nb_bits - 1))), nb_bits, label);
}
// Finish the bitstream by aligning the bitstream position.
uint8_t* Align() {
bit_pos_ = (bit_pos_ + 7) & ~7;
return buf_ + (bit_pos_ >> 3);
}
// Size used so far, in bytes.
size_t Used() const { return (bit_pos_ + 7) >> 3; }
// Should be checked before using the above methods.
bool Ok() const { return !error_; }
// Set the prefix that will appear when adding bits.
void SetDebugPrefix(const char prefix[]) {
#if defined(WP2_BITTRACE) || defined(WP2_TRACE) || defined(WP2_ENC_DEC_MATCH)
debug_prefix_ = prefix;
#else
(void)prefix;
#endif
}
private:
void PutBitsInternal(uint32_t value, int nb_bits); // internal
uint8_t* buf_;
size_t max_pos_;
size_t bit_pos_;
bool error_;
#if defined(WP2_BITTRACE) || defined(WP2_TRACE) || defined(WP2_ENC_DEC_MATCH)
std::string debug_prefix_;
#endif
};
//------------------------------------------------------------------------------
// ANS quantizations.
// Scale the counts to fit in max_bits and replace them with the nearest powers
// of 2. If cost is not null, set it to the cost of encoding the original
// counts using the quantized counts (same as calling
// ANSCountsQuantizedCost(counts, out, size)).
void ANSCountsQuantizeHuffman(uint32_t size,
const uint32_t* const counts,
uint32_t* const out,
uint32_t max_bits,
float* const cost);
// Quantize the counts to be at most max_freq. Non-null values stay non-null.
// Returns true if the array is modified
// If do_expand is set to true, the counts can increase if the current
// max is inferior to max_freq.
// 'cost' is the cost of storing the data with quantized probabilities. A
// nullptr can be passed.
// The function exists as inplace or with a pre-allocated 'out' buffer.
bool ANSCountsQuantize(bool do_expand, uint32_t max_freq, uint32_t size,
uint32_t* const counts, float* const cost);
bool ANSCountsQuantize(bool do_expand, uint32_t max_freq, uint32_t size,
const uint32_t* const counts, uint32_t* const out,
float* const cost);
// Given an original set of symbol counts, and some distribution (e.g
// a quantized version of counts), output the bit cost of the symbols when
// using this distribution.
float ANSCountsQuantizedCost(const uint32_t* counts,
const uint32_t* distribution, uint32_t size);
//------------------------------------------------------------------------------
// ANS vector storage.
// Helper function for the function below.
struct OptimizeArrayStorageStat {
uint32_t count;
uint8_t n_bits;
};
// define to have a fast, but slightly less efficient OptimizeArrayStorage.
#define OPTIMIZE_ARRAY_STORAGE 1
void OptimizeArrayStorage(OptimizeArrayStorageStat* const stats,
size_t* const size, float overhead);
// Return the index of the highest set bit.
inline uint8_t FindLastSet(uint32_t val) {
return (val == 0) ? 0 : (1 + WP2Log2Floor(val));
}
// This function efficiently stores a vector of values by splitting it into
// groups of numbers of similar bit size.
// val_upper is an upper bound (potentially the max) of the input values.
// The size of the array and this 'val_upper' must be stored independently.
// If no ANS encoder is provided (enc == nullptr), the function can still be
// used to estimate the resulting size in bits.
// It stores the array with tuples (number of bits, number of numbers with that
// bit-size, a list of numbers).
// 'stats' is a pre-allocated buffer of the same size that will be used for
// temporary computation.
template <typename T>
float StoreVector(const T* const vals, uint32_t size, uint32_t val_upper,
OptimizeArrayStorageStat* stats, ANSEncBase* enc) {
return StoreVectorImpl(vals, size,
/*nnz=*/std::numeric_limits<uint32_t>::max(),
val_upper, stats, enc);
}
// Same as StoreVector except that we know the number 'nnz' of
// non-zero values as well as the fact that the last element is non-zero.
template <typename T>
float StoreVectorNnz(const T* const vals, uint32_t size, uint32_t nnz,
uint32_t val_upper, OptimizeArrayStorageStat* stats,
ANSEncBase* enc) {
// Check the number of non-zero elements is correct.
assert(std::count(vals, vals + size, 0) + nnz == size);
return StoreVectorImpl(vals, size, nnz, val_upper, stats, enc);
}
// Implementation of StoreVector and StoreVectorNnz.
// If nnz is std::numeric_limits<uint32_t>::max(), the number of non-zero
// elements is not used.
template <typename T>
float StoreVectorImpl(const T* const vals, uint32_t size, uint32_t nnz,
uint32_t val_upper, OptimizeArrayStorageStat* stats,
ANSEncBase* enc) {
const bool use_nnz = (nnz != std::numeric_limits<uint32_t>::max());
if (use_nnz) assert(size > 0 && vals[size - 1] != 0);
if (size == 0 || val_upper == 0 || nnz == 0) return 0.f;
WP2MathInit(); // Initialization for WP2Log2.
if (size <= 2) {
// For 2 values, storing as ranges is usually more efficient because of the
// overhead that describes the data.
if (enc != nullptr) {
uint32_t nnz_left = nnz;
for (uint32_t i = 0; i < size && nnz_left > 0; ++i) {
enc->PutRange(vals[i], i + nnz_left == size ? 1 : 0, val_upper,
"value");
if (vals[i] != 0) --nnz_left;
}
}
return size * WP2Log2(val_upper + 1);
}
// Stats contains a list of pairs: number of bits, numbers of consecutive
// values with that bit depth.
size_t stats_size = 0;
T val_max = 0, val_min = 0;
uint32_t nnz_left = nnz;
for (size_t i = 0; i < size; ++i) {
// If only non-zero elements remain, store them with -1.
const T val = (i + nnz_left == size) ? vals[i] - 1 : vals[i];
assert(val <= val_upper);
// Check if the highest set bit is the same (faster than calling
// FindLastSet).
if (val < val_max && val >= val_min) {
++stats[stats_size - 1].count;
} else {
stats[stats_size].count = 1;
stats[stats_size].n_bits = FindLastSet(val);
val_max = (1u << stats[stats_size].n_bits);
val_min = (val_max >> 1);
++stats_size;
}
if (vals[i] != 0) --nnz_left;
}
// Merge the pairs to give an optimal cost.
const uint8_t n_bits_max = FindLastSet(val_upper);
const float cost0 = WP2Log2Fast(n_bits_max);
const float cost1 = WP2Log2Fast(n_bits_max + 1);
OptimizeArrayStorage(stats, &stats_size, cost0 + WP2Log2(size + 1));
// Figure out the cost of this storage.
float cost = cost1;
size_t size_left = size;
uint8_t n_bits_max_in_val = 0;
for (size_t i = 0; i < stats_size; ++i) {
const OptimizeArrayStorageStat& s = stats[i];
assert(s.count > 0);
if (i > 0) cost += cost0;
// Add the costs: number of elements + each element.
float cost_per_value;
if (s.n_bits == n_bits_max && n_bits_max <= kANSMaxRangeBits) {
cost_per_value =
WP2Log2(val_upper + 1 - (s.count == 1 ? 1 << (n_bits_max - 1) : 0));
} else {
cost_per_value = s.n_bits - (s.count == 1 ? 1 : 0);
}
cost += WP2Log2(size_left) + s.count * cost_per_value;
size_left -= s.count;
n_bits_max_in_val = std::max(n_bits_max_in_val, s.n_bits);
}
// Compute the cost if all values are set to the same bit depth and choose it
// accordingly.
const float cost_same_depth = cost1 + size * n_bits_max_in_val;
const bool have_same_depth = (cost_same_depth < cost);
if (have_same_depth) {
cost = cost_same_depth;
stats_size = 1;
stats->count = size;
stats->n_bits = n_bits_max_in_val;
}
// Add the cost for the same depth bit.
cost += 1;
if (enc == nullptr) return cost;
enc->PutBool(have_same_depth, "has_same_depth");
// Store the optimized version of the array.
const T* v = vals;
uint8_t n_bits_prev = 0;
size_left = size;
nnz_left = nnz;
for (size_t i = 0; i < stats_size && nnz_left > 0; ++i) {
const OptimizeArrayStorageStat& s = stats[i];
// The number of bits is in [0:n_bits_max) for the first set.
if (v == vals) {
enc->PutRValue(s.n_bits, n_bits_max + 1, "n_bits");
} else {
// If we store n_bits0 for a set, the following n_bits1 will be stored as:
// n_bits1 if n_bits1 < n_bits0,
// n_bits1 - 1 otherwise.
if (s.n_bits < n_bits_prev) {
enc->PutRValue(s.n_bits, n_bits_max, "n_bits");
} else {
enc->PutRValue(s.n_bits - 1, n_bits_max, "n_bits");
}
}
n_bits_prev = s.n_bits;
// Store the number of values.
if (!have_same_depth) enc->PutRange(s.count, 1, size_left, "count");
// Whether to write the values as RValue or UValue.
const bool use_r_value =
(s.n_bits == n_bits_max) && (n_bits_max <= kANSMaxRangeBits);
if (s.n_bits == 0) {
v += s.count;
size_left -= s.count;
// If we have more nnz_left than elements after this segment, the last 0s
// were actually elements reduced by 1.
if (use_nnz && nnz_left >= size_left) nnz_left = size_left;
} else if (s.count == 1) {
// If we only have one number, we don't need to store the high order
// bit as it's always 1, otherwise it would fit in (n_bits_ - 1).
// And if that number is only on one bit to begin with, we don't need
// to store anything.
if (s.n_bits > 1) {
const uint32_t high_order_bit = 1u << (s.n_bits - 1);
const bool subtract_one = (size_left == nnz_left);
const uint32_t value_to_code =
(subtract_one ? *v - 1 : *v) ^ high_order_bit;
if (use_r_value) {
enc->PutRValue(value_to_code,
subtract_one ? val_upper - high_order_bit
: val_upper + 1 - high_order_bit,
"value");
} else {
enc->PutUValue(value_to_code, s.n_bits - 1, "value");
}
}
if (*v != 0) --nnz_left;
--size_left;
++v;
} else {
// Store the values.
for (size_t j = 0; j < s.count && nnz_left > 0; ++j, --size_left, ++v) {
// Use the fact that the last element is non-zero.
if (nnz_left == 1 && size_left > 1) {
assert(*v == 0);
continue;
}
const bool subtract_one = (size_left == nnz_left);
if (use_r_value) {
if (subtract_one) {
enc->PutRValue(*v - 1, val_upper, "value");
} else {
enc->PutRValue(*v, val_upper + 1, "value");
}
} else {
enc->PutUValue(subtract_one ? *v - 1 : *v, s.n_bits, "value");
}
if (*v != 0) --nnz_left;
}
}
}
assert(size_left == 0);
if (use_nnz) assert(nnz_left == 0);
return cost;
}
// Reciprocal of the function above to read a stored vector.
// 'val_upper' is the *inclusive* upper bound expected for the vector's values.
// The vector must be pre-allocated (with length 'size').
template <typename T>
void ReadVector(ANSDec* dec, uint32_t val_upper, T& v) {
ReadVectorImpl(dec, /*nnz=*/std::numeric_limits<uint32_t>::max(), val_upper,
v);
}
// Same as above except we are also given the maximum number of non-zero values
// and we know the last element is non-zero.
template <typename T>
void ReadVectorNnz(ANSDec* dec, uint32_t nnz, uint32_t val_upper, T& v) {
ReadVectorImpl(dec, nnz, val_upper, v);
}
template <typename T>
void ReadVectorImpl(ANSDec* dec, size_t nnz, uint32_t val_upper, T& v) {
uint32_t size = v.size();
if (size == 0) return;
if (val_upper == 0 || nnz == 0) {
if (size > 0) std::fill(&v[0], &v[size], 0);
return;
}
if (size <= 2) {
uint32_t i = 0;
for (; i < size && nnz > 0; ++i) {
v[i] = dec->ReadRange(i + nnz == size ? 1 : 0, val_upper, "value");
if (v[i] > 0) --nnz;
}
std::fill(&v[i], &v[size], 0);
return;
}
const uint8_t n_bits_max = FindLastSet(val_upper);
size_t k = 0;
int n_bits_prev = -1;
const bool have_same_depth = dec->ReadBool("has_same_depth");
const bool use_nnz = (nnz != std::numeric_limits<uint32_t>::max());
while (size > 0 && nnz > 0) {
// Figure out the number of bits.
uint32_t n_bits;
if (n_bits_prev < 0) {
// The first time, we have to use the full range of bits.
n_bits = dec->ReadRValue(n_bits_max + 1, "n_bits");
} else {
// The following time, we save one unit as we know the value has to be
// different from before.
n_bits = dec->ReadRValue(n_bits_max, "n_bits");
if ((int)n_bits >= n_bits_prev) ++n_bits;
}
n_bits_prev = (int)n_bits;
// Figure out the number of elements with that bit depth.
const uint32_t n =
(have_same_depth) ? size : dec->ReadRange(1, size, "count");
// Whether to read the values as RValue or UValue.
const bool use_r_value =
(n_bits == n_bits_max) && (n_bits_max <= kANSMaxRangeBits);
if (n_bits == 0) {
// For a depth of 0 bits, we know it is a 0.
for (size_t i = 0; i < n; ++i) v[k++] = 0;
assert(size >= n);
size -= n;
// If we have more nnz_left than elements after this segment, the last 0s
// were actually elements reduced by 1.
if (use_nnz && nnz >= size) {
for (uint32_t i = k - (nnz - size); i < k; ++i) ++v[i];
nnz = size;
}
} else if (n == 1) {
// If we only have one number, we didn't store the high order
// bit as it's always 1, otherwise it would fit in (n_bits_ - 1).
uint32_t value;
const bool is_nz_for_sure = (size == nnz);
if (n_bits == 1) {
// And if that number is only on one bit to begin with, we didn't
// store anything.
value = 1u;
} else {
value = 1u << (n_bits - 1);
if (use_r_value) {
value |= dec->ReadRValue(
is_nz_for_sure ? val_upper - value : val_upper + 1 - value,
"value");
} else {
value |= dec->ReadUValue(n_bits - 1, "value");
}
}
v[k] = is_nz_for_sure ? value + 1 : value;
if (v[k] != 0) --nnz;
++k;
assert(size >= 1);
size -= 1;
} else {
for (size_t i = 0; i < n && nnz > 0;
++i, ++k, assert(size >= 1), --size) {
// Use the fact that the last element is non-zero.
if (nnz == 1 && size > 1) {
v[k] = 0;
continue;
}
const bool is_nz_for_sure = (size == nnz);
if (use_r_value) {
v[k] = dec->ReadRValue(is_nz_for_sure ? val_upper : val_upper + 1,
"value");
} else {
v[k] = dec->ReadUValue(n_bits, "value");
}
if (is_nz_for_sure) ++v[k];
if (v[k] > 0) --nnz;
}
}
}
std::fill(&v[k], v.end(), 0);
}
//------------------------------------------------------------------------------
// ANSEncCounter
// ANSEncCounter behaves like an ANSEnc but does not store anything.
// Its only goal is to keep track of the cost of what its ANSEnc counterpart
// will store. It is useful to test the cost of an ANSEnc without dealing with
// all the token logic.
class ANSEncCounter : public ANSEncBase {
public:
ANSEncCounter() : cost_(0.), symbol_cost_(0.) {}
uint32_t PutBit(uint32_t bit, uint32_t proba, WP2_OPT_LABEL) override;
uint32_t PutABit(uint32_t bit, ANSBinSymbol* const stats,
WP2_OPT_LABEL) override;
uint32_t PutSymbol(uint32_t symbol, const ANSDictionary& dict,
WP2_OPT_LABEL) override;
uint32_t PutSymbol(uint32_t symbol, const ANSAdaptiveSymbol& asym,
WP2_OPT_LABEL) override;
uint32_t PutSymbol(uint32_t symbol, uint32_t max_symbol,
const ANSDictionary& dict, WP2_OPT_LABEL) override;
uint32_t PutSymbol(uint32_t symbol, uint32_t max_symbol,
const ANSAdaptiveSymbol& asym, WP2_OPT_LABEL) override;
uint32_t PutUValue(uint32_t value, uint32_t bits, WP2_OPT_LABEL) override;
uint32_t PutRValue(uint32_t value, uint32_t range, WP2_OPT_LABEL) override;
// Returns the total cost in bits. Cost of symbols is the cost based on
// dictionary stats at time of writing.
float GetCost() const override;
// Returns the total cost. Cost of symbols is taken from the provided
// dictionaries, and thus the result might be different from GetCost().
float GetCost(const ANSDictionaries& dicts) const override;
// The number of tokens is useless for a counter.
uint32_t NumTokens() const override { return 0; };
WP2Status GetStatus() const override { return WP2_STATUS_OK; }
WP2Status Append(const ANSEncCounter& enc);
// Resets costs to 0.
void Reset();
protected:
float cost_;
// Cost of symbols at time of writing.
float symbol_cost_;
};
// ANS encoder that does nothing! Useful when a function expects an ANS encoder
// but we don't actually want to write to the bistream.
class ANSEncNoop : public ANSEncBase {
public:
ANSEncNoop() = default;
uint32_t PutBit(uint32_t bit, uint32_t proba, WP2_OPT_LABEL) override {
return bit;
}
uint32_t PutABit(uint32_t bit, ANSBinSymbol* const stats,
WP2_OPT_LABEL) override {
return bit;
}
uint32_t PutSymbol(uint32_t symbol, const ANSDictionary& dict,
WP2_OPT_LABEL) override {
return symbol;
}
uint32_t PutSymbol(uint32_t symbol, const ANSAdaptiveSymbol& asym,
WP2_OPT_LABEL) override {
return symbol;
}
uint32_t PutSymbol(uint32_t symbol, uint32_t max_symbol,
const ANSDictionary& dict, WP2_OPT_LABEL) override {
return symbol;
}
uint32_t PutSymbol(uint32_t symbol, uint32_t max_symbol,
const ANSAdaptiveSymbol& asym, WP2_OPT_LABEL) override {
return symbol;
}
uint32_t PutUValue(uint32_t value, uint32_t bits, WP2_OPT_LABEL) override {
return value;
}
uint32_t PutRValue(uint32_t value, uint32_t range, WP2_OPT_LABEL) override {
return value;
}
float GetCost() const override {
assert(false);
return 0;
}
float GetCost(const ANSDictionaries& dicts) const override {
assert(false);
return 0;
}
uint32_t NumTokens() const override {
assert(false);
return 0;
}
WP2Status GetStatus() const override { return WP2_STATUS_OK; }
};
//------------------------------------------------------------------------------
// Very simple utilities to store/load elements.
// Loads a mapping where all values are in the range [ 0, 'range' ).
// A mapping is such that value i is mapped to 'mapping'[i]. All values are
// strictly increasing and are in the range [ 0, 'range' ).
// 'mapping' is resized to 'size'.
WP2Status LoadMapping(ANSDec* const dec, uint32_t size, uint32_t range,
Vector_u16& mapping);
// Stores a mapping.
// 'stats' is the same as in StoreVector.
float StoreMapping(const uint16_t* const mapping, size_t size, uint32_t range,
OptimizeArrayStorageStat* const stats, ANSEncBase* enc);
//------------------------------------------------------------------------------
// Writes a value in [min, max] where the size of the interval can be larger
// than kANSMaxRange.
uint32_t PutLargeRange(uint32_t v, uint32_t min, uint32_t max,
ANSEncBase* const enc, WP2_OPT_LABEL);
// Reads a value written with PutLargeRange.
uint32_t ReadLargeRange(uint32_t min, uint32_t max, ANSDec* const dec,
WP2_OPT_LABEL);
//------------------------------------------------------------------------------
// Class that adds a debug prefix when it's instantiated and pop it in the
// destructor.
class ANSDebugPrefix {
public:
#if defined(WP2_BITTRACE) || defined(WP2_TRACE) || defined(WP2_ENC_DEC_MATCH)
ANSDebugPrefix(ANSEncBase* const enc, const char prefix[])
: enc_(enc), dec_(nullptr) {
if (enc_ != nullptr) enc_->AddDebugPrefix(prefix);
}
ANSDebugPrefix(ANSDec* const dec, const char prefix[])
: enc_(nullptr), dec_(dec) {
if (dec_ != nullptr) dec_->AddDebugPrefix(prefix);
}
~ANSDebugPrefix() {
if (enc_ != nullptr) {
enc_->PopDebugPrefix();
} else if (dec_ != nullptr) {
dec_->PopDebugPrefix();
}
}
private:
ANSEncBase* enc_;
ANSDec* dec_;
#else
ANSDebugPrefix(ANSEncBase* const enc, const char prefix[]) {
(void)enc;
(void)prefix;
}
ANSDebugPrefix(ANSDec* const dec, const char prefix[]) {
(void)dec;
(void)prefix;
}
#endif
};
} // namespace WP2
#endif // WP2_UTILS_ANS_UTILS_H_
| 36.144796 | 80 | 0.620013 | [
"vector"
] |
5b2670b9a7458368e3f2ddfc711c6a3820526a57 | 6,490 | c | C | src/survive_api.c | Groad/libsurvive | 1ed89a53c9170771d34c82a4fd9cedaf62b56efc | [
"MIT"
] | 1 | 2020-01-10T10:51:10.000Z | 2020-01-10T10:51:10.000Z | src/survive_api.c | Groad/libsurvive | 1ed89a53c9170771d34c82a4fd9cedaf62b56efc | [
"MIT"
] | null | null | null | src/survive_api.c | Groad/libsurvive | 1ed89a53c9170771d34c82a4fd9cedaf62b56efc | [
"MIT"
] | null | null | null | #include "survive_api.h"
#include "inttypes.h"
#include "os_generic.h"
#include "stdio.h"
#include "string.h"
#include "survive.h"
struct SurviveExternalObject {
SurvivePose pose;
};
struct SurviveSimpleObject {
struct SurviveSimpleContext *actx;
enum SurviveSimpleObject_type {
SurviveSimpleObject_LIGHTHOUSE,
SurviveSimpleObject_OBJECT,
SurviveSimpleObject_EXTERNAL
} type;
union {
int lighthouse;
struct SurviveObject *so;
struct SurviveExternalObject seo;
} data;
char name[32];
bool has_update;
};
struct SurviveSimpleContext {
SurviveContext* ctx;
bool running;
og_thread_t thread;
og_mutex_t poll_mutex;
size_t external_object_ct;
struct SurviveSimpleObject *external_objects;
size_t object_ct;
struct SurviveSimpleObject objects[];
};
SurviveSimpleObject *find_or_create_external(struct SurviveSimpleContext *actx, const char *name) {
for (int i = 0; i < actx->external_object_ct; i++) {
struct SurviveSimpleObject *so = &actx->external_objects[i];
if (strncmp(name, so->name, 32) == 0) {
return so;
}
}
actx->external_objects =
realloc(actx->external_objects, sizeof(struct SurviveSimpleObject) * (actx->external_object_ct + 1));
struct SurviveSimpleObject *so = &actx->external_objects[actx->external_object_ct++];
memset(so, 0, sizeof(struct SurviveSimpleObject));
so->type = SurviveSimpleObject_EXTERNAL;
so->actx = actx;
strncpy(so->name, name, 32);
return so;
}
static void external_pose_fn(SurviveContext *ctx, const char *name, const SurvivePose *pose) {
struct SurviveSimpleContext *actx = ctx->user_ptr;
OGLockMutex(actx->poll_mutex);
survive_default_external_pose_process(ctx, name, pose);
struct SurviveSimpleObject *so = find_or_create_external(actx, name);
so->has_update = true;
so->data.seo.pose = *pose;
OGUnlockMutex(actx->poll_mutex);
}
static void pose_fn(SurviveObject *so, uint32_t timecode, SurvivePose *pose) {
struct SurviveSimpleContext *actx = so->ctx->user_ptr;
OGLockMutex(actx->poll_mutex);
survive_default_raw_pose_process(so, timecode, pose);
intptr_t idx = (intptr_t)so->user_ptr;
actx->objects[idx].has_update = true;
OGUnlockMutex(actx->poll_mutex);
}
static void lh_fn(SurviveContext *ctx, uint8_t lighthouse, SurvivePose *lighthouse_pose,
SurvivePose *object_pose) {
struct SurviveSimpleContext *actx = ctx->user_ptr;
OGLockMutex(actx->poll_mutex);
survive_default_lighthouse_pose_process(ctx, lighthouse, lighthouse_pose, object_pose);
actx->objects[lighthouse].has_update = true;
OGUnlockMutex(actx->poll_mutex);
}
struct SurviveSimpleContext *survive_simple_init(int argc, char *const *argv) {
SurviveContext* ctx = survive_init(argc, argv);
if (ctx == 0)
return 0;
survive_startup(ctx);
int object_ct = ctx->activeLighthouses + ctx->objs_ct;
struct SurviveSimpleContext *actx =
calloc(1, sizeof(struct SurviveSimpleContext) + sizeof(struct SurviveSimpleObject) * object_ct);
actx->object_ct = object_ct;
actx->ctx = ctx;
actx->poll_mutex = OGCreateMutex();
ctx->user_ptr = actx;
intptr_t i = 0;
for (i = 0; i < ctx->activeLighthouses; i++) {
struct SurviveSimpleObject *obj = &actx->objects[i];
obj->data.lighthouse = i;
obj->type = SurviveSimpleObject_LIGHTHOUSE;
obj->actx = actx;
obj->has_update = ctx->bsd[i].PositionSet;
snprintf(obj->name, 32, "LH%" PRIdPTR, i);
}
for (; i < object_ct; i++) {
struct SurviveSimpleObject *obj = &actx->objects[i];
int so_idx = i - ctx->activeLighthouses;
obj->data.so = ctx->objs[so_idx];
obj->type = SurviveSimpleObject_OBJECT;
obj->actx = actx;
obj->data.so->user_ptr = (void*)i;
snprintf(obj->name, 32, "%s", obj->data.so->codename);
}
survive_install_pose_fn(ctx, pose_fn);
survive_install_external_pose_fn(ctx, external_pose_fn);
survive_install_external_pose_fn(ctx, external_pose_fn);
survive_install_lighthouse_pose_fn(ctx, lh_fn);
return actx;
}
int survive_simple_stop_thread(struct SurviveSimpleContext *actx) {
actx->running = false;
intptr_t error = (intptr_t)OGJoinThread(actx->thread);
if (error != 0) {
SurviveContext *ctx = actx->ctx;
SV_INFO("Warning: Loop exited with error %" PRIdPTR, error);
}
return error;
}
void survive_simple_close(struct SurviveSimpleContext *actx) {
if (actx->running) {
survive_simple_stop_thread(actx);
}
survive_close(actx->ctx);
}
static inline void *__simple_thread(void *_actx) {
struct SurviveSimpleContext *actx = _actx;
intptr_t error = 0;
while (actx->running && error == 0) {
error = survive_poll(actx->ctx);
}
actx->running = false;
return (void*)error;
}
bool survive_simple_is_running(struct SurviveSimpleContext *actx) { return actx->running; }
void survive_simple_start_thread(struct SurviveSimpleContext *actx) {
actx->running = true;
actx->thread = OGCreateThread(__simple_thread, actx);
}
const struct SurviveSimpleObject *survive_simple_get_next_object(struct SurviveSimpleContext *actx,
const struct SurviveSimpleObject *curr) {
const struct SurviveSimpleObject *next = curr + 1;
if (next >= actx->objects + actx->object_ct)
return 0;
return next;
}
const struct SurviveSimpleObject *survive_simple_get_first_object(struct SurviveSimpleContext *actx) {
return actx->objects;
}
const struct SurviveSimpleObject *survive_simple_get_next_updated(struct SurviveSimpleContext *actx) {
for (int i = 0; i < actx->object_ct; i++) {
if (actx->objects[i].has_update) {
actx->objects[i].has_update = false;
return &actx->objects[i];
}
}
for (int i = 0; i < actx->external_object_ct; i++) {
if (actx->external_objects[i].has_update) {
actx->external_objects[i].has_update = false;
return &actx->external_objects[i];
}
}
return 0;
}
uint32_t survive_simple_object_get_latest_pose(const struct SurviveSimpleObject *sao, SurvivePose *pose) {
uint32_t timecode = 0;
OGLockMutex(sao->actx->poll_mutex);
switch (sao->type) {
case SurviveSimpleObject_LIGHTHOUSE: {
if (pose)
*pose = sao->actx->ctx->bsd[sao->data.lighthouse].Pose;
break;
}
case SurviveSimpleObject_OBJECT:
if (pose)
*pose = sao->data.so->OutPose;
timecode = sao->data.so->OutPose_timecode;
break;
case SurviveSimpleObject_EXTERNAL:
if (pose)
*pose = sao->data.seo.pose;
break;
default: {
SurviveContext *ctx = sao->actx->ctx;
SV_ERROR("Invalid object type %d", sao->type);
}
}
OGUnlockMutex(sao->actx->poll_mutex);
return timecode;
}
const char *survive_simple_object_name(const SurviveSimpleObject *sao) { return sao->name; }
| 28.844444 | 106 | 0.740216 | [
"object"
] |
5b2c7b81d97668370ab3c7d895de692a79a40918 | 5,262 | h | C | torch/csrc/utils/throughput_benchmark-inl.h | magictiger/pytorch | eb71f7d93145379db4b3b2006065559ac46df344 | [
"Intel"
] | 3 | 2021-06-11T11:33:40.000Z | 2021-08-22T14:54:34.000Z | torch/csrc/utils/throughput_benchmark-inl.h | magictiger/pytorch | eb71f7d93145379db4b3b2006065559ac46df344 | [
"Intel"
] | null | null | null | torch/csrc/utils/throughput_benchmark-inl.h | magictiger/pytorch | eb71f7d93145379db4b3b2006065559ac46df344 | [
"Intel"
] | 1 | 2021-12-26T23:20:06.000Z | 2021-12-26T23:20:06.000Z | #pragma once
#include <random>
#include <thread>
#include <torch/csrc/autograd/profiler.h>
#include <torch/csrc/jit/python/pybind_utils.h>
#include <torch/csrc/utils/pybind.h>
#include <aten/src/ATen/Parallel.h>
#include <c10/util/irange.h>
namespace torch {
namespace throughput_benchmark {
namespace detail {
template <class Input, class Output, class Model>
BenchmarkExecutionStats BenchmarkHelper<Input, Output, Model>::benchmark(
const BenchmarkConfig& config) const {
CHECK(initialized_);
TORCH_CHECK(
config.num_worker_threads == 1,
"Only parallelization by callers is supported");
LOG(INFO) << at::get_parallel_info();
// We pre-generate inputs here for each of the threads. This allows us to
// safely move inputs out for each of the threads independently and thus avoid
// overhead from the benchmark runner itself
std::vector<std::vector<Input>> thread_inputs(config.num_calling_threads);
std::vector<size_t> input_iters(config.num_calling_threads);
{
std::random_device seeder;
std::mt19937 engine(seeder());
TORCH_CHECK(
!inputs_.empty(),
"Please provide benchmark inputs."
"Did you forget to call add_input()? ");
std::uniform_int_distribution<int> dist(0, inputs_.size() - 1);
for (const auto thread_id : c10::irange(config.num_calling_threads)) {
// Just in case we generate num_iters inputs for each of the threads
// This was if one thread does all the work we will be fine
for (int i = 0; i < config.num_iters + config.num_warmup_iters; ++i) {
thread_inputs[thread_id].push_back(cloneInput(inputs_[dist(engine)]));
}
input_iters[thread_id] = 0;
}
}
std::mutex m;
std::condition_variable worker_main_cv;
std::condition_variable main_worker_cv;
// TODO: add GUARDED_BY once it is available
int64_t initialized{0};
int64_t finished{0};
bool start{false};
std::atomic<int64_t> num_attempted_iters{0};
std::vector<std::thread> callers;
for (const auto thread_id : c10::irange(config.num_calling_threads)) {
// NOLINTNEXTLINE(performance-inefficient-vector-operation)
callers.emplace_back([&, thread_id]() {
// We use conditional variable as a barrier to make sure each thread
// performs required warmeup iterations before we start measuring
for (const auto j : c10::irange(config.num_warmup_iters)) {
runOnce(std::move(thread_inputs[thread_id][input_iters[thread_id]]));
++input_iters[thread_id];
}
{
std::unique_lock<std::mutex> lock(m);
++initialized;
worker_main_cv.notify_one();
// NOLINTNEXTLINE(bugprone-infinite-loop)
while (!start) {
main_worker_cv.wait(lock);
}
}
LOG(INFO) << "Starting forward thread " << thread_id;
while (num_attempted_iters.fetch_add(1) < config.num_iters) {
runOnce(std::move(thread_inputs[thread_id][input_iters[thread_id]]));
++input_iters[thread_id];
}
{
std::unique_lock<std::mutex> lock(m);
++finished;
worker_main_cv.notify_one();
LOG(INFO) << "Shutting down forward thread " << thread_id
<< ". Total number of finished threads: " << finished;
}
});
}
using Clock = std::chrono::high_resolution_clock;
using TimePoint = std::chrono::time_point<Clock>;
TimePoint start_time;
std::unique_ptr<torch::autograd::profiler::RecordProfile> profiler_guard;
{
std::unique_lock<std::mutex> lock(m);
while (initialized != config.num_calling_threads) {
worker_main_cv.wait(lock);
}
if (!config.profiler_output_path.empty()) {
LOG(INFO) << "Using Autograd profiler. Trace will be saved to "
<< config.profiler_output_path;
// NOLINTNEXTLINE(modernize-make-unique)
profiler_guard.reset(new torch::autograd::profiler::RecordProfile(
config.profiler_output_path));
}
LOG(INFO) << "Starting threads";
start = true;
start_time = Clock::now();
}
main_worker_cv.notify_all();
{
std::unique_lock<std::mutex> lock(m);
worker_main_cv.wait(
lock, [&]() { return finished == config.num_calling_threads; });
}
auto end_time = std::chrono::high_resolution_clock::now();
profiler_guard.reset();
LOG(INFO) << "Finished benchmark";
BenchmarkExecutionStats stats;
// NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
float total_time_ms = std::chrono::duration_cast<std::chrono::nanoseconds>(
end_time - start_time)
.count() /
1000.0 / 1000.0;
// We use config.num_iters instead of num_attempted_iters as it is
// repsesatative of the real work done. Last attempted iteration on each
// calling threads doesn't represent the real work (i.e. running the model)
stats.latency_avg_ms =
// NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
total_time_ms * config.num_calling_threads / config.num_iters;
stats.num_iters = config.num_iters;
for (auto& t : callers) {
t.join();
}
return stats;
}
} // namespace detail
} // namespace throughput_benchmark
} // namespace torch
| 34.847682 | 95 | 0.679209 | [
"vector",
"model"
] |
5b2cd76488c1829f230d48cfbf0ae2c839b0c921 | 12,541 | h | C | src/kudu/common/key_encoder.h | shirodkara/kudu | 1e39599b458c57c4016fc28680f2579d6472ce0b | [
"Apache-2.0"
] | 6 | 2020-05-12T02:18:48.000Z | 2021-04-15T20:39:21.000Z | src/kudu/common/key_encoder.h | shirodkara/kudu | 1e39599b458c57c4016fc28680f2579d6472ce0b | [
"Apache-2.0"
] | 1 | 2021-02-23T19:20:32.000Z | 2021-02-24T08:41:41.000Z | src/kudu/common/key_encoder.h | shirodkara/kudu | 1e39599b458c57c4016fc28680f2579d6472ce0b | [
"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.
#ifndef KUDU_COMMON_KEYENCODER_H
#define KUDU_COMMON_KEYENCODER_H
#include <emmintrin.h>
#include <smmintrin.h>
#include <climits>
#include <cstdint>
#include <cstring>
#include <ostream>
#include <glog/logging.h>
#include "kudu/common/common.pb.h"
#include "kudu/common/types.h"
#include "kudu/gutil/endian.h"
#include "kudu/gutil/macros.h"
#include "kudu/gutil/mathlimits.h"
#include "kudu/gutil/port.h"
#include "kudu/gutil/type_traits.h"
#include "kudu/util/logging.h"
#include "kudu/util/memory/arena.h"
#include "kudu/util/slice.h"
#include "kudu/util/status.h"
// The SSE-based encoding is not yet working. Don't define this!
#undef KEY_ENCODER_USE_SSE
namespace kudu {
template<DataType Type, typename Buffer, class Enable = void>
struct KeyEncoderTraits {
};
// This complicated-looking template magic defines a specialization of the
// KeyEncoderTraits struct for any integral type. This avoids a bunch of
// code duplication for all of our different size/signed-ness variants.
template<DataType Type, typename Buffer>
struct KeyEncoderTraits<Type,
Buffer,
typename base::enable_if<
base::is_integral<
typename DataTypeTraits<Type>::cpp_type
>::value
>::type
> {
private:
typedef typename DataTypeTraits<Type>::cpp_type cpp_type;
typedef typename MathLimits<cpp_type>::UnsignedType unsigned_cpp_type;
static unsigned_cpp_type SwapEndian(unsigned_cpp_type x) {
switch (sizeof(x)) {
case 1: return x;
case 2: return BigEndian::FromHost16(x);
case 4: return BigEndian::FromHost32(x);
case 8: return BigEndian::FromHost64(x);
case 16: return BigEndian::FromHost128(x);
default: LOG(FATAL) << "bad type size of: " << sizeof(x);
}
return 0;
}
public:
static void Encode(cpp_type key, Buffer* dst) {
Encode(&key, dst);
}
static void Encode(const void* key_ptr, Buffer* dst) {
unsigned_cpp_type key_unsigned;
memcpy(&key_unsigned, key_ptr, sizeof(key_unsigned));
// To encode signed integers, swap the MSB.
if (MathLimits<cpp_type>::kIsSigned) {
key_unsigned ^= static_cast<unsigned_cpp_type>(1) << (sizeof(key_unsigned) * CHAR_BIT - 1);
}
key_unsigned = SwapEndian(key_unsigned);
dst->append(reinterpret_cast<const char*>(&key_unsigned), sizeof(key_unsigned));
}
static void EncodeWithSeparators(const void* key, bool is_last, Buffer* dst) {
Encode(key, dst);
}
static Status DecodeKeyPortion(Slice* encoded_key,
bool /*is_last*/,
Arena* /*arena*/,
uint8_t* cell_ptr) {
if (PREDICT_FALSE(encoded_key->size() < sizeof(cpp_type))) {
return Status::InvalidArgument("key too short", KUDU_REDACT(encoded_key->ToDebugString()));
}
unsigned_cpp_type val;
memcpy(&val, encoded_key->data(), sizeof(cpp_type));
val = SwapEndian(val);
if (MathLimits<cpp_type>::kIsSigned) {
val ^= static_cast<unsigned_cpp_type>(1) << (sizeof(val) * CHAR_BIT - 1);
}
memcpy(cell_ptr, &val, sizeof(val));
encoded_key->remove_prefix(sizeof(cpp_type));
return Status::OK();
}
};
template<typename Buffer>
struct KeyEncoderTraits<BINARY, Buffer> {
static void Encode(const void* key, Buffer* dst) {
Encode(*reinterpret_cast<const Slice*>(key), dst);
}
// simple slice encoding that just adds to the buffer
inline static void Encode(const Slice& s, Buffer* dst) {
dst->append(reinterpret_cast<const char*>(s.data()),s.size());
}
static void EncodeWithSeparators(const void* key, bool is_last, Buffer* dst) {
EncodeWithSeparators(*reinterpret_cast<const Slice*>(key), is_last, dst);
}
// slice encoding that uses a separator to retain lexicographic
// comparability.
//
// This implementation is heavily optimized for the case where the input
// slice has no '\0' bytes. We assume this is common in most user-generated
// compound keys.
inline static void EncodeWithSeparators(const Slice& s, bool is_last, Buffer* dst) {
if (is_last) {
dst->append(reinterpret_cast<const char*>(s.data()), s.size());
} else {
// If we're a middle component of a composite key, we need to add a \x00
// at the end in order to separate this component from the next one. However,
// if we just did that, we'd have issues where a key that actually has
// \x00 in it would compare wrong, so we have to instead add \x00\x00, and
// encode \x00 as \x00\x01.
int old_size = dst->size();
dst->resize(old_size + s.size() * 2 + 2);
const uint8_t* srcp = s.data();
uint8_t* dstp = reinterpret_cast<uint8_t*>(&(*dst)[old_size]);
int len = s.size();
int rem = len;
while (rem >= 16) {
if (!SSEEncodeChunk<16>(&srcp, &dstp)) {
goto slow_path;
}
rem -= 16;
}
while (rem >= 8) {
if (!SSEEncodeChunk<8>(&srcp, &dstp)) {
goto slow_path;
}
rem -= 8;
}
// Roll back to operate in 8 bytes at a time.
if (len > 8 && rem > 0) {
dstp -= 8 - rem;
srcp -= 8 - rem;
if (!SSEEncodeChunk<8>(&srcp, &dstp)) {
// TODO: optimize for the case where the input slice has '\0'
// bytes. (e.g. move the pointer to the first zero byte.)
dstp += 8 - rem;
srcp += 8 - rem;
goto slow_path;
}
rem = 0;
goto done;
}
slow_path:
EncodeChunkLoop(&srcp, &dstp, rem);
done:
*dstp++ = 0;
*dstp++ = 0;
dst->resize(dstp - reinterpret_cast<uint8_t*>(&(*dst)[0]));
}
}
static Status DecodeKeyPortion(Slice* encoded_key,
bool is_last,
Arena* arena,
uint8_t* cell_ptr) {
if (is_last) {
Slice* dst_slice = reinterpret_cast<Slice *>(cell_ptr);
if (PREDICT_FALSE(!arena->RelocateSlice(*encoded_key, dst_slice))) {
return Status::RuntimeError("OOM");
}
encoded_key->remove_prefix(encoded_key->size());
return Status::OK();
}
uint8_t* separator = static_cast<uint8_t*>(memmem(encoded_key->data(), encoded_key->size(),
"\0\0", 2));
if (PREDICT_FALSE(separator == NULL)) {
return Status::InvalidArgument("Missing separator after composite key string component",
KUDU_REDACT(encoded_key->ToDebugString()));
}
uint8_t* src = encoded_key->mutable_data();
int max_len = separator - src;
uint8_t* dst_start = static_cast<uint8_t*>(arena->AllocateBytes(max_len));
uint8_t* dst = dst_start;
for (int i = 0; i < max_len; i++) {
if (i >= 1 && src[i - 1] == '\0' && src[i] == '\1') {
continue;
}
*dst++ = src[i];
}
int real_len = dst - dst_start;
Slice slice(dst_start, real_len);
memcpy(cell_ptr, &slice, sizeof(Slice));
encoded_key->remove_prefix(max_len + 2);
return Status::OK();
}
private:
// Encode a chunk of 'len' bytes from '*srcp' into '*dstp', incrementing
// the pointers upon return.
//
// This uses SSE2 operations to operate in 8 or 16 bytes at a time, fast-pathing
// the case where there are no '\x00' bytes in the source.
//
// Returns true if the chunk was successfully processed, false if there was one
// or more '\0' bytes requiring the slow path.
//
// REQUIRES: len == 16 or 8
template<int LEN>
static bool SSEEncodeChunk(const uint8_t** srcp, uint8_t** dstp) {
COMPILE_ASSERT(LEN == 16 || LEN == 8, invalid_length);
__m128i data;
if (LEN == 16) {
// Load 16 bytes (unaligned) into the XMM register.
data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(*srcp));
} else if (LEN == 8) {
// Load 8 bytes (unaligned) into the XMM register
data = reinterpret_cast<__m128i>(_mm_load_sd(reinterpret_cast<const double*>(*srcp)));
}
// Compare each byte of the input with '\0'. This results in a vector
// where each byte is either \x00 or \xFF, depending on whether the
// input had a '\x00' in the corresponding position.
__m128i zeros = reinterpret_cast<__m128i>(_mm_setzero_pd());
__m128i zero_bytes = _mm_cmpeq_epi8(data, zeros);
// Check whether the resulting vector is all-zero.
bool all_zeros;
if (LEN == 16) {
all_zeros = _mm_testz_si128(zero_bytes, zero_bytes);
} else { // LEN == 8
all_zeros = _mm_cvtsi128_si64(zero_bytes) == 0;
}
// If it's all zero, we can just store the entire chunk.
if (PREDICT_FALSE(!all_zeros)) {
return false;
}
if (LEN == 16) {
_mm_storeu_si128(reinterpret_cast<__m128i*>(*dstp), data);
} else {
_mm_storel_epi64(reinterpret_cast<__m128i*>(*dstp), data); // movq m64, xmm
}
*dstp += LEN;
*srcp += LEN;
return true;
}
// Non-SSE loop which encodes 'len' bytes from 'srcp' into 'dst'.
static void EncodeChunkLoop(const uint8_t** srcp, uint8_t** dstp, int len) {
while (len--) {
if (PREDICT_FALSE(**srcp == '\0')) {
*(*dstp)++ = 0;
*(*dstp)++ = 1;
} else {
*(*dstp)++ = **srcp;
}
(*srcp)++;
}
}
};
// Forward declaration is necessary for friend declaration in KeyEncoder.
template<typename Buffer>
class EncoderResolver;
// The runtime version of the key encoder
template <typename Buffer>
class KeyEncoder {
public:
// Encodes the provided key to the provided buffer
void Encode(const void* key, Buffer* dst) const {
encode_func_(key, dst);
}
// Special encoding for composite keys.
void Encode(const void* key, bool is_last, Buffer* dst) const {
encode_with_separators_func_(key, is_last, dst);
}
void ResetAndEncode(const void* key, Buffer* dst) const {
dst->clear();
Encode(key, dst);
}
// Decode the next component out of the composite key pointed to by '*encoded_key'
// into *cell_ptr.
// After decoding encoded_key is advanced forward such that it contains the remainder
// of the composite key.
// 'is_last' should be true when we expect that this component is the last (or only) component
// of the composite key.
// Any indirect data (eg strings) are allocated out of 'arena'.
Status Decode(Slice* encoded_key,
bool is_last,
Arena* arena,
uint8_t* cell_ptr) const {
return decode_key_portion_func_(encoded_key, is_last, arena, cell_ptr);
}
private:
friend class EncoderResolver<Buffer>;
template<typename EncoderTraitsClass>
explicit KeyEncoder(EncoderTraitsClass t)
: encode_func_(EncoderTraitsClass::Encode),
encode_with_separators_func_(EncoderTraitsClass::EncodeWithSeparators),
decode_key_portion_func_(EncoderTraitsClass::DecodeKeyPortion) {
}
typedef void (*EncodeFunc)(const void* key, Buffer* dst);
const EncodeFunc encode_func_;
typedef void (*EncodeWithSeparatorsFunc)(const void* key, bool is_last, Buffer* dst);
const EncodeWithSeparatorsFunc encode_with_separators_func_;
typedef Status (*DecodeKeyPortionFunc)(Slice* enc_key, bool is_last,
Arena* arena, uint8_t* cell_ptr);
const DecodeKeyPortionFunc decode_key_portion_func_;
private:
DISALLOW_COPY_AND_ASSIGN(KeyEncoder);
};
template <typename Buffer>
extern const KeyEncoder<Buffer>& GetKeyEncoder(const TypeInfo* typeinfo);
extern const bool IsTypeAllowableInKey(const TypeInfo* typeinfo);
} // namespace kudu
#endif
| 34.171662 | 97 | 0.642054 | [
"vector"
] |
5b314bae82cecede78eac348b898ca15358f755d | 7,742 | h | C | Project_2/JSONParser.h | jplabadie/graphix | d5f856c66120c26ead5faa56aa501b9eb1b82488 | [
"MIT"
] | null | null | null | Project_2/JSONParser.h | jplabadie/graphix | d5f856c66120c26ead5faa56aa501b9eb1b82488 | [
"MIT"
] | null | null | null | Project_2/JSONParser.h | jplabadie/graphix | d5f856c66120c26ead5faa56aa501b9eb1b82488 | [
"MIT"
] | null | null | null | #ifndef _VECTOR_MATH_H_
#define _VECTOR_MATH_H_
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "VectorMath.h"
#include "RayTracer.h"
int line = 1;
const uint8_t INIT_NUM_OBJ = 64;
/**
* Wrapper for the getc() func, adds error checking and line-number maintainance
* @param json
* @return
*/
int nextC(FILE *json) {
int c = fgetc(json);
#ifdef DEBUG
printf("nextC: '%c'\n", c);
#endif
if (c == '\n') {
line += 1;
}
if (c == EOF) {
fprintf(stderr, "Error: Unexpected end of file on line number %d.\n", line);
exit(1);
}
return c;
}
/**
* Verifies that the next number is d, or throws an error and exits
*
* @param json
* @param d the next expected number
*/
void expectC(FILE *json, int d) {
int c = nextC(json);
if (c == d)
return;
fprintf(stderr, "Error: Expected '%c' on line %d.\n", d, line);
exit(1);
}
/**
* Skips all whitespace at the current position in the file
*
* @param json
*/
void skipWs(FILE *json) {
int c = nextC(json);
while (isspace(c)) {
c = nextC(json);
}
ungetc(c, json);
}
/**
* Returns the next numerical string from the file, or throws an error and exits
* @param json
* @return
*/
char *nextString(FILE *json) {
char buffer[129];
int c = nextC(json);
if (c != '"') {
fprintf(stderr, "Error: Expected string on line %d.\n", line);
exit(1);
}
c = nextC(json);
int i = 0;
while (c != '"') {
if (i >= 128) {
fprintf(stderr, "Error: Strings > 128 characters in length are not supported.\n");
exit(1);
}
if (c == '\\') {
fprintf(stderr, "Error: Strings containing escape codes are not supported.\n");
exit(1);
}
if (c < 32 || c > 126) {
fprintf(stderr, "Error: Strings containing non-ascii characters are not supported.\n");
exit(1);
}
buffer[i] = c;
i += 1;
c = nextC(json);
}
buffer[i] = 0;
return strdup(buffer);
}
/**
* Returns the next number encountered in the input file
* (no error checking implemented)
*
* @param json
* @return
*/
double nextNumber(FILE *json) {
double value;
fscanf(json, "%lf", &value);
//Todo: Error handling
return value;
}
/**
* Returns the next Vector value encountered in the input File
* (no error checking implemented)
*
* @param json
* @return
*/
double *nextVector(FILE *json) {
double *v = malloc(3 * sizeof(double));
expectC(json, '[');
skipWs(json);
v[0] = nextNumber(json);
skipWs(json);
expectC(json, ',');
skipWs(json);
v[1] = nextNumber(json);
skipWs(json);
expectC(json, ',');
skipWs(json);
v[2] = nextNumber(json);
skipWs(json);
expectC(json, ']');
return v;
//Todo: Error handling
}
/**
* Loads the scene from a given file into an object struct array as defined in tracer.h
*
* @param filename
* @return
*/
Object **readScene(char *filename) {
int c;
FILE *json = fopen(filename, "r");
if (json == NULL) {
fprintf(stderr, "Error: Could not open file \"%s\"\n", filename);
exit(1);
}
Object **objArray;
objArray = malloc(sizeof(Object *) * INIT_NUM_OBJ);
skipWs(json);
// Find the beginning of the list
expectC(json, '[');
skipWs(json);
size_t curr_obj = 0;
while (1) {
objArray[curr_obj] = malloc(sizeof(Object));
c = fgetc(json);
if (c == ']') {
fprintf(stderr, "Error: This is the worst scene file EVER.\n");
fclose(json);
return NULL;
}
if (c == '{') {
skipWs(json);
// Parse the object
char *key = nextString(json);
if (strcmp(key, "type") != 0) {
fprintf(stderr, "Error: Expected \"type\" key on line number %d.\n",
line);
exit(1);
}
skipWs(json);
expectC(json, ':');
skipWs(json);
char *value = nextString(json);
if (strcmp(value, "camera") == 0) {
objArray[curr_obj]->type = CAMERA;
} else if (strcmp(value, "sphere") == 0) {
objArray[curr_obj]->type = SPHERE;
} else if (strcmp(value, "plane") == 0) {
objArray[curr_obj]->type = PLANE;
} else {
fprintf(stderr, "Error: Unknown type, \"%s\", on line number %d.\n",
value, line);
exit(1);
}
skipWs(json);
while (1) {
c = nextC(json);
if (c == '}') {
// stop parsing this object
break;
} else if (c == ',') {
// read another field
skipWs(json);
char *key = nextString(json);
skipWs(json);
expectC(json, ':');
skipWs(json);
// scalar types
if (strcmp(key, "width") == 0) {
double value = nextNumber(json);
if (value < 0) {
fprintf(stderr, "Error: Width cannot be less than 0. Found %lf "
"on line number %d.\n",
value, line);
exit(1);
}
objArray[curr_obj]->Camera.width = value;
} else if (strcmp(key, "height") == 0) {
double value = nextNumber(json);
if (value < 0) {
fprintf(stderr, "Error: Height cannot be less than 0. Found %lf "
"on line number %d.\n",
value, line);
exit(1);
}
objArray[curr_obj]->Camera.height = value;
} else if (strcmp(key, "radius") == 0) {
double value = nextNumber(json);
if (value < 0) {
fprintf(stderr, "Error: Radius cannot be less than 0. Found %lf "
"on line number %d.\n",
value, line);
exit(1);
}
objArray[curr_obj]->Sphere.radius = value;
}
else if (strcmp(key, "color") == 0) {
double *value = nextVector(json);
objArray[curr_obj]->color.r = value[0];
if (value[0] < 0 || value[1] < 0 || value[2] < 0) {
fprintf(stderr, "Error: color values cannot be less than 0. "
"On line number %d.\n",
line);
exit(1);
}
objArray[curr_obj]->color.g = value[1];
objArray[curr_obj]->color.b = value[2];
} else if (strcmp(key, "position") == 0) {
double *value = nextVector(json);
if (objArray[curr_obj]->type == PLANE) {
vectorCopy(objArray[curr_obj]->Plane.position, value);
} else if (objArray[curr_obj]->type == SPHERE) {
vectorCopy(objArray[curr_obj]->Sphere.position, value);
} else {
fprintf(stderr, "Error: Unknown type, \"%d\", on line %d.\n",
objArray[curr_obj]->type, line);
exit(1);
}
} else if (strcmp(key, "normal") == 0) {
double *value = nextVector(json);
vectorCopy(objArray[curr_obj]->Plane.normal, value);
} else {
fprintf(stderr, "Error: Unknown property, \"%s\", on line %d.\n",
key, line);
exit(1);
}
skipWs(json);
} else {
fprintf(stderr, "Error: Unexpected value on line %d\n", line);
exit(1);
}
}
skipWs(json);
c = nextC(json);
if (c == ',') {
skipWs(json);
} else if (c == ']') {
fclose(json);
objArray[curr_obj + 1] = 0;
return objArray;
} else {
fprintf(stderr, "Error: Expecting ',' or ']' on line %d.\n", line);
exit(1);
}
}
curr_obj++;
}
}
#endif
| 25.136364 | 93 | 0.510592 | [
"object",
"vector"
] |
5b31d32149e201d0e05c3b9b5e26a3de7dae66b0 | 1,478 | c | C | tools-src/gnu/glibc/localedata/tests-mbwc/tst_mbrlen.c | enfoTek/tomato.linksys.e2000.nvram-mod | 2ce3a5217def49d6df7348522e2bfda702b56029 | [
"FSFAP"
] | 80 | 2015-01-02T10:14:04.000Z | 2021-06-07T06:29:49.000Z | tools-src/gnu/glibc/localedata/tests-mbwc/tst_mbrlen.c | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 9 | 2015-05-14T11:03:12.000Z | 2018-01-04T07:12:58.000Z | tools-src/gnu/glibc/localedata/tests-mbwc/tst_mbrlen.c | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 69 | 2015-01-02T10:45:56.000Z | 2021-09-06T07:52:13.000Z | /*
MBRLEN: size_t mbrlen (char *s, size_t n, mbstate_t *ps)
*/
#define TST_FUNCTION mbrlen
#include "tsp_common.c"
#include "dat_mbrlen.c"
int
tst_mbrlen (FILE * fp, int debug_flg)
{
TST_DECL_VARS (size_t);
char s_flg;
const char *s_in;
size_t n;
char t_flg;
char t_ini;
static mbstate_t s = { 0 };
mbstate_t *ps;
TST_DO_TEST (mbrlen)
{
TST_HEAD_LOCALE (mbrlen, S_MBRLEN);
TST_DO_REC (mbrlen)
{
if (mbrlen (NULL, 0, &s) != 0)
{
err_count++;
Result (C_FAILURE, S_MBRLEN, CASE_3,
"Initialization (external mbstate object) failed "
"- skipped this test case.");
continue;
}
TST_DO_SEQ (MBRLEN_SEQNUM)
{
TST_GET_ERRET_SEQ (mbrlen);
s_flg = TST_INPUT_SEQ (mbrlen).s_flg;
s_in = TST_INPUT_SEQ (mbrlen).s;
n = TST_INPUT_SEQ (mbrlen).n;
t_flg = TST_INPUT_SEQ (mbrlen).t_flg;
t_ini = TST_INPUT_SEQ (mbrlen).t_init;
if (s_flg == 0)
{
s_in = NULL;
}
if (n == USE_MBCURMAX) /* rewrite tst_mblen() like this */
{
n = MB_CUR_MAX;
}
ps = (t_flg == 0) ? NULL : &s;
if (t_ini != 0)
{
memset (&s, 0, sizeof (s));
mbrlen (NULL, 0, NULL);
}
TST_CLEAR_ERRNO;
ret = mbrlen (s_in, n, ps);
TST_SAVE_ERRNO;
if (debug_flg)
{
fprintf (stdout, "mbrlen() [ %s : %d : %d ] ret = %d\n",
locale, rec + 1, seq_num + 1, ret);
fprintf (stdout, " errno = %d\n", errno_save);
}
TST_IF_RETURN (S_MBRLEN)
{
};
}
}
}
return err_count;
}
| 17.807229 | 61 | 0.592016 | [
"object"
] |
5b367389c0966aa08bb9f0995b1d58d56193c7cf | 653 | h | C | src/util/object.h | mmig/zeromq.js | e2821f002eebec2428e83614d8b5309388c79342 | [
"MIT"
] | 1,180 | 2016-10-30T15:46:20.000Z | 2022-03-27T21:12:21.000Z | src/util/object.h | mmig/zeromq.js | e2821f002eebec2428e83614d8b5309388c79342 | [
"MIT"
] | 358 | 2016-10-29T17:12:17.000Z | 2022-03-25T15:18:30.000Z | src/util/object.h | mmig/zeromq.js | e2821f002eebec2428e83614d8b5309388c79342 | [
"MIT"
] | 205 | 2016-10-30T07:44:13.000Z | 2022-03-08T17:39:15.000Z | /* Copyright (c) 2017-2019 Rolf Timmermans */
#pragma once
namespace zmq {
/* Seals an object to prevent setting incorrect options. */
static inline void Seal(Napi::Object object) {
auto global = object.Env().Global();
auto seal = global.Get("Object").As<Napi::Object>().Get("seal").As<Napi::Function>();
seal.Call({object});
}
/* Assign all properties in the given options object. */
static inline void Assign(Napi::Object object, Napi::Object options) {
auto global = object.Env().Global();
auto assign =
global.Get("Object").As<Napi::Object>().Get("assign").As<Napi::Function>();
assign.Call({object, options});
}
}
| 32.65 | 89 | 0.666156 | [
"object"
] |
5b37ec6fcb0e1bd2c660ff2359ca640b96f11f0d | 1,093 | h | C | NoiseStudioLib/NoiseStudioLib/input_socket.h | SneakyMax/NoiseStudio | b0c3c72e787d61b798acbcd2147f36e1e78f5bad | [
"Unlicense"
] | null | null | null | NoiseStudioLib/NoiseStudioLib/input_socket.h | SneakyMax/NoiseStudio | b0c3c72e787d61b798acbcd2147f36e1e78f5bad | [
"Unlicense"
] | null | null | null | NoiseStudioLib/NoiseStudioLib/input_socket.h | SneakyMax/NoiseStudio | b0c3c72e787d61b798acbcd2147f36e1e78f5bad | [
"Unlicense"
] | null | null | null | #ifndef INPUT_SOCKET_H
#define INPUT_SOCKET_H
#include <boost/optional.hpp>
#include "accepted_types.h"
#include "socket.h"
#include "connection.h"
namespace noises
{
class InputSocket : public Socket
{
public:
InputSocket(const std::string& name, SocketType type);
InputSocket(const InputSocket&) = delete;
InputSocket operator=(const InputSocket&) = delete;
void set_accepts(const ConnectionDataType& type);
bool accepts(const ConnectionDataType& type) const;
std::vector<std::reference_wrapper<const ConnectionDataType>> accepted_types() const;
bool optional() const;
void set_optional(bool optional);
const boost::optional<std::reference_wrapper<const Connection>> connection() const;
void set_connection(const Connection& connection);
void remove_connection();
void on_removing();
private:
AcceptedTypes accepted_types_;
bool optional_;
const Connection* connection_;
};
}
#endif // INPUT_SOCKET_H
| 26.658537 | 94 | 0.662397 | [
"vector"
] |
5b44250038bca7890daf413cd6bf8c0f529fca0c | 990 | h | C | src/resummation/gauss_grid.h | dulatf/ihixs | 316d5cdf3e88f2ba69cc43668d66b4f69ff833ce | [
"MIT"
] | 1 | 2019-02-08T13:50:24.000Z | 2019-02-08T13:50:24.000Z | src/resummation/gauss_grid.h | dulatf/ihixs | 316d5cdf3e88f2ba69cc43668d66b4f69ff833ce | [
"MIT"
] | null | null | null | src/resummation/gauss_grid.h | dulatf/ihixs | 316d5cdf3e88f2ba69cc43668d66b4f69ff833ce | [
"MIT"
] | null | null | null | #ifndef GAUSS_GRID_H
#define GAUSS_GRID_H
#include "constants.h"
#include <vector>
#include "as_series.h"
#include "user_interface.h"
#include <complex>
#include <utility>
#include "luminosity.h"
#include <functional>
using namespace std;
class GaussGrid{
public:
GaussGrid(const UserInterface& UI,const string &gridPath);
~GaussGrid();
double DoIntegral(const function<complex<double> (complex<double>)>&);
private:
bool check_grid(const string &gridPath);
void load_grid(void);
void store_grid(void);
void generate_grid(const UserInterface& UI);
void export_grid(const string& path);
void generate_subdivisions(void);
void compute_moments(void);
complex<double> mellin_integral(const complex<double> &n);
string _gridPath;
unsigned int _numContourPoints;
unsigned int _numIntegralSamples;
vector<complex<double> > _moments;
vector<pair<double, double> >_subdivisions;
Luminosity *_lumi;
double _scale;
double _tau;
bool _verbose;
};
#endif
| 23.023256 | 72 | 0.754545 | [
"vector"
] |
5b46c941a720048797879d1cedb3d3dc8c0a8e29 | 998 | h | C | engine_test/shader_tests/src/graphics/renderer/3D/renderer.h | llGuy/gamedev | 16aa203934fd767926c58558e021630288556399 | [
"MIT"
] | null | null | null | engine_test/shader_tests/src/graphics/renderer/3D/renderer.h | llGuy/gamedev | 16aa203934fd767926c58558e021630288556399 | [
"MIT"
] | 4 | 2018-12-24T11:16:53.000Z | 2018-12-24T11:20:29.000Z | engine_test/shader_tests/src/graphics/renderer/3D/renderer.h | llGuy/gamedev | 16aa203934fd767926c58558e021630288556399 | [
"MIT"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include "../pre_render.h"
#include "../render_func.h"
#include "../../../api/api.h"
class mesh_handler;
struct pre_render_ptr
{
bool on_heap;
renderer_pre_render * pre_render;
auto destroy(void) -> void
{
if (on_heap) delete pre_render;
}
};
class renderer_3D
{
protected:
u32 mesh_id;
std::unique_ptr<render_func> draw;
std::vector<pre_render_ptr> pre_renders;
public:
renderer_3D(void) = default;
virtual auto render(glsl_program & program, mesh_handler & mh) -> void = 0;
virtual auto submit(glm::mat4 const & model_matrix) -> void = 0;
virtual auto flush(void) -> void = 0;
virtual ~renderer_3D(void) {};
auto set_mesh(u32 mesh_id, mesh_handler & mh) -> void;
inline auto submit_pre_render(renderer_pre_render * const pre_render, bool on_heap = true)
{
pre_renders.push_back(pre_render_ptr{ on_heap, pre_render });
}
private:
inline auto set_rf(std::unique_ptr<render_func> & func) -> void
{
draw = std::move(func);
}
}; | 20.791667 | 92 | 0.709419 | [
"render",
"vector"
] |
5b560d2d9bac8c172fdffaf46626e52191c504a4 | 98,212 | h | C | CNN/headers/model_2_2_8.h | tclements/CS249FINAL | a8b5196192507cb246aff3718fe0e26085e00f0e | [
"MIT"
] | null | null | null | CNN/headers/model_2_2_8.h | tclements/CS249FINAL | a8b5196192507cb246aff3718fe0e26085e00f0e | [
"MIT"
] | null | null | null | CNN/headers/model_2_2_8.h | tclements/CS249FINAL | a8b5196192507cb246aff3718fe0e26085e00f0e | [
"MIT"
] | null | null | null | const unsigned char model[] __attribute__((aligned(4))) = {
0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c, 0x33, 0x00, 0x00, 0x12, 0x00,
0x1c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00,
0x00, 0x00, 0x18, 0x00, 0x12, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00,
0x28, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
0x04, 0x07, 0x00, 0x00, 0x20, 0x06, 0x00, 0x00, 0x7c, 0x03, 0x00, 0x00,
0xc8, 0x02, 0x00, 0x00, 0xa8, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0xcc, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0xcc, 0x3d, 0x00, 0x00,
0xc8, 0x3d, 0x00, 0x00, 0xd8, 0x3c, 0x00, 0x00, 0x40, 0x3c, 0x00, 0x00,
0x94, 0x3b, 0x00, 0x00, 0x1c, 0x3b, 0x00, 0x00, 0xac, 0x3a, 0x00, 0x00,
0x54, 0x0a, 0x00, 0x00, 0x3c, 0x09, 0x00, 0x00, 0xc4, 0x08, 0x00, 0x00,
0xa4, 0x07, 0x00, 0x00, 0xa0, 0x3d, 0x00, 0x00, 0x9c, 0x3d, 0x00, 0x00,
0x98, 0x3d, 0x00, 0x00, 0x94, 0x3d, 0x00, 0x00, 0x90, 0x3d, 0x00, 0x00,
0x8c, 0x3d, 0x00, 0x00, 0x88, 0x3d, 0x00, 0x00, 0x84, 0x3d, 0x00, 0x00,
0x38, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x08, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
0x6d, 0x69, 0x6e, 0x5f, 0x72, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x5f,
0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0xaa, 0xc3, 0xff, 0xff,
0x04, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x31, 0x2e, 0x35, 0x2e,
0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x00, 0x00, 0x00, 0x4d, 0x4c, 0x49, 0x52, 0x20, 0x43, 0x6f, 0x6e,
0x76, 0x65, 0x72, 0x74, 0x65, 0x64, 0x2e, 0x00, 0x00, 0x00, 0x0e, 0x00,
0x18, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00,
0x60, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00,
0x12, 0x00, 0x00, 0x00, 0x94, 0x3c, 0x00, 0x00, 0x20, 0x3c, 0x00, 0x00,
0x90, 0x3b, 0x00, 0x00, 0x04, 0x3b, 0x00, 0x00, 0x58, 0x3a, 0x00, 0x00,
0xf4, 0x39, 0x00, 0x00, 0x84, 0x39, 0x00, 0x00, 0x2c, 0x09, 0x00, 0x00,
0x0c, 0x08, 0x00, 0x00, 0x94, 0x07, 0x00, 0x00, 0xe8, 0x05, 0x00, 0x00,
0x04, 0x05, 0x00, 0x00, 0xb8, 0x03, 0x00, 0x00, 0x08, 0x03, 0x00, 0x00,
0x58, 0x02, 0x00, 0x00, 0xa4, 0x01, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00,
0x80, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x54, 0x05, 0x00, 0x00, 0x74, 0x04, 0x00, 0x00, 0x48, 0x03, 0x00, 0x00,
0x94, 0x02, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x24, 0x01, 0x00, 0x00,
0x94, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x9a, 0xfd, 0xff, 0xff,
0x00, 0x00, 0x00, 0x09, 0x04, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xa6, 0xc4, 0xff, 0xff,
0x00, 0x00, 0x80, 0x3f, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xbe, 0xfa, 0xff, 0xff,
0x00, 0x00, 0x00, 0x19, 0x01, 0x00, 0x00, 0x00, 0x44, 0xc4, 0xff, 0xff,
0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x30, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00,
0x1c, 0xc4, 0xff, 0xff, 0x1a, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x08,
0x03, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x38, 0xc4, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xbc, 0xc4, 0xff, 0xff,
0x14, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x44, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00,
0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31,
0x30, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x32, 0x31, 0x2f, 0x42,
0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0xa8, 0xc4, 0xff, 0xff,
0xce, 0xfc, 0xff, 0xff, 0x00, 0x00, 0x00, 0x08, 0x03, 0x00, 0x00, 0x00,
0x24, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0x08, 0x00, 0x07, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0xda, 0xfb, 0xff, 0xff, 0x00, 0x00, 0x00, 0x09,
0x01, 0x00, 0x00, 0x00, 0x60, 0xc5, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00,
0x50, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75,
0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x64, 0x65,
0x6e, 0x73, 0x65, 0x5f, 0x32, 0x30, 0x2f, 0x52, 0x65, 0x6c, 0x75, 0x3b,
0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31,
0x30, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x32, 0x30, 0x2f, 0x42,
0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x60, 0xc6, 0xff, 0xff,
0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
0x8a, 0xfc, 0xff, 0xff, 0x00, 0x00, 0x00, 0x16, 0x01, 0x00, 0x00, 0x00,
0x10, 0xc6, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
0x18, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x66, 0x6c, 0x61, 0x74, 0x74, 0x65,
0x6e, 0x5f, 0x31, 0x30, 0x2f, 0x52, 0x65, 0x73, 0x68, 0x61, 0x70, 0x65,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0xc0, 0x00, 0x00, 0x00, 0xf8, 0xc6, 0xff, 0xff, 0x00, 0x00, 0x0e, 0x00,
0x18, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x07, 0x00, 0x14, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00,
0x2c, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x26, 0xfe, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x01, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0xbc, 0xc6, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00,
0x44, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x26, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x6f,
0x6f, 0x6c, 0x69, 0x6e, 0x67, 0x32, 0x64, 0x5f, 0x32, 0x31, 0x2f, 0x4d,
0x61, 0x78, 0x50, 0x6f, 0x6f, 0x6c, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0xc0, 0xc6, 0xff, 0xff, 0x0a, 0xfe, 0xff, 0xff,
0x00, 0x00, 0x00, 0x01, 0x24, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0xfc, 0xfd, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x09, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x68, 0xc7, 0xff, 0xff,
0x14, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0xc8, 0x00, 0x00, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75,
0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63, 0x6f,
0x6e, 0x76, 0x32, 0x64, 0x5f, 0x32, 0x31, 0x2f, 0x52, 0x65, 0x6c, 0x75,
0x3b, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f,
0x31, 0x30, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x32, 0x31,
0x2f, 0x42, 0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x3b, 0x73, 0x65, 0x71,
0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63,
0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x32, 0x31, 0x2f, 0x43, 0x6f, 0x6e,
0x76, 0x32, 0x44, 0x3b, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64,
0x5f, 0x32, 0x31, 0x2f, 0x42, 0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x2f,
0x52, 0x65, 0x61, 0x64, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65,
0x4f, 0x70, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x00,
0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0xd0, 0xc8, 0xff, 0xff,
0x00, 0x00, 0x0e, 0x00, 0x1a, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00,
0x07, 0x00, 0x14, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
0x01, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x18, 0x00, 0x17, 0x00,
0x10, 0x00, 0x0c, 0x00, 0x08, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x2a, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x11, 0x01, 0x00, 0x00, 0x00,
0xb0, 0xc8, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00,
0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31,
0x30, 0x2f, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x6f, 0x6f, 0x6c, 0x69, 0x6e,
0x67, 0x32, 0x64, 0x5f, 0x32, 0x30, 0x2f, 0x4d, 0x61, 0x78, 0x50, 0x6f,
0x6f, 0x6c, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0x1a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0xac, 0xc9, 0xff, 0xff, 0x00, 0x00, 0x0e, 0x00, 0x14, 0x00, 0x00, 0x00,
0x08, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x30, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x04, 0x00,
0x08, 0x00, 0x0f, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00,
0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x90, 0xc9, 0xff, 0xff,
0x14, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0xc8, 0x00, 0x00, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75,
0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63, 0x6f,
0x6e, 0x76, 0x32, 0x64, 0x5f, 0x32, 0x30, 0x2f, 0x52, 0x65, 0x6c, 0x75,
0x3b, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f,
0x31, 0x30, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x32, 0x30,
0x2f, 0x42, 0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x3b, 0x73, 0x65, 0x71,
0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63,
0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x32, 0x30, 0x2f, 0x43, 0x6f, 0x6e,
0x76, 0x32, 0x44, 0x3b, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64,
0x5f, 0x32, 0x30, 0x2f, 0x42, 0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x2f,
0x52, 0x65, 0x61, 0x64, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65,
0x4f, 0x70, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x00,
0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x4e, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0xca, 0xff, 0xff,
0xf2, 0xca, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00,
0x69, 0x25, 0xc9, 0x3c, 0x0b, 0x3e, 0x0e, 0x3e, 0x18, 0x0e, 0xb6, 0x38,
0x6d, 0x4d, 0x7d, 0xbd, 0x2b, 0x59, 0x08, 0xbd, 0x46, 0xc3, 0x01, 0x3f,
0x89, 0x85, 0xcf, 0x3d, 0x52, 0x49, 0x2c, 0xbe, 0x97, 0xec, 0xfa, 0x3e,
0x4d, 0xc6, 0x4f, 0xbe, 0x9f, 0x3a, 0x2a, 0x3f, 0x53, 0x06, 0x54, 0xbe,
0x4a, 0x78, 0x76, 0xbf, 0xf6, 0x60, 0x84, 0xbf, 0x98, 0x7e, 0x0f, 0xbf,
0x97, 0x76, 0xfa, 0xbe, 0x9e, 0xe5, 0x8f, 0x3d, 0x90, 0x6c, 0x2a, 0x3f,
0x2c, 0x16, 0xa9, 0xbe, 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e, 0x76,
0x32, 0x44, 0x00, 0x00, 0x1c, 0xcb, 0xff, 0xff, 0x0e, 0xcc, 0xff, 0xff,
0x04, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0b, 0x4f, 0x89, 0xbf,
0xd7, 0x6b, 0x28, 0x3c, 0xa6, 0xd3, 0xa4, 0xbe, 0x04, 0xf3, 0x4e, 0xbf,
0xdb, 0x35, 0x32, 0xbc, 0xeb, 0xb3, 0x90, 0x3f, 0x16, 0xcc, 0xff, 0xff,
0x10, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00,
0x3c, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64,
0x5f, 0x32, 0x30, 0x2f, 0x43, 0x6f, 0x6e, 0x76, 0x32, 0x44, 0x00, 0x00,
0x90, 0xcb, 0xff, 0xff, 0x82, 0xcc, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00,
0xc0, 0x00, 0x00, 0x00, 0x4f, 0x70, 0xe7, 0xbe, 0x90, 0x7d, 0xc8, 0x3d,
0x77, 0x97, 0x8c, 0xbd, 0x89, 0x22, 0x8e, 0x3e, 0xb2, 0x80, 0x9b, 0xbe,
0xa8, 0x33, 0x2d, 0xbe, 0x99, 0x1c, 0x4c, 0xbe, 0x7d, 0xaf, 0xb6, 0x3e,
0x88, 0xcf, 0x1b, 0x3f, 0x60, 0xbe, 0x58, 0x3e, 0xd4, 0x57, 0x82, 0xbf,
0x91, 0xe3, 0x3b, 0xbf, 0xb4, 0x06, 0x44, 0x3f, 0x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x23, 0x3e, 0x72, 0xa0, 0xcc, 0xbd, 0x14, 0xa5, 0x75, 0xbe,
0x9c, 0x0c, 0x01, 0xbd, 0x86, 0xfd, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00,
0x1d, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f,
0x32, 0x30, 0x2f, 0x4d, 0x61, 0x74, 0x4d, 0x75, 0x6c, 0x00, 0x00, 0x00,
0xf8, 0xfc, 0xff, 0xff, 0xea, 0xfd, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0e, 0x00, 0x18, 0x00, 0x08, 0x00, 0x07, 0x00, 0x0c, 0x00,
0x10, 0x00, 0x14, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x66, 0x6c, 0x61, 0x74, 0x74, 0x65,
0x6e, 0x5f, 0x31, 0x30, 0x2f, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x00, 0x00,
0x64, 0xfd, 0xff, 0xff, 0x56, 0xfe, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x56, 0x5d, 0x8d, 0xbd, 0x34, 0x41, 0xe3, 0x3d,
0xad, 0xd4, 0x18, 0xbe, 0x52, 0xfe, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00,
0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31,
0x30, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x32, 0x31, 0x2f, 0x42,
0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x2f, 0x52, 0x65, 0x61, 0x64, 0x56,
0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x4f, 0x70, 0x2f, 0x72, 0x65,
0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x00, 0x00, 0xd8, 0xfd, 0xff, 0xff,
0xca, 0xfe, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x87, 0xfc, 0xa7, 0xbd, 0x4f, 0x6c, 0x4f, 0x3e, 0x83, 0xdf, 0xff, 0x3d,
0xd3, 0xd8, 0x46, 0x3d, 0x32, 0xf5, 0x15, 0xbe, 0xbf, 0x60, 0xfb, 0x3e,
0x65, 0x68, 0x66, 0x3e, 0xc1, 0x0a, 0x1b, 0x3f, 0xbf, 0x02, 0xcf, 0x3d,
0x6e, 0x8b, 0xd3, 0x3e, 0x50, 0xbf, 0xe0, 0x3e, 0xb0, 0xa0, 0x76, 0x3f,
0x8d, 0x48, 0xc1, 0x3e, 0x6b, 0x07, 0xae, 0xbd, 0x50, 0x15, 0xaf, 0x3e,
0xd1, 0xd3, 0xb3, 0x3e, 0xfa, 0xfe, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00,
0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31,
0x30, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x32, 0x30, 0x2f, 0x42,
0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x2f, 0x52, 0x65, 0x61, 0x64, 0x56,
0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x4f, 0x70, 0x2f, 0x72, 0x65,
0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x00, 0x00, 0x80, 0xfe, 0xff, 0xff,
0x72, 0xff, 0xff, 0xff, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x57, 0x33, 0x43, 0xbe, 0x1e, 0xd6, 0x79, 0xbd, 0xde, 0xd9, 0x04, 0xbb,
0x5e, 0x72, 0x18, 0xbd, 0x15, 0x92, 0x53, 0xbe, 0xc2, 0xde, 0x9e, 0xbd,
0x41, 0x4f, 0xb6, 0xbb, 0x9e, 0xd5, 0xde, 0xbb, 0x82, 0xff, 0xff, 0xff,
0x10, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x37, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69,
0x61, 0x6c, 0x5f, 0x31, 0x30, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64,
0x5f, 0x32, 0x31, 0x2f, 0x42, 0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x2f,
0x52, 0x65, 0x61, 0x64, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65,
0x4f, 0x70, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x00,
0x04, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x08, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0xe5, 0xd3, 0x25, 0xbd, 0x0f, 0xd2, 0x7d, 0xbc,
0x00, 0x00, 0x0e, 0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00,
0x0c, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00,
0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x31,
0x30, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x32, 0x30, 0x2f,
0x42, 0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x2f, 0x52, 0x65, 0x61, 0x64,
0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x4f, 0x70, 0x2f, 0x72,
0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x00, 0x94, 0xff, 0xff, 0xff,
0x14, 0x00, 0x18, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00,
0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x69, 0x6e, 0x70, 0x75,
0x74, 0x5f, 0x31, 0x31, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0x50, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0x04, 0x00, 0x04, 0x00,
0x04, 0x00, 0x00, 0x00
};
| 73.843609 | 73 | 0.648668 | [
"model"
] |
85a7154bc5a8160770830be29621d0b5ba870bcd | 7,724 | h | C | liberty/include/liberty/Utilities/CompressedPointerVector.h | righier/cpf | 0a9d7c2cde6676be519c490d98197eb5283520b4 | [
"MIT"
] | 18 | 2020-08-14T21:19:59.000Z | 2022-02-22T12:43:52.000Z | liberty/include/liberty/Utilities/CompressedPointerVector.h | righier/cpf | 0a9d7c2cde6676be519c490d98197eb5283520b4 | [
"MIT"
] | 23 | 2020-08-17T21:04:36.000Z | 2022-03-02T19:29:27.000Z | liberty/include/liberty/Utilities/CompressedPointerVector.h | righier/cpf | 0a9d7c2cde6676be519c490d98197eb5283520b4 | [
"MIT"
] | 2 | 2020-09-17T17:25:19.000Z | 2021-05-21T11:21:43.000Z | #ifndef LLVM_LIBERTY_COMPRESSED_POINTER_VECTOR_H
#define LLVM_LIBERTY_COMPRESSED_POINTER_VECTOR_H
#include <assert.h>
#include <stdint.h>
#include <vector>
#include <algorithm>
#include <iostream>
namespace liberty
{
/// A somewhat less-ugly way to
/// define an integer which is
/// big-enough to hold a pointer.
template <unsigned PtrSize>
struct BigEnough
{ };
template <>
struct BigEnough<4U>
{
typedef uint32_t Integer;
};
template <>
struct BigEnough<8U>
{
typedef uint64_t Integer;
};
template <class Type> class CompressedPointerVector;
template <class Type> class CompressedPointerVectorBuilder;
/// Allows forward iteration over the elements
/// of a CompressedPointerVector
template <class Type>
class CompressedPointerVectorIterator
{
public:
typedef typename BigEnough<sizeof(Type*)>::Integer Int;
typedef typename CompressedPointerVector<Type>::Storage::const_iterator StorageIterator;
typedef CompressedPointerVectorIterator<Type> iterator;
CompressedPointerVectorIterator(const StorageIterator &i, const StorageIterator &e, Int initial=0U)
: iter(i), end(e), accumulator(initial)
{
++*this;
}
/// Dereference the iterator
Type * operator*() const
{
return (Type*)accumulator;
}
/// Advance the iterator
iterator &operator++()
{
if( iter == end )
return *this;
uint8_t byte = *iter;
++iter;
// Is this a delta or a sync?
if( (byte & 1U) == 1U )
{
// Sync!
// this marks a full entry, remove
// the sentinel bit.
Int full = (Int) (byte & ~1U);
// read more the remaining sizeof(Int)-1 bytes...
// Remember, least significant first.
for( unsigned i=1U, shift=8U; i<sizeof(Int)/sizeof(uint8_t); ++i, shift += 8U, ++iter)
full |= ( (Int) *iter ) << shift;
accumulator = full;
}
else
{
// Delta!
accumulator += byte;
}
return *this;
}
/// Compare for inequality.
bool operator!=(const iterator &other) const
{
return iter != other.iter;
}
private:
StorageIterator iter, end;
Int accumulator;
};
/// This class is a space-efficient
/// method of storing a large number of
/// pointers, effectively using 14-bits
/// per pointer.
///
/// The trick is that it will store
/// the difference between pointer
/// values. If you sort the list first,
/// It turns out that a large fraction
/// of these values are within 256 of their
/// neighbor.
///
/// It assumes that the pointers are
/// aligned to even addresses (i.e.
/// the low bit of a pointer is
/// 0). This means it will NOT
/// work on char*.
///
/// As long as the differences are less than 2**8,
/// we can store it in a single byte. All
/// other values we store as native-sized
/// pointers.
///
/// And if you think this is an unreasonable
/// hack, I'll remind you that llvm::Value
/// does something like this for it's use_list:
/// http://llvm.org/docs/ProgrammersManual.html#UserLayout
template <class Type>
class CompressedPointerVector
{
/// don't call this
CompressedPointerVector(const CompressedPointerVector<Type> &) { assert(false); }
/// don't call this
CompressedPointerVector<Type> &operator=(const CompressedPointerVector<Type> &) { assert(false); return *this; }
public:
typedef typename BigEnough<sizeof(Type*)>::Integer Int;
typedef std::vector<uint8_t> Storage;
typedef CompressedPointerVectorIterator<Type> iterator;
CompressedPointerVector() : sz(0U), bytes() {}
/// Determine the number of elements in this collection.
unsigned size() const { return sz-1; }
/// Get a forward iterator to all elements
/// of this collection.
iterator begin() const
{
Storage::const_iterator b=bytes.begin(), e=bytes.end();
return iterator(b,e);
}
/// Get the end iterator corresponding to begin()
iterator end() const
{
Storage::const_iterator e=bytes.end();
return iterator(e,e);
}
/// Returns the effective number of bits required
/// for each pointer.
double efficiency() const
{
return 8.0 * bytes.size() / size();
}
private:
unsigned sz;
Storage bytes;
protected:
friend class CompressedPointerVectorBuilder<Type>;
void reserve(unsigned n)
{
bytes.reserve(n);
}
void push_diff(uint8_t delta)
{
assert( (delta & 1U) == 0U && "Alignment assumption was incorrect for this type!");
++sz;
bytes.push_back(delta);
}
void push_sync(Int full)
{
assert( (full & 1U) == 0U && "Alignment assumption was incorrect for this type!");
++sz;
// Mark this as a full sync entry
// by making least significant bit 1.
// This is sound if (1) we store the
// sync records in little-endian order,
// and (2) our pointer types have alignment
// of AT LEAST 2 bytes.
full |= 1U;
// Write the integer byte-by-byte; write
// least-significant first.
for(unsigned i=0U; i< sizeof(Int)/sizeof(uint8_t); ++i, full >>= 8U)
bytes.push_back( (uint8_t) (full & 0xff));
}
};
/// This is used to construct a
/// CompressedPointerVector. You build
/// one by push()ing zero or more elements,
/// and then calling the distill() method.
/// After they have been distilled, a
/// CompressedPointerVector should be treated
/// as if it is immutable.
template <class Type>
class CompressedPointerVectorBuilder
{
// Average number of bits required for one pointer
// Any number >0 will work, but better
// estimates yield faster distill()ation.
#define AVERAGE_EFFICIENCY (14)
public:
typedef typename BigEnough<sizeof(Type*)>::Integer Int;
typedef std::vector<Type *> Storage;
typedef typename Storage::iterator iterator;
typedef typename Storage::const_iterator const_iterator;
private:
Storage pointers;
public:
CompressedPointerVectorBuilder() : pointers() {}
/// Add a new pointer to the collection
void push(Type *t)
{
pointers.push_back(t);
}
/// Remove a pointer from the collection
void remove(Type *t)
{
iterator i = std::find(pointers.begin(), pointers.end(), t);
if( i == pointers.end() )
return;
*i = pointers.back();
pointers.pop_back();
}
/// You can iterate over the collection
/// before you distill, if you wish
const_iterator begin() const { return pointers.begin(); }
const_iterator end() const { return pointers.end(); }
/// Release internal storage
void clear()
{
pointers.clear();
}
/// Construct a compressed pointer vector
/// from the elements which have been added
/// so far.
void distill(CompressedPointerVector<Type> &output)
{
std::sort( pointers.begin(), pointers.end() );
const unsigned expectedSize = AVERAGE_EFFICIENCY * pointers.size() / 8;
output.reserve( expectedSize );
Int prev = 0U;
for(iterator i=pointers.begin(), e=pointers.end(); i!=e; ++i)
{
const Int next = (Int) *i;
const Int diff64 = next - prev;
const uint8_t diff8 = (uint8_t) (diff64 & 0xffU);
if( diff64 == diff8 )
output.push_diff( diff8 );
else
output.push_sync( next );
prev = next;
}
// put one more to make the iterator easier to implement
output.push_diff(0);
assert( output.size() == pointers.size() );
}
};
}
#endif
| 25.407895 | 116 | 0.625842 | [
"vector"
] |
85b8e2454ffbd9c925749dae7603435dd2b3f1ec | 3,995 | h | C | Client/BalanceShoeClient_old/pages/Mac/macmainpage.h | nimile/Balance-Shoe | 525e129caa2e2ab19186217776a2d73b656980ff | [
"MIT"
] | 1 | 2019-12-11T23:35:25.000Z | 2019-12-11T23:35:25.000Z | Client/BalanceShoeClient_old/pages/Mac/macmainpage.h | nimile/Balance-Shoe | 525e129caa2e2ab19186217776a2d73b656980ff | [
"MIT"
] | null | null | null | Client/BalanceShoeClient_old/pages/Mac/macmainpage.h | nimile/Balance-Shoe | 525e129caa2e2ab19186217776a2d73b656980ff | [
"MIT"
] | null | null | null | /**
* @file macmainpage.h
* @brief Provides the logic to handle main page
* @details This file contains the logic for the main page
* At this page it is possible to invoke different settings
* it is also possible to start the ESP.
* @author Nils Milewski (nimile/10010480)
*/
#ifndef MACMAINPAGE_H
#define MACMAINPAGE_H
#include <QObject>
#if defined(Q_OS_MAC)
#include <QWidget>
/* Qt widgets */
#include <QWidget> // Used as base class
#include <QLabel>
#include <QSpacerItem> // Used to insert space between UI elements
#include <QPushButton>
/* Qt layout */
#include <QVBoxLayout> // Used as primary layout
/* User inccldues */
#include "util/vibrator.h" // Used to vibrate the device
#include "util/utils.h" // Used to access project utilities
namespace haevn::esp::pages{
/**
* @brief The MacMainPage class This lass contains the logic to handle main page
* @details This class contains the logic for the main page
* At this page it is possible to invoke different settings
* it is also possible to start the ESP.
* @author Nils Milewski (nimile/10010480)
*/
class MacMainPage : public QWidget{
Q_OBJECT
private attributes:
util::Vibrator* vib;
QPushButton* buttonOff;
QPushButton* buttonOn;
QPushButton* buttonUserSettings;
QPushButton* buttonStat;
public methods:
/**
* @brief MacMainPage This is a constructor.
* @details This constructor initializes all required attributes and the UI.
* It also connects all required signals to their equivalent slot.
* @param parent This is the parrent object of this page, default nullptr.
* @author Nils Milewski (nimile/10010480)
*/
MacMainPage(QWidget* parent = nullptr);
private slots:
/**
* @brief buttonOnPressed Currently this method activates the vibration of the device.
* @details This slot will be invoked if the buttonOn is pressed. It will start the
* Bluetooth (Low Energy) connection to the ESP ans enters a listen mode.
* @author Nils Milewski (nimile/10010480)
*/
void buttonOnPressed();
/**
* @brief buttonOffPressed Currently this method deactivates the vibration of the device.
* @details This slot will be invoked if the buttonOff is pressed. It will shut down the
* Bluetooth (Low Energy) connection to the ESP ans leaves the listen mode.
* @author Nils Milewski (nimile/10010480)
*/
void buttonOffPressed();
/**
* @brief buttonShowUserSettings This method invokes the user settings.
* @details This slot will be invoked if the buttonUserSettings is pressed.
* It will call the \a show method of the \a WindowHandle object with
* \a userSettingsWindow as argument.
* @author Nils Milewski (nimile/10010480)
*/
void buttonShowUserSettings();
/**
* @brief buttonShowDevSettings This method invokes the developer settings.
* @details This slot will be invoked if the buttonDevSettings is pressed.
* It will call the \a show method of the \a WindowHandle object with
* \a devSettingsWindow as argument.
* @author Nils Milewski (nimile/10010480)
*/
void buttonDevPressed();
/**
* @brief showBluetoothDialog This method opens a dialog of bluetooth devices nearby.
* @details This slot will be invoked if buttonOn is pressed.
* It will open a dialog window where all bluetooth devices nearby gets shown.
* @author Marc Nowakowski (marcnow/10009339)
*/
void showBluetoothDialog();
};
}
#endif // defined(Q_OS_MAC)
#endif // MACMAINPAGE_H
| 34.145299 | 98 | 0.632791 | [
"object"
] |
85c730a89b34dcdf18c08ff80178479ceccf1c92 | 5,706 | h | C | ImportantExample/cuteReportView/cutereport/src/plugins/standard/core_plugins/items/line/line.h | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | 3 | 2018-12-24T19:35:52.000Z | 2022-02-04T14:45:59.000Z | ImportantExample/cuteReportView/cutereport/src/plugins/standard/core_plugins/items/line/line.h | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | null | null | null | ImportantExample/cuteReportView/cutereport/src/plugins/standard/core_plugins/items/line/line.h | xiaohaijin/Qt | 54d961c6a8123d8e4daf405b7996aba4be9ab7ed | [
"MIT"
] | 1 | 2019-05-09T02:42:40.000Z | 2019-05-09T02:42:40.000Z | /***************************************************************************
* This file is part of the CuteReport project *
* Copyright (C) 2012-2015 by Alexander Mikhalov *
* alexander.mikhalov@gmail.com *
* *
** GNU General Public License Usage **
* *
* This library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
** GNU Lesser General Public License **
* *
* 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 3 of the *
* License, or (at your option) any later version. *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
***************************************************************************/
#ifndef LINE_H
#define LINE_H
#include <iteminterface.h>
#include "iteminterfaceview.h"
#include "renderediteminterface.h"
#include "cutereport_globals.h"
class LineItemPrivate;
class LineItem : public CuteReport::ItemInterface
{
Q_OBJECT
#if QT_VERSION >= 0x050000
Q_PLUGIN_METADATA(IID "CuteReport.ItemInterface/1.0")
#endif
Q_INTERFACES(CuteReport::ItemInterface)
Q_ENUMS(LineStyle)
Q_PROPERTY(QPen linePen READ linePen WRITE setLinePen NOTIFY linePenChanged)
Q_PROPERTY(QString lineStyle READ lineStyleStr WRITE setLineStyleStr NOTIFY lineStyleChanged)
Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle NOTIFY lineStyleChanged)
Q_PROPERTY(QStringList _lineStyle_variants READ _lineStyle_variants DESIGNABLE false)
public:
enum LineStyle {Vertical, Horizontal, ForwardDiagonal, BackwardDiagonal};
explicit LineItem(QObject * parent = 0);
virtual void moduleInit();
virtual void init_gui();
virtual CuteReport::BaseItemInterface * createInstance(QObject * parent) const;
virtual CuteReport::BaseItemHelperInterface * helper();
virtual QByteArray serialize();
virtual void deserialize(QByteArray &data);
virtual bool canContain(QObject * object);
virtual QIcon itemIcon() const;
virtual QString moduleShortName() const;
virtual QString suitName() const { return "Standard"; }
virtual QString itemGroup() const;
virtual bool renderPrepare();
virtual CuteReport::RenderedItemInterface * renderView();
static void paint(QPainter * painter, const QStyleOptionGraphicsItem *option, const CuteReport::BaseItemInterfacePrivate * data, const QRectF &boundingRect, CuteReport::RenderingType type = CuteReport::RenderingTemplate);
LineStyle lineStyle() const;
void setLineStyle(LineStyle lineStyle);
QString lineStyleStr() const;
void setLineStyleStr(const QString & lineStyle);
QPen linePen() const;
void setLinePen(const QPen & pen);
virtual void initScript(QScriptEngine * scriptEngine);
/** propertyeditor hints */
QStringList _lineStyle_variants() const;
virtual QString _current_property_description() const;
signals:
void lineStyleChanged(LineStyle);
void lineStyleChanged(const QString &);
void linePenChanged(QPen);
protected:
explicit LineItem(LineItemPrivate *dd, QObject * parent);
virtual BaseItemInterface * itemClone() const;
private:
Q_DECLARE_PRIVATE(LineItem)
};
class LineItemView : public CuteReport::ItemInterfaceView
{
Q_INTERFACES(CuteReport::ItemInterfaceView)
public:
LineItemView(CuteReport::BaseItemInterface * item):
CuteReport::ItemInterfaceView(item){}
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0)
{
Q_UNUSED(widget)
LineItem::paint(painter, option, ptr(), boundingRect(), CuteReport::RenderingTemplate);
}
};
class RenderedLineItem : public CuteReport::RenderedItemInterface
{
public:
explicit RenderedLineItem(CuteReport::BaseItemInterface * item, CuteReport::BaseItemInterfacePrivate *itemPrivateData)
:RenderedItemInterface(item, itemPrivateData) {}
virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0)
{
Q_UNUSED(widget)
LineItem::paint(painter, option, d_ptr, boundingRect(), CuteReport::RenderingReport);
}
};
Q_DECLARE_METATYPE(LineItem::LineStyle)
#endif
| 40.183099 | 225 | 0.625832 | [
"object"
] |
85ce9e2505fe1162dd08eb529b8590e1c3aec0f7 | 1,130 | c | C | STM32Cube_FW_F4_V1.25.0/Middlewares/Third_Party/FatFs/doc/res/app1.c | XiaZhouZero/OPEC | e2844492e27769137ac5c50e9b08f58f5942d5b2 | [
"MIT"
] | 307 | 2019-10-24T09:05:23.000Z | 2022-03-31T12:31:46.000Z | STM32Cube_FW_F4_V1.25.0/Middlewares/Third_Party/FatFs/doc/res/app1.c | XiaZhouZero/OPEC | e2844492e27769137ac5c50e9b08f58f5942d5b2 | [
"MIT"
] | 28 | 2016-08-05T03:02:09.000Z | 2017-10-18T00:04:01.000Z | STM32Cube_FW_F4_V1.25.0/Middlewares/Third_Party/FatFs/doc/res/app1.c | XiaZhouZero/OPEC | e2844492e27769137ac5c50e9b08f58f5942d5b2 | [
"MIT"
] | 116 | 2019-10-24T09:14:23.000Z | 2022-03-18T20:52:21.000Z | /*------------------------------------------------------------/
/ Open or create a file in append mode
/ (This function was sperseded by FA_OPEN_APPEND at FatFs R0.12a)
/------------------------------------------------------------*/
FRESULT open_append (
FIL* fp, /* [OUT] File object to create */
const char* path /* [IN] File name to be opened */
)
{
FRESULT fr;
/* Opens an existing file. If not exist, creates a new file. */
fr = f_open(fp, path, FA_WRITE | FA_OPEN_ALWAYS);
if (fr == FR_OK) {
/* Seek to end of the file to append data */
fr = f_lseek(fp, f_size(fp));
if (fr != FR_OK)
f_close(fp);
}
return fr;
}
int main (void)
{
FRESULT fr;
FATFS fs;
FIL fil;
/* Open or create a log file and ready to append */
f_mount(&fs, "", 0);
fr = open_append(&fil, "logfile.txt");
if (fr != FR_OK) return 1;
/* Append a line */
f_printf(&fil, "%02u/%02u/%u, %2u:%02u\n", Mday, Mon, Year, Hour, Min);
/* Close the file */
f_close(&fil);
return 0;
}
| 25.111111 | 76 | 0.472566 | [
"object"
] |
85d2b514bef6ab7fb6c3c8c263328b2a5a90b761 | 56,931 | c | C | interface/vmcs_host/vc_vchi_cecservice.c | anthonyryan1/raspberrypi-userland | 4f5d2748100ab151189374b7ce0a2d22ef9a9d95 | [
"BSD-3-Clause"
] | 1 | 2019-10-15T02:38:55.000Z | 2019-10-15T02:38:55.000Z | interface/vmcs_host/vc_vchi_cecservice.c | anthonyryan1/raspberrypi-userland | 4f5d2748100ab151189374b7ce0a2d22ef9a9d95 | [
"BSD-3-Clause"
] | null | null | null | interface/vmcs_host/vc_vchi_cecservice.c | anthonyryan1/raspberrypi-userland | 4f5d2748100ab151189374b7ce0a2d22ef9a9d95 | [
"BSD-3-Clause"
] | 3 | 2017-02-15T20:29:07.000Z | 2021-07-11T10:09:03.000Z | /*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string.h>
#include <stdio.h>
#include "vchost_platform_config.h"
#include "vchost.h"
#include "interface/vcos/vcos.h"
#include "interface/vchi/vchi.h"
#include "interface/vchi/common/endian.h"
#include "interface/vchi/message_drivers/message.h"
#include "vc_cecservice.h"
#include "vc_service_common.h"
/******************************************************************************
Local types and defines.
******************************************************************************/
#ifndef _min
#define _min(x,y) (((x) <= (y))? (x) : (y))
#endif
#ifndef _max
#define _max(x,y) (((x) >= (y))? (x) : (y))
#endif
//TV service host side state (mostly the same as Videocore side - TVSERVICE_STATE_T)
typedef struct {
//Generic service stuff
VCHI_SERVICE_HANDLE_T client_handle[VCHI_MAX_NUM_CONNECTIONS]; //To connect to server on VC
VCHI_SERVICE_HANDLE_T notify_handle[VCHI_MAX_NUM_CONNECTIONS]; //For incoming notification
uint32_t msg_flag[VCHI_MAX_NUM_CONNECTIONS];
char command_buffer[CECSERVICE_MSGFIFO_SIZE];
char response_buffer[CECSERVICE_MSGFIFO_SIZE];
uint32_t response_length;
uint32_t notify_buffer[CECSERVICE_MSGFIFO_SIZE/sizeof(uint32_t)];
uint32_t notify_length;
uint32_t num_connections;
VCOS_MUTEX_T lock;
CECSERVICE_CALLBACK_T notify_fn;
void *notify_data;
int initialised;
int to_exit;
//CEC state, not much here
//Most things live on Videocore side
uint16_t physical_address; //16-bit packed physical address
CEC_DEVICE_TYPE_T logical_address; //logical address
VC_CEC_TOPOLOGY_T *topology; //16-byte aligned for the transfer
} CECSERVICE_HOST_STATE_T;
/******************************************************************************
Static data.
******************************************************************************/
static CECSERVICE_HOST_STATE_T cecservice_client;
static VCOS_EVENT_T cecservice_message_available_event;
static VCOS_EVENT_T cecservice_notify_available_event;
static VCOS_THREAD_T cecservice_notify_task;
static uint32_t cecservice_log_initialised = 0;
//Command strings - must match what's in vc_cecservice_defs.h
static char* cecservice_command_strings[] = {
"register_cmd",
"register_all",
"deregister_cmd",
"deregister_all",
"send_msg",
"get_logical_addr",
"alloc_logical_addr",
"release_logical_addr",
"get_topology",
"set_vendor_id",
"set_osd_name",
"get_physical_addr",
"get_vendor_id",
"poll_addr",
"set_logical_addr",
"add_device",
"set_passive",
"end_of_list"
};
static const uint32_t max_command_strings = sizeof(cecservice_command_strings)/sizeof(char *);
//Notification strings - must match vc_cec.h VC_CEC_NOTIFY_T
static char* cecservice_notify_strings[] = {
"none",
"TX",
"RX",
"User Ctrl Pressed",
"User Ctrl Released",
"Vendor Remote Down",
"Vendor Remote Up",
"logical address",
"topology",
"logical address lost",
"???"
};
static const uint32_t max_notify_strings = sizeof(cecservice_notify_strings)/sizeof(char *);
//Device type strings
static char* cecservice_devicetype_strings[] = {
"TV",
"Rec",
"Reserved",
"Tuner",
"Playback",
"Audio",
"Switch",
"VidProc",
"8", "9", "10", "11", "12", "13", "14", "invalid"
};
static const uint32_t max_devicetype_strings = sizeof(cecservice_devicetype_strings)/sizeof(char *);
/******************************************************************************
Static functions.
******************************************************************************/
//Lock the host state
static __inline int lock_obtain (void) {
VCOS_STATUS_T status = VCOS_EAGAIN;
if(cecservice_client.initialised && (status = vcos_mutex_lock(&cecservice_client.lock)) == VCOS_SUCCESS) {
if(cecservice_client.initialised) { // check service hasn't been closed while we were waiting for the lock.
vchi_service_use(cecservice_client.client_handle[0]);
return status;
} else {
vcos_mutex_unlock(&cecservice_client.lock);
vc_cec_log_error("CEC Service closed while waiting for lock");
return VCOS_EAGAIN;
}
}
vc_cec_log_error("CEC service failed to obtain lock, initialised:%d, lock status:%d",
cecservice_client.initialised, status);
return status;
}
//Unlock the host state
static __inline void lock_release (void) {
if(cecservice_client.initialised) {
vchi_service_release(cecservice_client.client_handle[0]);
}
vcos_mutex_unlock(&cecservice_client.lock);
}
//Forward declarations
static void cecservice_client_callback( void *callback_param,
VCHI_CALLBACK_REASON_T reason,
void *msg_handle );
static void cecservice_notify_callback( void *callback_param,
VCHI_CALLBACK_REASON_T reason,
void *msg_handle );
static int32_t cecservice_wait_for_reply(void *response, uint32_t max_length);
static int32_t cecservice_wait_for_bulk_receive(void *buffer, uint32_t max_length);
static int32_t cecservice_send_command( uint32_t command, const void *buffer, uint32_t length, uint32_t has_reply);
static int32_t cecservice_send_command_reply( uint32_t command, void *buffer, uint32_t length,
void *response, uint32_t max_length);
static void *cecservice_notify_func(void *arg);
static void cecservice_logging_init(void);
/******************************************************************************
Global data
*****************************************************************************/
VCOS_LOG_CAT_T cechost_log_category;
/******************************************************************************
CEC service API
******************************************************************************/
/******************************************************************************
NAME
vc_vchi_cec_init
SYNOPSIS
void vc_vchi_cec_init(VCHI_INSTANCE_T initialise_instance, VCHI_CONNECTION_T **connections, uint32_t num_connections )
FUNCTION
Initialise the CEC service for use. A negative return value
indicates failure (which may mean it has not been started on VideoCore).
RETURNS
int
******************************************************************************/
VCHPRE_ void VCHPOST_ vc_vchi_cec_init(VCHI_INSTANCE_T initialise_instance, VCHI_CONNECTION_T **connections, uint32_t num_connections ) {
int32_t success = -1;
VCOS_STATUS_T status;
VCOS_THREAD_ATTR_T attrs;
uint32_t i;
if (cecservice_client.initialised)
return;
vc_cec_log_info("Initialising CEC service");
// record the number of connections
vcos_memset( &cecservice_client, 0, sizeof(CECSERVICE_HOST_STATE_T) );
cecservice_client.num_connections = num_connections;
cecservice_client.physical_address = CEC_CLEAR_ADDR;
cecservice_client.logical_address = CEC_AllDevices_eUnRegistered;
status = vcos_mutex_create(&cecservice_client.lock, "HCEC");
vcos_assert(status == VCOS_SUCCESS);
status = vcos_event_create(&cecservice_message_available_event, "HCEC");
vcos_assert(status == VCOS_SUCCESS);
status = vcos_event_create(&cecservice_notify_available_event, "HCEC");
vcos_assert(status == VCOS_SUCCESS);
cecservice_client.topology = vcos_malloc_aligned(sizeof(VC_CEC_TOPOLOGY_T), 16, "HCEC topology");
vcos_assert(cecservice_client.topology);
for (i=0; i < cecservice_client.num_connections; i++) {
// Create a 'Client' service on the each of the connections
SERVICE_CREATION_T cecservice_parameters = { VCHI_VERSION(VC_CECSERVICE_VER),
CECSERVICE_CLIENT_NAME, // 4cc service code
connections[i], // passed in fn ptrs
0, // tx fifo size (unused)
0, // tx fifo size (unused)
&cecservice_client_callback,// service callback
&cecservice_message_available_event, // callback parameter
VC_FALSE, // want_unaligned_bulk_rx
VC_FALSE, // want_unaligned_bulk_tx
VC_FALSE, // want_crc
};
SERVICE_CREATION_T cecservice_parameters2 = { VCHI_VERSION(VC_CECSERVICE_VER),
CECSERVICE_NOTIFY_NAME, // 4cc service code
connections[i], // passed in fn ptrs
0, // tx fifo size (unused)
0, // tx fifo size (unused)
&cecservice_notify_callback,// service callback
&cecservice_notify_available_event, // callback parameter
VC_FALSE, // want_unaligned_bulk_rx
VC_FALSE, // want_unaligned_bulk_tx
VC_FALSE, // want_crc
};
//Create the client to normal CEC service
success = vchi_service_open( initialise_instance, &cecservice_parameters, &cecservice_client.client_handle[i] );
vcos_assert( success == 0 );
if(success)
vc_cec_log_error("Failed to connected to CEC service: %d", success);
//Create the client to the async CEC service (any CEC related notifications)
success = vchi_service_open( initialise_instance, &cecservice_parameters2, &cecservice_client.notify_handle[i] );
vcos_assert( success == 0 );
if(success)
vc_cec_log_error("Failed to connected to CEC async service: %d", success);
vchi_service_release(cecservice_client.client_handle[i]);
vchi_service_release(cecservice_client.notify_handle[i]);
}
//Create the notifier task
vcos_thread_attr_init(&attrs);
vcos_thread_attr_setstacksize(&attrs, 2048);
vcos_thread_attr_settimeslice(&attrs, 1);
//Initialise logging
cecservice_logging_init();
status = vcos_thread_create(&cecservice_notify_task, "HCEC Notify", &attrs, cecservice_notify_func, &cecservice_client);
vcos_assert(status == VCOS_SUCCESS);
cecservice_client.initialised = 1;
vc_cec_log_info("CEC service initialised");
}
/***********************************************************
* Name: vc_vchi_cec_stop
*
* Arguments:
* -
*
* Description: Stops the Host side part of CEC service
*
* Returns: -
*
***********************************************************/
VCHPRE_ void VCHPOST_ vc_vchi_cec_stop( void ) {
// Wait for the current lock-holder to finish before zapping TV service
uint32_t i;
if (!cecservice_client.initialised)
return;
if(lock_obtain() == 0)
{
void *dummy;
vchi_service_release(cecservice_client.client_handle[0]);
vc_cec_log_info("Stopping CEC service");
for (i=0; i < cecservice_client.num_connections; i++) {
int32_t result;
vchi_service_use(cecservice_client.client_handle[i]);
vchi_service_use(cecservice_client.notify_handle[i]);
result = vchi_service_close(cecservice_client.client_handle[i]);
vcos_assert( result == 0 );
result = vchi_service_close(cecservice_client.notify_handle[i]);
vcos_assert( result == 0 );
}
cecservice_client.initialised = 0;
lock_release();
cecservice_client.to_exit = 1;
vcos_event_signal(&cecservice_notify_available_event);
vcos_thread_join(&cecservice_notify_task, &dummy);
vcos_mutex_delete(&cecservice_client.lock);
vcos_event_delete(&cecservice_message_available_event);
vcos_event_delete(&cecservice_notify_available_event);
vcos_free(cecservice_client.topology);
vc_cec_log_info("CEC service stopped");
}
}
/***********************************************************
* Name: vc_cec_register_callaback
*
* Arguments:
* callback function, context to be passed when function is called
*
* Description: Register a callback function for all CEC notifications
*
* Returns: -
*
***********************************************************/
VCHPRE_ void VCHPOST_ vc_cec_register_callback(CECSERVICE_CALLBACK_T callback, void *callback_data) {
if(lock_obtain() == 0){
cecservice_client.notify_fn = callback;
cecservice_client.notify_data = callback_data;
vc_cec_log_info("CEC service registered callback 0x%x", (uint32_t) callback);
lock_release();
} else {
vc_cec_log_error("CEC service registered callback 0x%x failed", (uint32_t) callback);
}
}
/*********************************************************************************
*
* Static functions definitions
*
*********************************************************************************/
//TODO: Might need to handle multiple connections later
/***********************************************************
* Name: cecservice_client_callback
*
* Arguments: semaphore, callback reason and message handle
*
* Description: Callback when a message is available for CEC service
*
***********************************************************/
static void cecservice_client_callback( void *callback_param,
const VCHI_CALLBACK_REASON_T reason,
void *msg_handle ) {
VCOS_EVENT_T *event = (VCOS_EVENT_T *)callback_param;
if ( reason != VCHI_CALLBACK_MSG_AVAILABLE || event == NULL)
return;
vcos_event_signal(event);
}
/***********************************************************
* Name: cecservice_notify_callback
*
* Arguments: semaphore, callback reason and message handle
*
* Description: Callback when a message is available for CEC notify service
*
***********************************************************/
static void cecservice_notify_callback( void *callback_param,
const VCHI_CALLBACK_REASON_T reason,
void *msg_handle ) {
VCOS_EVENT_T *event = (VCOS_EVENT_T *)callback_param;
if ( reason != VCHI_CALLBACK_MSG_AVAILABLE || event == NULL)
return;
vcos_event_signal(event);
}
/***********************************************************
* Name: cecservice_wait_for_reply
*
* Arguments: response buffer, buffer length
*
* Description: blocked until something is in the buffer
*
* Returns zero if successful or error code of vchi otherwise (see vc_service_common_defs.h)
* If success, response is updated
*
***********************************************************/
static int32_t cecservice_wait_for_reply(void *response, uint32_t max_length) {
int32_t success = 0;
uint32_t length_read = 0;
do {
//TODO : we need to deal with messages coming through on more than one connections properly
//At the moment it will always try to read the first connection if there is something there
//Check if there is something in the queue, if so return immediately
//otherwise wait for the semaphore and read again
success = (int32_t) vchi2service_status(vchi_msg_dequeue( cecservice_client.client_handle[0], response, max_length, &length_read, VCHI_FLAGS_NONE ));
} while( length_read == 0 && vcos_event_wait(&cecservice_message_available_event) == VCOS_SUCCESS);
if(length_read) {
vc_cec_log_info("CEC service got reply %d bytes", length_read);
} else {
vc_cec_log_warn("CEC service wait for reply failed, error: %s",
vchi2service_status_string(success));
}
return success;
}
/***********************************************************
* Name: cecservice_wait_for_bulk_receive
*
* Arguments: response buffer, buffer length
*
* Description: blocked until bulk receive
*
* Returns error code of vchi
*
***********************************************************/
static int32_t cecservice_wait_for_bulk_receive(void *buffer, uint32_t max_length) {
if(!vcos_verify(buffer)) {
vc_cec_log_error("CEC: NULL buffer passed to wait_for_bulk_receive");
return -1;
}
return (int32_t) vchi2service_status(vchi_bulk_queue_receive( cecservice_client.client_handle[0],
buffer,
max_length,
VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE,
NULL ));
}
/***********************************************************
* Name: cecservice_send_command
*
* Arguments: command, parameter buffer, parameter legnth, has reply? (non-zero means yes)
*
* Description: send a command and optionally wait for its single value response (TV_GENERAL_RESP_T)
*
* Returns: < 0 if there is VCHI error, if tranmission is successful, value
* returned is the response from CEC server (which will be VC_CEC_ERROR_T (>= 0))
*
***********************************************************/
static int32_t cecservice_send_command( uint32_t command, const void *buffer, uint32_t length, uint32_t has_reply) {
VCHI_MSG_VECTOR_T vector[] = { {&command, sizeof(command)},
{buffer, length} };
int32_t success = 0;
int32_t response = -1;
vc_cec_log_info("CEC sending command %s length %d %s",
cecservice_command_strings[command], length,
(has_reply)? "has reply" : " no reply");
if(lock_obtain() == 0)
{
success = (int32_t) vchi2service_status(vchi_msg_queuev(cecservice_client.client_handle[0],
vector, sizeof(vector)/sizeof(vector[0]),
VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL ));
if(success == VC_SERVICE_VCHI_SUCCESS && has_reply) {
//otherwise only wait for a reply if we ask for one
success = cecservice_wait_for_reply(&response, sizeof(response));
if(success == VC_SERVICE_VCHI_SUCCESS) {
response = VC_VTOH32(response);
} else {
response = success;
}
} else {
if(success != VC_SERVICE_VCHI_SUCCESS)
vc_cec_log_error("CEC failed to send command %s length %d, error: %s",
cecservice_command_strings[command], length,
vchi2service_status_string(success));
//No reply expected or failed to send, send the success code back instead
response = success;
}
lock_release();
}
return response;
}
/***********************************************************
* Name: cecservice_send_command_reply
*
* Arguments: command, parameter buffer, parameter legnth, reply buffer, buffer length
*
* Description: send a command and wait for its non-single value response (in a buffer)
*
* Returns: error code, host app is responsible to do endian translation
*
***********************************************************/
static int32_t cecservice_send_command_reply( uint32_t command, void *buffer, uint32_t length,
void *response, uint32_t max_length) {
VCHI_MSG_VECTOR_T vector[] = { {&command, sizeof(command)},
{buffer, length} };
int32_t success = VC_SERVICE_VCHI_VCHIQ_ERROR, ret = 0;
vc_cec_log_info("CEC sending command (with reply) %s length %d",
cecservice_command_strings[command], length);
if(lock_obtain() == 0)
{
if((ret = vchi_msg_queuev( cecservice_client.client_handle[0],
vector, sizeof(vector)/sizeof(vector[0]),
VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL )) == VC_SERVICE_VCHI_SUCCESS) {
success = cecservice_wait_for_reply(response, max_length);
} else {
vc_cec_log_error("CEC failed to send command %s length %d, error code %d",
cecservice_command_strings[command], length, ret);
}
lock_release();
}
return success;
}
/***********************************************************
* Name: cecservice_notify_func
*
* Arguments: CEC service state
*
* Description: This is the notification task which receives all CEC
* service notifications
*
* Returns: does not return
*
***********************************************************/
static void *cecservice_notify_func(void *arg) {
int32_t success;
CECSERVICE_HOST_STATE_T *state = (CECSERVICE_HOST_STATE_T *) arg;
vc_cec_log_info("CEC service async thread started");
while(1) {
VCOS_STATUS_T status = vcos_event_wait(&cecservice_notify_available_event);
uint32_t cb_reason_str_idx = max_notify_strings - 1;
if(status != VCOS_SUCCESS || !state->initialised || state->to_exit)
break;
do {
uint32_t reason, param1, param2, param3, param4;
//Get all notifications in the queue
success = vchi_msg_dequeue( state->notify_handle[0], state->notify_buffer, sizeof(state->notify_buffer), &state->notify_length, VCHI_FLAGS_NONE );
if(success != 0 || state->notify_length < sizeof(uint32_t)*5 ) { //reason + 4x32-bit parameter
vcos_assert(state->notify_length == sizeof(uint32_t)*5);
break;
}
//if(lock_obtain() != 0)
// break;
//All notifications are of format: reason, param1, param2, param3, param4 (all 32-bit unsigned int)
reason = VC_VTOH32(state->notify_buffer[0]);
param1 = VC_VTOH32(state->notify_buffer[1]);
param2 = VC_VTOH32(state->notify_buffer[2]);
param3 = VC_VTOH32(state->notify_buffer[3]);
param4 = VC_VTOH32(state->notify_buffer[4]);
//lock_release();
//Store away physical/logical addresses
if(CEC_CB_REASON(reason) == VC_CEC_LOGICAL_ADDR) {
state->logical_address = (CEC_DEVICE_TYPE_T) param1;
state->physical_address = (uint16_t) (param2 & 0xFFFF);
}
switch(CEC_CB_REASON(reason)) {
case VC_CEC_NOTIFY_NONE:
cb_reason_str_idx = 0; break;
case VC_CEC_TX:
cb_reason_str_idx = 1; break;
case VC_CEC_RX:
cb_reason_str_idx = 2; break;
case VC_CEC_BUTTON_PRESSED:
cb_reason_str_idx = 3; break;
case VC_CEC_BUTTON_RELEASE:
cb_reason_str_idx = 4; break;
case VC_CEC_REMOTE_PRESSED:
cb_reason_str_idx = 5; break;
case VC_CEC_REMOTE_RELEASE:
cb_reason_str_idx = 6; break;
case VC_CEC_LOGICAL_ADDR:
cb_reason_str_idx = 7; break;
case VC_CEC_TOPOLOGY:
cb_reason_str_idx = 8; break;
case VC_CEC_LOGICAL_ADDR_LOST:
cb_reason_str_idx = 9; break;
}
vc_cec_log_info("CEC service callback [%s]: 0x%x, 0x%x, 0x%x, 0x%x",
cecservice_notify_strings[cb_reason_str_idx], param1, param2, param3, param4);
if(state->notify_fn) {
(*state->notify_fn)(state->notify_data, reason, param1, param2, param3, param4);
} else {
vc_cec_log_info("CEC service: No callback handler specified, callback [%s] swallowed",
cecservice_notify_strings[cb_reason_str_idx]);
}
} while(success == 0 && state->notify_length >= sizeof(uint32_t)*5); //read the next message if any
} //while (1)
if(state->to_exit)
vc_cec_log_info("CEC service async thread exiting");
return 0;
}
/***********************************************************
* Name: cecservice_logging_init
*
* Arguments: None
*
* Description: Initialise VCOS logging
*
* Returns: -
*
***********************************************************/
static void cecservice_logging_init() {
if(cecservice_log_initialised == 0) {
vcos_log_set_level(&cechost_log_category, VCOS_LOG_WARN);
vcos_log_register("cecservice-client", &cechost_log_category);
vc_cec_log_info("CEC HOST: log initialised");
cecservice_log_initialised = 1;
}
}
/***********************************************************
Actual CEC service API starts here
***********************************************************/
/***********************************************************
* Name: vc_cec_register_command
*
* Arguments:
* opcode to be registered
*
* Description
* Register an opcode to be forwarded as VC_CEC_RX notification
* The following opcode cannot be registered:
* <User Control Pressed>, <User Control Released>,
* <Vendor Remote Button Down>, <Vendor Remote Button Up>,
* <Feature Abort>, <Abort>
*
* Returns: if the command is successful (zero) or not (non-zero)
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_register_command(CEC_OPCODE_T opcode) {
int success = -1;
uint32_t param = VC_HTOV32(opcode);
success = cecservice_send_command( VC_CEC_REGISTER_CMD, ¶m, sizeof(param), 0);
return success;
}
/***********************************************************
* Name: vc_cec_register_all
*
* Arguments:
* None
*
* Description
* Register all commands except <Abort>
* Button presses/release will still be forwarded as
* BUTTON_PRESSED/BUTTON_RELEASE notifications
*
* Returns: if the command is successful (zero) or not (non-zero)
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_register_all( void ) {
return cecservice_send_command( VC_CEC_REGISTER_ALL, NULL, 0, 0);
}
/***********************************************************
* Name: vc_cec_deregister_command
*
* Arguments:
* opcode to be deregistered
*
* Description
* Deregister an opcode to be forwarded as VC_CEC_RX notification
* The following opcode cannot be deregistered:
* <User Control Pressed>, <User Control Released>,
* <Vendor Remote Button Down>, <Vendor Remote Button Up>,
* <Feature Abort>, <Abort>
*
* Returns: if the command is successful (zero) or not (non-zero)
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_deregister_command(CEC_OPCODE_T opcode) {
int success = -1;
uint32_t param = VC_HTOV32(opcode);
success = cecservice_send_command( VC_CEC_DEREGISTER_CMD, ¶m, sizeof(param), 0);
return success;
}
/***********************************************************
* Name: vc_cec_deregister_all
*
* Arguments:
* None
*
* Description
* Remove all commands to be forwarded. This does not affect
* the button presses which are always forwarded
*
* Returns: if the command is successful (zero) or not (non-zero)
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_deregister_all( void ) {
return cecservice_send_command( VC_CEC_DEREGISTER_ALL, NULL, 0, 0);
}
/***********************************************************
* Name: vc_cec_send_message
*
* Arguments:
* Follower's logical address
* Message payload WITHOUT the header byte (can be NULL)
* Payload length WITHOUT the header byte (can be zero)
* VC_TRUE if the message is a reply to an incoming message
* (For poll message set payload to NULL and length to zero)
*
* Description
* Remove all commands to be forwarded. This does not affect
* the button presses which are always forwarded
*
* Returns: if the command is successful (zero) or not (non-zero)
* If the command is successful, there will be a Tx callback
* in due course to indicate whether the message has been
* acknowledged by the recipient or not
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_message(const uint32_t follower,
const uint8_t *payload,
uint32_t length,
vcos_bool_t is_reply) {
int success = -1;
CEC_SEND_MSG_PARAM_T param;
if(!vcos_verify(length <= CEC_MAX_XMIT_LENGTH))
return -1;
param.follower = VC_HTOV32(follower);
param.length = VC_HTOV32(length);
param.is_reply = VC_HTOV32(is_reply);
vcos_memset(param.payload, 0, sizeof(param.payload));
vc_cec_log_info("CEC service sending CEC message (%d->%d) (0x%02X) length %d%s",
cecservice_client.logical_address, follower,
(payload)? payload[0] : 0xFF, length, (is_reply)? " as reply" : "");
if(length > 0 && vcos_verify(payload)) {
char s[96] = {0}, *p = &s[0];
int i;
vcos_memcpy(param.payload, payload, _min(length, CEC_MAX_XMIT_LENGTH));
p += sprintf(p, "0x%02X", (cecservice_client.logical_address << 4) | (follower & 0xF));
for(i = 0; i < _min(length, CEC_MAX_XMIT_LENGTH); i++) {
p += sprintf(p, " %02X", payload[i]);
}
vc_cec_log_info("CEC message: %s", s);
}
success = cecservice_send_command( VC_CEC_SEND_MSG, ¶m, sizeof(param), 1);
return success;
}
/***********************************************************
* Name: vc_cec_get_logical_address
*
* Arguments:
* pointer to logical address
*
* Description
* Get the logical address, if one is being allocated
* 0xF (unregistered) will be returned
*
* Returns: if the command is successful (zero) or not (non-zero)
* logical_address is not modified if command failed
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_get_logical_address(CEC_AllDevices_T *logical_address) {
uint32_t response;
int32_t success = cecservice_send_command_reply( VC_CEC_GET_LOGICAL_ADDR, NULL, 0,
&response, sizeof(response));
if(success == 0) {
*logical_address = (CEC_AllDevices_T)(VC_VTOH32(response) & 0xF);
vc_cec_log_info("CEC got logical address %d", *logical_address);
}
return success;
}
/***********************************************************
* Name: vc_cec_alloc_logical_address
*
* Arguments:
* None
*
* Description
* Start the allocation of a logical address. The host only
* needs to call this if the initial allocation failed
* (logical address being 0xF and physical address is NOT 0xFFFF
* from VC_CEC_LOGICAL_ADDR notification), or if the host explicitly
* released its logical address.
*
* Returns: if the command is successful (zero) or not (non-zero)
* If successful, there will be a callback notification
* VC_CEC_LOGICAL_ADDR. The host should wait for this before
* calling this function again.
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_alloc_logical_address( void ) {
return cecservice_send_command( VC_CEC_ALLOC_LOGICAL_ADDR, NULL, 0, 0);
}
/***********************************************************
* Name: vc_cec_release_logical_address
*
* Arguments:
* None
*
* Description
* Release our logical address. This effectively disables CEC.
* The host will need to allocate a new logical address before
* doing any CEC calls (send/receive message, get topology, etc.).
*
* Returns: if the command is successful (zero) or not (non-zero)
* The host should get a callback VC_CEC_LOGICAL_ADDR with
* 0xF being the logical address and 0xFFFF being the physical address.
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_release_logical_address( void ) {
return cecservice_send_command( VC_CEC_RELEASE_LOGICAL_ADDR, NULL, 0, 0);
}
/***********************************************************
* Name: vc_cec_get_topology
*
* Arguments:
* pointer to topology struct
*
* Description
* Get the topology
*
* Returns: if the command is successful (zero) or not (non-zero)
* If successful, the topology will be set, otherwise it is unchanged
* A topology with 1 device (us) means CEC is not supported
* If there is no topology available, this also returns a failure.
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_get_topology( VC_CEC_TOPOLOGY_T* topology) {
int32_t success = -1;
vchi_service_use(cecservice_client.client_handle[0]);
success = cecservice_send_command( VC_CEC_GET_TOPOLOGY, NULL, 0, 1);
if(success == 0) {
success = cecservice_wait_for_bulk_receive(cecservice_client.topology, sizeof(VC_CEC_TOPOLOGY_T));
}
vchi_service_release(cecservice_client.client_handle[0]);
if(success == 0) {
int i;
cecservice_client.topology->active_mask = VC_VTOH16(cecservice_client.topology->active_mask);
cecservice_client.topology->num_devices = VC_VTOH16(cecservice_client.topology->num_devices);
vc_cec_log_info("CEC topology: mask=0x%x; #device=%d",
cecservice_client.topology->active_mask,
cecservice_client.topology->num_devices);
for(i = 0; i < 15; i++) {
cecservice_client.topology->device_attr[i] = VC_VTOH32(cecservice_client.topology->device_attr[i]);
}
vcos_memcpy(topology, cecservice_client.topology, sizeof(VC_CEC_TOPOLOGY_T));
}
return success;
}
/***********************************************************
* Name: vc_cec_set_vendor_id
*
* Arguments:
* 24-bit IEEE vendor id
*
* Description
* Set the response to <Give Device Vendor ID>
*
* Returns: if the command is successful (zero) or not (non-zero)
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_set_vendor_id( uint32_t id ) {
uint32_t vendor_id = VC_HTOV32(id);
vc_cec_log_info("CEC setting vendor id to 0x%x", vendor_id);
return cecservice_send_command( VC_CEC_SET_VENDOR_ID, &vendor_id, sizeof(vendor_id), 0);
}
/***********************************************************
* Name: vc_cec_set_osd_name
*
* Arguments:
* OSD name (14 byte array)
*
* Description
* Set the response to <Give OSD Name>
*
* Returns: if the command is successful (zero) or not (non-zero)
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_set_osd_name( const char* name ) {
vc_cec_log_info("CEC setting OSD name to %s", name);
return cecservice_send_command( VC_CEC_SET_OSD_NAME, name, OSD_NAME_LENGTH, 0);
}
/***********************************************************
* Name: vc_cec_get_physical_address
*
* Arguments:
* pointer to physical address (returned as 16-bit packed value)
*
* Description
* Get the physical address
*
* Returns: if the command is successful (zero) or not (non-zero)
* If failed, physical address argument will not be changed
* A physical address of 0xFFFF means CEC is not supported
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_get_physical_address(uint16_t *physical_address) {
uint32_t response;
int32_t success = cecservice_send_command_reply( VC_CEC_GET_PHYSICAL_ADDR, NULL, 0,
&response, sizeof(response));
if(success == 0) {
*physical_address = (uint16_t)(VC_VTOH32(response) & 0xFFFF);
vc_cec_log_info("CEC got physical address: %d.%d.%d.%d",
(*physical_address >> 12), (*physical_address >> 8) & 0xF,
(*physical_address >> 4) & 0xF, (*physical_address) & 0xF);
}
return success;
}
/***********************************************************
* Name: vc_cec_get_vendor_id
*
* Arguments:
* logical address [in]
* pointer to 24-bit IEEE vendor id [out]
*
* Description
* Get the vendor ID of the device with the said logical address
* Application should send <Give Device Vendor ID> if vendor ID
* is not known (and register opcode <Device Vendor ID>)
*
* Returns: if the command is successful (zero) or not (non-zero)
* vendor ID is set to zero if unknown or 0xFFFFFF if
* device does not exist.
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_get_vendor_id( const CEC_AllDevices_T logical_address, uint32_t *vendor_id) {
uint32_t log_addr = VC_HTOV32(logical_address);
uint32_t response;
int32_t success = cecservice_send_command_reply( VC_CEC_GET_VENDOR_ID, &log_addr, sizeof(log_addr),
&response, sizeof(response));
if(success == 0) {
vcos_assert(vendor_id);
*vendor_id = VC_VTOH32(response);
vc_cec_log_info("CEC got vendor id 0x%X", *vendor_id);
}
return success;
}
/***********************************************************
* Name: vc_cec_device_type
*
* Arguments:
* logical address [in]
*
* Description
* Get the default device type of a logical address
* Logical address 12 to 14 cannot be used
*
* Returns: For logical addresses 0-11 the default
* device type of that address will be returned
* logical address 12-14 will return "reserved" type.
*
***********************************************************/
VCHPRE_ CEC_DEVICE_TYPE_T VCHPOST_ vc_cec_device_type(const CEC_AllDevices_T logical_address) {
CEC_DEVICE_TYPE_T device_type = CEC_DeviceType_Invalid;
switch(logical_address) {
case CEC_AllDevices_eSTB1:
case CEC_AllDevices_eSTB2:
case CEC_AllDevices_eSTB3:
case CEC_AllDevices_eSTB4:
device_type = CEC_DeviceType_Tuner;
break;
case CEC_AllDevices_eDVD1:
case CEC_AllDevices_eDVD2:
case CEC_AllDevices_eDVD3:
device_type = CEC_DeviceType_Playback;
break;
case CEC_AllDevices_eRec1:
case CEC_AllDevices_eRec2:
case CEC_AllDevices_eRec3:
device_type = CEC_DeviceType_Rec;
break;
case CEC_AllDevices_eAudioSystem:
device_type = CEC_DeviceType_Audio;
break;
case CEC_AllDevices_eTV:
device_type = CEC_DeviceType_TV;
break;
case CEC_AllDevices_eRsvd3:
case CEC_AllDevices_eRsvd4:
case CEC_AllDevices_eFreeUse:
device_type = CEC_DeviceType_Reserved; //XXX: Are we allowed to use this?
break;
default:
vcos_assert(0); //Invalid
break;
}
return device_type;
}
/***********************************************************
* Name: vc_cec_send_message2
*
* Arguments:
* pointer to encapsulated message
*
* Description
* Call vc_cec_send_message above
* messages are always sent as non-reply
*
* Returns: if the command is successful (zero) or not (non-zero)
* If the command is successful, there will be a Tx callback
* in due course to indicate whether the message has been
* acknowledged by the recipient or not
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_message2(const VC_CEC_MESSAGE_T *message) {
if(vcos_verify(message)) {
return vc_cec_send_message(message->follower,
(message->length)?
message->payload : NULL,
message->length,
VC_FALSE);
} else {
return -1;
}
}
/***********************************************************
* Name: vc_cec_param2message
*
* Arguments:
* arguments from CEC callback (reason, param1 to param4)
* pointer to VC_CEC_MESSAGE_T
*
* Description
* Turn the CEC_TX/CEC_RX/BUTTON_PRESS/BUTTON_RELEASE
* callback parameters back into an encapsulated form
*
* Returns: zero normally
* non-zero if something has gone wrong
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_param2message( const uint32_t reason, const uint32_t param1,
const uint32_t param2, const uint32_t param3,
const uint32_t param4, VC_CEC_MESSAGE_T *message) {
if(vcos_verify(message &&
CEC_CB_REASON(reason) != VC_CEC_LOGICAL_ADDR &&
CEC_CB_REASON(reason) != VC_CEC_TOPOLOGY)) {
message->length = CEC_CB_MSG_LENGTH(reason) - 1; //Length is without the header byte
message->initiator = CEC_CB_INITIATOR(param1);
message->follower = CEC_CB_FOLLOWER(param1);
if(message->length) {
uint32_t tmp = param1 >> 8;
vcos_memcpy(message->payload, &tmp, sizeof(uint32_t)-1);
vcos_memcpy(message->payload+sizeof(uint32_t)-1, ¶m2, sizeof(uint32_t));
vcos_memcpy(message->payload+sizeof(uint32_t)*2-1, ¶m3, sizeof(uint32_t));
vcos_memcpy(message->payload+sizeof(uint32_t)*3-1, ¶m4, sizeof(uint32_t));
} else {
vcos_memset(message->payload, 0, sizeof(message->payload));
}
return 0;
} else {
return -1;
}
}
//Extra API if CEC is running in passive mode
/***********************************************************
* Name: vc_cec_poll_address
*
* Arguments:
* logical address to try
*
* Description
* Sets and polls a particular address to find out
* its availability in the CEC network. Only available
* when CEC is running in passive mode. The host can
* only call this function during logical address allocation stage.
*
* Returns: 0 if poll is successful (address is occupied)
* >0 if poll is unsuccessful (address is free if error code is VC_CEC_ERROR_NO_ACK)
* <0 other (VCHI) errors
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_poll_address(const CEC_AllDevices_T logical_address) {
uint32_t log_addr = VC_HTOV32(logical_address);
int32_t response = VC_CEC_ERROR_INVALID_ARGUMENT;
int32_t success = -1;
vc_cec_log_info("CEC polling address %d", logical_address);
success = cecservice_send_command_reply( VC_CEC_POLL_ADDR, &log_addr, sizeof(log_addr),
&response, sizeof(response));
return (success == 0)? response : success;
}
/***********************************************************
* Name: vc_cec_set_logical_address
*
* Arguments:
* logical address, device type, vendor id
*
* Description
* sets the logical address, device type and vendor ID to be in use.
* Only available when CEC is running in passive mode. It is the
* responsibility of the host to make sure the logical address
* is actually free (see vc_cec_poll_address). Physical address used
* will be what is read from EDID and cannot be set.
*
* Returns: 0 if successful, non-zero otherwise
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_set_logical_address(const CEC_AllDevices_T logical_address,
const CEC_DEVICE_TYPE_T device_type,
const uint32_t vendor_id) {
CEC_SET_LOGICAL_ADDR_PARAM_T param = {VC_HTOV32(logical_address),
VC_HTOV32(device_type),
VC_HTOV32(vendor_id)};
int32_t response = VC_CEC_ERROR_INVALID_ARGUMENT;
int32_t success = VC_CEC_ERROR_INVALID_ARGUMENT;
if(vcos_verify(logical_address <= CEC_AllDevices_eUnRegistered &&
(device_type <= CEC_DeviceType_VidProc ||
device_type == CEC_DeviceType_Invalid))) {
vc_cec_log_info("CEC setting logical address to %d; device type %s; vendor 0x%X",
logical_address,
cecservice_devicetype_strings[device_type], vendor_id );
success = cecservice_send_command_reply( VC_CEC_SET_LOGICAL_ADDR, ¶m, sizeof(param),
&response, sizeof(response));
} else {
vc_cec_log_error("CEC invalid arguments for set_logical_address");
}
return (success == 0)? response : success;
}
/***********************************************************
* Name: vc_cec_add_device
*
* Arguments:
* logical address, physical address, device type, whether this is the last device
*
* Description
* Adds a new device to topology. Only available when CEC
* is running in passive mode. Device will be automatically
* removed from topology if a failed xmit is detected. If
* last_device is true, it will trigger a topology computation
* (and may trigger a topology callback).
*
* Returns: 0 if successful, non-zero otherwise
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_add_device(const CEC_AllDevices_T logical_address,
const uint16_t physical_address,
const CEC_DEVICE_TYPE_T device_type,
vcos_bool_t last_device) {
CEC_ADD_DEVICE_PARAM_T param = {VC_HTOV32(logical_address),
VC_HTOV32(physical_address),
VC_HTOV32(device_type),
VC_HTOV32(last_device)};
int32_t response = VC_CEC_ERROR_INVALID_ARGUMENT;
int32_t success = VC_CEC_ERROR_INVALID_ARGUMENT;
if(vcos_verify(logical_address <= CEC_AllDevices_eUnRegistered &&
(device_type <= CEC_DeviceType_VidProc ||
device_type == CEC_DeviceType_Invalid))) {
vc_cec_log_info("CEC adding device %d (0x%X); device type %s",
logical_address, physical_address,
cecservice_devicetype_strings[device_type]);
success = cecservice_send_command_reply( VC_CEC_ADD_DEVICE, ¶m, sizeof(param),
&response, sizeof(response));
} else {
vc_cec_log_error("CEC invalid arguments for add_device");
}
return (success == 0)? response : success;
}
/***********************************************************
* Name: vc_cec_set_passive
*
* Arguments:
* Enable/disable (TRUE to enable/ FALSE to disable)
*
* Description
* Enable / disable CEC passive mode
*
* Returns: 0 if successful, non-zero otherwise
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_set_passive(vcos_bool_t enabled) {
uint32_t param = VC_HTOV32(enabled);
int32_t response;
int32_t success = cecservice_send_command_reply( VC_CEC_SET_PASSIVE, ¶m, sizeof(param),
&response, sizeof(response));
return (success == 0)? response : success;
}
/***********************************************************
API for some common CEC messages, uses the API above to
actually send the message
***********************************************************/
/***********************************************************
* Name: vc_cec_send_FeatureAbort
*
* Arguments:
* follower, rejected opcode, reject reason, reply or not
*
* Description
* send <Feature Abort> for a received command
*
* Returns: if the command is successful (zero) or not (non-zero)
* Tx callback if successful
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_FeatureAbort(uint32_t follower,
CEC_OPCODE_T opcode,
CEC_ABORT_REASON_T reason) {
uint8_t tx_buf[3];
tx_buf[0] = CEC_Opcode_FeatureAbort; // <Feature Abort>
tx_buf[1] = opcode;
tx_buf[2] = reason;
return vc_cec_send_message(follower,
tx_buf,
sizeof(tx_buf),
VC_TRUE);
}
/***********************************************************
* Name: vc_cec_send_ActiveSource
*
* Arguments:
* physical address, reply or not
*
* Description
* send <Active Source>
*
* Returns: if the command is successful (zero) or not (non-zero)
* Tx callback if successful
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_ActiveSource(uint16_t physical_address,
vcos_bool_t is_reply) {
uint8_t tx_buf[3];
tx_buf[0] = CEC_Opcode_ActiveSource; // <Active Source>
tx_buf[1] = physical_address >> 8; // physical address msb
tx_buf[2] = physical_address & 0x00FF; // physical address lsb
return vc_cec_send_message(CEC_BROADCAST_ADDR, // This is a broadcast only message
tx_buf,
sizeof(tx_buf),
is_reply);
}
/***********************************************************
* Name: vc_cec_send_ImageViewOn
*
* Arguments:
* follower, reply or not
* Description
* send <Image View On>
*
* Returns: if the command is successful (zero) or not (non-zero)
* Tx callback if successful
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_ImageViewOn(uint32_t follower,
vcos_bool_t is_reply) {
uint8_t tx_buf[1];
tx_buf[0] = CEC_Opcode_ImageViewOn; // <Image View On> no param required
return vc_cec_send_message(follower,
tx_buf,
sizeof(tx_buf),
is_reply);
}
/***********************************************************
* Name: vc_cec_send_SetOSDString
*
* Arguments:
* follower, display control, string (char[13]), reply or not
*
* Description
* send <Image View On>
*
* Returns: if the command is successful (zero) or not (non-zero)
* Tx callback if successful
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_SetOSDString(uint32_t follower,
CEC_DISPLAY_CONTROL_T disp_ctrl,
const char* string,
vcos_bool_t is_reply) {
uint8_t tx_buf[CEC_MAX_XMIT_LENGTH];
tx_buf[0] = CEC_Opcode_SetOSDString; // <Set OSD String>
tx_buf[1] = disp_ctrl;
vcos_memset(&tx_buf[2], 0, sizeof(tx_buf)-2);
vcos_memcpy(&tx_buf[2], string, _min(strlen(string), CEC_MAX_XMIT_LENGTH-2));
return vc_cec_send_message(follower,
tx_buf,
sizeof(tx_buf),
is_reply);
}
/***********************************************************
* Name: vc_cec_send_Standby
*
* Arguments:
* follower, reply or not
*
* Description
* send <Standby>. Turn other devices to standby
*
* Returns: if the command is successful (zero) or not (non-zero)
* Tx callback if successful
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_Standby(uint32_t follower, vcos_bool_t is_reply) {
uint8_t tx_buf[1];
tx_buf[0] = CEC_Opcode_Standby; // <Standby>
return vc_cec_send_message(follower,
tx_buf,
sizeof(tx_buf),
is_reply);
}
/***********************************************************
* Name: vc_cec_send_MenuStatus
*
* Arguments:
* follower, menu state, reply or not
*
* Description
* send <Menu Status> (response to <Menu Request>)
* menu state is either CEC_MENU_STATE_ACTIVATED or CEC_MENU_STATE_DEACTIVATED
*
* Returns: if the command is successful (zero) or not (non-zero)
* Tx callback if successful
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_MenuStatus(uint32_t follower,
CEC_MENU_STATE_T menu_state,
vcos_bool_t is_reply) {
uint8_t tx_buf[2];
if(!vcos_verify(menu_state < CEC_MENU_STATE_QUERY))
return -1;
tx_buf[0] = CEC_Opcode_MenuStatus; // <Menu Status>
tx_buf[1] = menu_state;
return vc_cec_send_message(follower,
tx_buf,
sizeof(tx_buf),
is_reply);
}
/***********************************************************
* Name: vc_cec_send_ReportPhysicalAddress
*
* Arguments:
* physical address, device type, reply or not
*
* Description
* send <Report Physical Address> (first command to be
* sent after a successful logical address allocation
* device type should be the appropriate one for
* the allocated logical address
*
* Returns: if the command is successful (zero) or not (non-zero)
* Tx callback if successful. We also get a failure
* if we do not currently have a valid physical address
***********************************************************/
VCHPRE_ int VCHPOST_ vc_cec_send_ReportPhysicalAddress(uint16_t physical_address,
CEC_DEVICE_TYPE_T device_type,
vcos_bool_t is_reply) {
uint8_t tx_buf[4];
if(vcos_verify(physical_address == cecservice_client.physical_address &&
cecservice_client.physical_address != CEC_CLEAR_ADDR)) {
tx_buf[0] = CEC_Opcode_ReportPhysicalAddress;
tx_buf[1] = physical_address >> 8; // physical address msb
tx_buf[2] = physical_address & 0x00FF; // physical address lsb
tx_buf[3] = device_type; // 'device type'
return vc_cec_send_message(CEC_BROADCAST_ADDR, // This is a broadcast only message
tx_buf,
sizeof(tx_buf),
is_reply);
} else {
//Current we do not allow sending a random physical address
vc_cec_log_error("CEC cannot send physical address 0x%X, does not match internal 0x%X",
physical_address, cecservice_client.physical_address);
return VC_CEC_ERROR_NO_PA;
}
}
| 40.635974 | 155 | 0.576716 | [
"vector"
] |
85d315e022687a0afa74e590609df53a55614f0e | 4,935 | c | C | src/renderer.c | Df458/Cloudy-Climb | 24de95fbe677475edf48a2b022275184c77f3002 | [
"Zlib"
] | null | null | null | src/renderer.c | Df458/Cloudy-Climb | 24de95fbe677475edf48a2b022275184c77f3002 | [
"Zlib"
] | null | null | null | src/renderer.c | Df458/Cloudy-Climb | 24de95fbe677475edf48a2b022275184c77f3002 | [
"Zlib"
] | null | null | null | #include "renderer.h"
#include "camera.h"
#include "check.h"
#include "data_loader.h"
#include "debug_draw.h"
#include "graphics_log.h"
#include "matrix.h"
#include "mesh.h"
#include "paths.h"
#include "renderpass.h"
#include "shader_init.h"
#include "shader.h"
#include "texture_loader.h"
#include "vector.h"
#include "window.h"
#include <GL/glew.h>
#include <GL/gl.h>
shader s_default;
static shader s_transition;
static renderpass transition_pass = NULL;
static gltex t_transition;
extern camera c_main;
extern camera c_ui;
static const vec4 transition_color = { .r = 34.0f/256.0f, .g = 32.0f/256.0f, .b = 52.0f/256.0f, .a = 1.0f};
void init_renderer(void* window) {
// ------------------------------------------------
glewExperimental = 1;
check_kill(glewInit() == GLEW_OK, "Failed to initialize GLEW");
if(!check_error(glewIsExtensionSupported("GL_ARB_debug_output"), "Graphics debug logging is not available for your hardware. Graphical errors will not be reported")) {
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(graphics_log, NULL);
GLuint VAO; // Setup default VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
// ------------------------------------------------
shaders_init();
s_default = shader_basic_tex_get();
char* path = assets_path("transition.vert", NULL);
char* vert = (char*)load_data_buffer(path, NULL);
sfree(path);
path = assets_path("transition.frag", NULL);
char* frag = (char*)load_data_buffer(path, NULL);
sfree(path);
s_transition = shader_new_vf((const char**)&vert, (const char**)&frag);
path = assets_path("Transition.png", NULL);
t_transition = load_texture_gl(path);
sfree(path);
vec2 v = get_window_dims(window);
transition_pass = renderpass_new(vec2_decomp(v));
}
void cleanup_renderer() {
renderpass_free(transition_pass);
glDeleteProgram(s_transition.id);
}
void begin_frame() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderpass_start(transition_pass);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void end_frame(float transition_time) {
glUseProgram(s_transition.id);
shader_bind_uniform_name(s_transition, "u_time", transition_time * 2);
shader_bind_uniform_name(s_transition, "u_transition_color", transition_color);
shader_bind_uniform_texture_name(s_transition, "u_transition_texture", t_transition, GL_TEXTURE1);
renderpass_next(NULL, s_transition);
}
void draw_texture(mat4 m, gltex t, vec4 c) {
glUseProgram(s_default.id);
vec2 dims = { .x = t.width * 2, .y = t.height * 2 };
shader_bind_uniform_name(s_default, "u_color", c);
shader_bind_uniform_name(s_default, "u_transform", mat4_mul(camera_get_vp(c_main), mat4_scale(m, dims)));
shader_bind_uniform_texture_name(s_default, "u_texture", t, GL_TEXTURE0);
mesh_render(s_default, mesh_quad(), GL_TRIANGLES, "i_pos", VT_POSITION, "i_uv", VT_TEXTURE);
}
void draw_texture_ui(mat4 m, gltex t, vec4 c) {
glUseProgram(s_default.id);
vec2 dims = { .x = t.width * 2, .y = t.height * 2 };
shader_bind_uniform_name(s_default, "u_color", c);
shader_bind_uniform_name(s_default, "u_transform", mat4_mul(camera_get_vp(c_ui), mat4_scale(m, dims)));
shader_bind_uniform_texture_name(s_default, "u_texture", t, GL_TEXTURE0);
mesh_render(s_default, mesh_quad(), GL_TRIANGLES, "i_pos", VT_POSITION, "i_uv", VT_TEXTURE);
}
void draw_text(vec3 p, text t, vec4 c) {
glUseProgram(s_default.id);
shader_bind_uniform_name(s_default, "u_color", c);
text_draw(t, s_default, mat4_mul(camera_get_vp(c_ui), mat4_translate(mat4_ident, p)));
}
void draw_sprite(mat4 m, sprite spr, vec4 c) {
glUseProgram(s_default.id);
shader_bind_uniform_name(s_default, "u_color", c);
vec2 dims = { .x = 2, .y = 2 };
sprite_draw(spr, s_default, mat4_scale(m, dims), camera_get_vp(c_main));
}
void draw_debug_rect(aabb_2d rect, vec4 color) {
#ifdef BUILD_EDITOR
vt_pc ul = (vt_pc){ .position = { .x = rect.position.x, .y = rect.position.y }, .color = color};
vt_pc ur = (vt_pc){ .position = { .x = rect.position.x + rect.dimensions.x, .y = rect.position.y }, .color = color};
vt_pc bl = (vt_pc){ .position = { .x = rect.position.x, .y = rect.position.y + rect.dimensions.y }, .color = color};
vt_pc br = (vt_pc){ .position = { .x = rect.position.x + rect.dimensions.x, .y = rect.position.y + rect.dimensions.y }, .color = color};
debug_draw_line(camera_get_vp(c_main), ul, ur, 2);
debug_draw_line(camera_get_vp(c_main), ur, br, 2);
debug_draw_line(camera_get_vp(c_main), bl, br, 2);
debug_draw_line(camera_get_vp(c_main), ul, bl, 2);
#endif
}
mat4 get_camera_matrix() {
return camera_get_vp(c_main);
}
| 36.828358 | 171 | 0.690578 | [
"mesh",
"vector"
] |
85db45cb3dfc6ee933cff4a0dd2d2a6726b76f6d | 10,624 | h | C | src/game.h | Joshua1337/letvezi | f3d7e792896fdd0c62b801e0c6e400b654ab3ae2 | [
"MIT"
] | 4 | 2015-11-27T14:31:49.000Z | 2015-12-18T02:41:56.000Z | src/game.h | Joshua1337/letvezi | f3d7e792896fdd0c62b801e0c6e400b654ab3ae2 | [
"MIT"
] | 4 | 2015-12-07T13:33:32.000Z | 2015-12-22T01:32:42.000Z | src/game.h | Joshua1337/letvezi | f3d7e792896fdd0c62b801e0c6e400b654ab3ae2 | [
"MIT"
] | 3 | 2015-11-27T14:45:45.000Z | 2020-06-05T22:02:28.000Z | #pragma once
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
#include <map>
#include <thread>
#include <future>
#include <mutex>
#include <stdexcept>
#include <boost/optional.hpp>
#include "conc.h"
#include "timer.h"
namespace Game {
/*
load_png("bg_star" , "art/img/bg_star.png" );
load_png("player" , "art/img/player.png" );
load_png("player_laser" , "art/img/player_laser.png" );
load_png("player_life" , "art/img/player_life.png" );
load_png("player_shield" , "art/img/player_shield.png" );
load_png("enemy_1" , "art/img/enemy_1.png" );
load_png("enemy_2" , "art/img/enemy_2.png" );
load_png("enemy_3" , "art/img/enemy_3.png" );
load_png("enemy_boss" , "art/img/enemy_boss.png" );
load_png("enemy_laser" , "art/img/enemy_laser.png" );
load_png("enemy_boss_laser", "art/img/enemy_boss_laser.png" );
load_png("enemy_boss_squad", "art/img/enemy_boss_squad.png" );
load_png("powerup_shield" , "art/img/powerup_shield.png" );
load_png("powerup_bolt" , "art/img/powerup_bolt.png" );
load_sfx("player_laser" , "art/sfx/player_laser.ogg" );
load_sfx("shield_enabled" , "art/sfx/player_laser.ogg" );
*/
enum TextureID {
TEX_BackgroundStar = 0x01,
TEX_Player = 0x10,
TEX_PlayerLaser = 0x11,
TEX_PlayerLife = 0x12,
TEX_PlayerShield = 0x13,
TEX_Enemy1 = 0x21,
TEX_Enemy2 = 0x22,
TEX_Enemy3 = 0x23,
TEX_EnemyBoss = 0x25,
TEX_EnemyBossSquad = 0x26,
TEX_EnemyLaser = 0x28,
TEX_EnemyBossLaser = 0x29,
TEX_PowerupShield = 0x31,
TEX_PowerupBolt = 0x32,
};
enum SFX_ID {
SFX_PlayerLaser = 0x01,
SFX_ShieldEnabled = 0x02
};
class SDLError: public std::runtime_error {
private:
std::string info;
public:
SDLError(std::string x)
: std::runtime_error("SDL Error")
{ info = x; }
SDLError(const char* x)
: std::runtime_error("SDL Error")
{ info = x; }
SDLError()
: std::runtime_error("SDL Error")
{ info = SDL_GetError(); }
virtual const char* what() const throw() {
return info.c_str();
}
};
enum LSit {
KeepLooping,
BreakLoop,
};
enum FontID {
Small ,
Normal ,
Huge
};
struct Resolution {
int16_t width;
int16_t height;
Resolution(int16_t width, int16_t height) : width(width), height(height) {}
};
struct TextureInfo {
SDL_Texture* texture;
int width;
int height;
TextureInfo(SDL_Texture* txt, int width, int height) : texture(txt), width(width), height(height) {}
TextureInfo() : texture(NULL), width(0), height(0) {}
};
namespace Utils {
template <typename FN>
auto tempo(uint32_t expected_time_loop, FN&& fn) {
auto debt = std::chrono::milliseconds(0);
while(true) {
auto t_start = std::chrono::steady_clock::now();
Game::LSit x = fn(expected_time_loop, debt);
switch(x) {
case BreakLoop: return;
break;
default: break;
}
auto t_finish = std::chrono::steady_clock::now();
auto dif = std::chrono::duration_cast<std::chrono::milliseconds>(t_finish - t_start);
auto sleep_time = std::chrono::milliseconds(expected_time_loop) - dif;
debt = debt / 2;
if (sleep_time >= std::chrono::milliseconds(0)) {
std::this_thread::sleep_for(sleep_time + std::chrono::milliseconds(1));
} else {
/* if we are here, that means we have got a negative sleep time
* iow, we need to "advance" more in the next frame to make up for the slow frame we had previously
*/
debt = -sleep_time;
}
};
};
};
class sdl_info {
private:
uint16_t fps = 60; /* fps >= 0 */
std::map<TextureID, TextureInfo> txts;
std::map<FontID,TTF_Font*> fonts;
std::map<SFX_ID, Mix_Chunk*> sfx;
std::string gm_name;
Mix_Music* music;
public:
SDL_Window* window = NULL;
SDL_Renderer* win_renderer = NULL;
Timer tim;
sdl_info(const char* game_name, std::string font_name,int fps_param=60);
sdl_info(const sdl_info&) = delete;
sdl_info& operator=(const sdl_info&) = delete;
~sdl_info();
Resolution get_current_res();
void set_background(std::string bg_name);
void load_png(TextureID key, std::string path);
void load_sfx(SFX_ID key, std::string path);
void play_sfx(SFX_ID key);
template <typename FN>
void loading_screen(FN&& fn) {
using LoadCB = std::tuple<std::string,std::function<void(sdl_info&)>>;
Resolution res = get_current_res();
int start_y = res.height/4;
int finish_y = 3 * start_y;
int current_y = start_y;
int accel = 32;
std::queue<LoadCB> chan;
fn(chan);
while (1) {
SDL_SetRenderDrawColor(win_renderer, 0, 0, 0, 255);
SDL_RenderClear(win_renderer);
SDL_Color color = {255, 0, 255, 255};
render_text(res.width/4, res.height/4, Huge, color, gm_name);
render_text(res.width/4, res.height/2, Normal, color, "Loading game");
render_text(4*(res.width/5), current_y, Small, color, "~");
if (current_y > finish_y || current_y < start_y) accel *= -1;
current_y += accel;
if (chan.size() == 0) break;
LoadCB x = chan.front();
chan.pop();
render_text(res.width/3, 4*(res.height/5), Normal, color, std::get<0>(x));
SDL_RenderPresent(win_renderer);
{
auto t_start = std::chrono::steady_clock::now();
(std::get<1>(x))(*this);
auto t_finish = std::chrono::steady_clock::now();
auto diff = t_finish - t_start;
std::this_thread::sleep_for(std::chrono::milliseconds(16) - diff);
};
};
SDL_SetRenderDrawColor(win_renderer, 0, 0, 0, 255);
SDL_RenderClear(win_renderer);
SDL_RenderPresent(win_renderer);
std::cout << "Game loaded" << std::endl;
};
void render_text(int x, int y, FontID f_id, SDL_Color txt_color, std::string text);
template <typename F>
auto with(TextureID key, F&& fn) {
auto it = txts.find(key);
if (it == txts.end()) { throw SDLError("with TextureID couldn't find texture, did you load all the resources?"); }
auto surf = it->second;
/* we use .at as if it didn't exist, we already threw a nice error message */
return fn(surf);
}
const std::map<TextureID,TextureInfo>& textures() {
return txts;
}
/* the second parameter of render_handled specifies the proportion of a second it should work with
* e.g. x being 1000 represents it has to "process" a whole second of time
* x is represented in ms
*/
template <typename EV, typename S>
void loop(std::function<void(Conc::Chan<SDL_Event>&,Conc::Chan<EV>&)> event_handler ,
std::function<void(Conc::Chan<EV>&,Conc::VarL<S>&)> gs_handler ,
std::function<void(Conc::VarL<S>&)> expensive_fn ,
std::function<LSit(Conc::VarL<S>&,uint16_t)> render_handler ,
S start_state) {
Conc::Chan<SDL_Event> sdl_events;
Conc::Chan<EV> game_events;
Conc::VarL<S> game_state(start_state);
/* the basic idea is:
* > the event_handler converts [or ignores] SDL_Events into "Game Events" (GEVs)
* > GEVs are processed by the GS handler, which will update the game state
* >> the core idea behind this, is that the game states will be minimal and
* won't care about things like acceleration or similar
* > the render handler, shouldn't loop, and is special in the sense that it
* runs in the main thread, and should apply acceleration to entities/etc
*/
std::thread ev_th(event_handler, std::ref(sdl_events), std::ref(game_events));
std::thread gevs_th(gs_handler , std::ref(game_events), std::ref(game_state));
std::thread exp_th(expensive_fn, std::ref(game_state));
ev_th.detach();
gevs_th.detach();
exp_th.detach();
uint16_t fps_relation = 1000/fps;
Utils::tempo(fps_relation, [&](uint32_t&, auto debt) {
SDL_Event e;
while( SDL_PollEvent(&e) != 0) {
sdl_events.push(e);
}
LSit x = render_handler(game_state, fps_relation + debt.count() + 2);
SDL_RenderPresent(win_renderer);
return x;
});
};
};
} | 39.641791 | 130 | 0.494352 | [
"render"
] |
85e21b982027b1b5ac4b4800a5487311e3104beb | 1,826 | h | C | ui/gfx/ozone/overlay_candidates_ozone.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/gfx/ozone/overlay_candidates_ozone.h | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/gfx/ozone/overlay_candidates_ozone.h | shaochangbin/chromium-crosswalk | 634d34e4cf82b4f7400357c53ec12efaffe94add | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-04-17T13:19:09.000Z | 2021-10-21T12:55:15.000Z | // Copyright 2014 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_GFX_OZONE_OVERLAY_CANDIDATES_OZONE_H_
#define UI_GFX_OZONE_OVERLAY_CANDIDATES_OZONE_H_
#include <vector>
#include "base/basictypes.h"
#include "ui/gfx/gfx_export.h"
#include "ui/gfx/ozone/surface_factory_ozone.h"
#include "ui/gfx/rect_f.h"
namespace gfx {
// This class can be used to answer questions about possible overlay
// configurations for a particular output device. We get an instance of this
// class from SurfaceFactoryOzone given an AcceleratedWidget.
class GFX_EXPORT OverlayCandidatesOzone {
public:
struct OverlaySurfaceCandidate {
OverlaySurfaceCandidate();
~OverlaySurfaceCandidate();
// Transformation to apply to layer during composition.
SurfaceFactoryOzone::OverlayTransform transform;
// Format of the buffer to composite.
SurfaceFactoryOzone::BufferFormat format;
// Rect on the display to position the overlay to.
gfx::Rect display_rect;
// Crop within the buffer to be placed inside |display_rect|.
gfx::RectF crop_rect;
// To be modified by the implementer if this candidate can go into
// an overlay.
bool overlay_handled;
};
typedef std::vector<OverlaySurfaceCandidate> OverlaySurfaceCandidateList;
// A list of possible overlay candidates is presented to this function.
// The expected result is that those candidates that can be in a separate
// plane are marked with |overlay_handled| set to true, otherwise they are
// to be tranditionally composited.
virtual void CheckOverlaySupport(OverlaySurfaceCandidateList* surfaces);
virtual ~OverlayCandidatesOzone();
};
} // namespace gfx
#endif // UI_GFX_OZONE_OVERLAY_CANDIDATES_OZONE_H_
| 33.814815 | 76 | 0.768894 | [
"vector",
"transform"
] |
85f10cfbb64cb947037e8d666f81a003e9bac060 | 31,145 | c | C | src/client/dfs/dfs_sys.c | tylerqi/daos | 290a7740e8af958c2036270163640cf7f2f313d9 | [
"BSD-2-Clause-Patent"
] | null | null | null | src/client/dfs/dfs_sys.c | tylerqi/daos | 290a7740e8af958c2036270163640cf7f2f313d9 | [
"BSD-2-Clause-Patent"
] | null | null | null | src/client/dfs/dfs_sys.c | tylerqi/daos | 290a7740e8af958c2036270163640cf7f2f313d9 | [
"BSD-2-Clause-Patent"
] | null | null | null | /**
* (C) Copyright 2018-2022 Intel Corporation.
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*/
#include <libgen.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/xattr.h>
#include <linux/xattr.h>
#include <daos/common.h>
#include <daos/event.h>
#include <gurt/atomic.h>
#include "daos.h"
#include "daos_fs.h"
#include "daos_fs_sys.h"
/** Number of entries for readdir */
#define DFS_SYS_NUM_DIRENTS 24
/** Size of the hash table */
#define DFS_SYS_HASH_SIZE 12
struct dfs_sys {
dfs_t *dfs; /* mounted filesystem */
struct d_hash_table *hash; /* optional lookup hash */
};
/** struct holding parsed dirname, name, and cached parent obj */
struct sys_path {
const char *path; /* original, full path */
size_t path_len; /* length of path */
char *alloc; /* allocation of dir and name */
char *dir_name; /* dirname(path) */
size_t dir_name_len; /* length of dir_name */
char *name; /* basename(path) */
size_t name_len; /* length of name */
dfs_obj_t *parent; /* dir_name obj */
d_list_t *rlink; /* hash link */
};
struct dfs_sys_dir {
dfs_obj_t *obj;
struct dirent ents[DFS_SYS_NUM_DIRENTS];
daos_anchor_t anchor;
uint32_t num_ents;
};
/**
* Hash handle for each entry.
*/
struct hash_hdl {
dfs_obj_t *obj;
d_list_t entry;
char *name;
size_t name_len;
ATOMIC uint ref;
};
/*
* Get a hash_hdl from the d_list_t.
*/
static inline struct hash_hdl*
hash_hdl_obj(d_list_t *rlink)
{
return container_of(rlink, struct hash_hdl, entry);
}
/**
* Compare hash entry key.
* Simple string comparison of name.
*/
static bool
hash_key_cmp(struct d_hash_table *table, d_list_t *rlink,
const void *key, unsigned int ksize)
{
struct hash_hdl *hdl = hash_hdl_obj(rlink);
if (hdl->name_len != ksize)
return false;
return (strncmp(hdl->name, (const char *)key, ksize) == 0);
}
/**
* Add reference to hash entry.
*/
static void
hash_rec_addref(struct d_hash_table *htable, d_list_t *rlink)
{
struct hash_hdl *hdl;
uint oldref;
hdl = hash_hdl_obj(rlink);
oldref = atomic_fetch_add_relaxed(&hdl->ref, 1);
D_DEBUG(DB_TRACE, "%s, oldref = %u\n",
hdl->name, oldref);
}
/**
* Decrease reference to hash entry.
*/
static bool
hash_rec_decref(struct d_hash_table *htable, d_list_t *rlink)
{
struct hash_hdl *hdl;
uint oldref;
hdl = hash_hdl_obj(rlink);
oldref = atomic_fetch_sub_relaxed(&hdl->ref, 1);
D_DEBUG(DB_TRACE, "%s, oldref = %u\n",
hdl->name, oldref);
D_ASSERT(oldref > 0);
return oldref == 1;
}
/*
* Free a hash entry.
*/
static void
hash_rec_free(struct d_hash_table *htable, d_list_t *rlink)
{
struct hash_hdl *hdl = hash_hdl_obj(rlink);
int rc = 0;
D_DEBUG(DB_TRACE, "name=%s\n", hdl->name);
rc = dfs_release(hdl->obj);
if (rc == ENOMEM)
dfs_release(hdl->obj);
D_FREE(hdl->name);
D_FREE(hdl);
}
static uint32_t
hash_rec_hash(struct d_hash_table *htable, d_list_t *rlink)
{
struct hash_hdl *hdl = hash_hdl_obj(rlink);
return d_hash_string_u32(hdl->name, hdl->name_len);
}
/**
* Operations for the hash table.
*/
static d_hash_table_ops_t hash_hdl_ops = {
.hop_key_cmp = hash_key_cmp,
.hop_rec_addref = hash_rec_addref,
.hop_rec_decref = hash_rec_decref,
.hop_rec_free = hash_rec_free,
.hop_rec_hash = hash_rec_hash
};
/**
* Try to get dir_name from the hash.
* If not found, call dfs_lookup on name
* and store in the hash.
* Stores the hashed obj in parent.
*/
/* TODO
* We could recursively cache a path instead of blindly calling
* dfs_lookup. For example, consider lookup on these paths in succession:
* dfs_lookup("/path/to/dir1")
* dfs_lookup("/path/to/dir2")
* Internally, dfs_lookup will be fetching and iterating over the same
* entries along the path. We could more efficiently do this:
* dfs_lookup_rel("/", "path")
* dfs_lookup_rel("/path", "to")
* dfs_lookup_rel("/path/to", "dir1")
* dfs_lookup_rel("/path/to", "dir2")
*/
static int
hash_lookup(dfs_sys_t *dfs_sys, struct sys_path *sys_path)
{
struct hash_hdl *hdl;
d_list_t *rlink;
mode_t mode;
int rc = 0;
/* If we aren't caching, just call dfs_lookup */
if (dfs_sys->hash == NULL) {
rc = dfs_lookup(dfs_sys->dfs, sys_path->dir_name, O_RDWR,
&sys_path->parent, &mode, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path->dir_name, rc);
return rc;
}
/* We only cache directories */
if (!S_ISDIR(mode)) {
dfs_release(sys_path->parent);
return ENOTDIR;
}
return rc;
}
/* If cached, return it */
rlink = d_hash_rec_find(dfs_sys->hash, sys_path->dir_name,
sys_path->dir_name_len);
if (rlink != NULL) {
hdl = hash_hdl_obj(rlink);
D_GOTO(out, rc = 0);
}
/* Not cached, so create an entry and add it */
D_ALLOC_PTR(hdl);
if (hdl == NULL)
return ENOMEM;
hdl->name_len = sys_path->dir_name_len;
D_STRNDUP(hdl->name, sys_path->dir_name, sys_path->dir_name_len);
if (hdl->name == NULL)
D_GOTO(free_hdl, rc = ENOMEM);
/* Start with 2 so we have exactly 1 reference left
* when dfs_sys_umount is called.
*/
atomic_store_relaxed(&hdl->ref, 2);
/* Lookup name in dfs */
rc = dfs_lookup(dfs_sys->dfs, sys_path->dir_name, O_RDWR, &hdl->obj,
&mode, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n", sys_path->dir_name, rc);
D_GOTO(free_hdl_name, rc);
}
/* We only cache directories */
if (!S_ISDIR(mode))
D_GOTO(free_hdl_obj, rc = ENOTDIR);
/* call find_insert in case another thread added the same entry
* after calling find.
*/
rlink = d_hash_rec_find_insert(dfs_sys->hash, hdl->name,
sys_path->dir_name_len, &hdl->entry);
if (rlink != &hdl->entry) {
/* another thread beat us. Use the existing entry. */
sys_path->parent = hash_hdl_obj(rlink)->obj;
sys_path->rlink = rlink;
D_GOTO(free_hdl_obj, rc = 0);
}
out:
sys_path->parent = hdl->obj;
sys_path->rlink = rlink;
return rc;
free_hdl_obj:
dfs_release(hdl->obj);
free_hdl_name:
D_FREE(hdl->name);
free_hdl:
D_FREE(hdl);
return rc;
}
/**
* Free a struct sys_path.
*/
static void
sys_path_free(dfs_sys_t *dfs_sys, struct sys_path *sys_path)
{
D_FREE(sys_path->alloc);
if (dfs_sys->hash == NULL)
dfs_release(sys_path->parent);
else if (sys_path->rlink != NULL)
d_hash_rec_decref(dfs_sys->hash, sys_path->rlink);
}
/**
* Set up a struct sys_path.
* Parse path into dirname and basename stored in a single
* allocation separated by null terminators.
* Lookup dir_name in the hash.
*/
static int
sys_path_parse(dfs_sys_t *dfs_sys, struct sys_path *sys_path,
const char *path)
{
int rc;
char *new_path = NULL;
char *dir_name = NULL;
char *name = NULL;
size_t path_len;
size_t dir_name_len = 0;
size_t name_len = 0;
size_t i;
size_t end_idx = 0;
size_t slash_idx = 0;
if (path == NULL)
return EINVAL;
if (path[0] != '/')
return EINVAL;
path_len = strnlen(path, PATH_MAX);
if (path_len > PATH_MAX - 1)
return ENAMETOOLONG;
/** Find end, not including trailing slashes */
for (i = path_len - 1; i > 0; i--) {
if (path[i] != '/') {
end_idx = i;
break;
}
}
/** Find last slash */
for (; i > 0; i--) {
if (path[i] == '/') {
slash_idx = i;
break;
}
}
/** Build a single path of the format:
* <dir> + '\0' + <name> + '\0'
*/
D_ALLOC(new_path, end_idx + 3);
if (new_path == NULL) {
return ENOMEM;
}
/** Copy the dirname */
if (slash_idx == 0)
dir_name_len = 1;
else
dir_name_len = slash_idx;
strncpy(new_path, path, dir_name_len);
dir_name = new_path;
/** Copy the basename */
name_len = end_idx - slash_idx;
if (name_len > 0) {
new_path[dir_name_len] = 0;
strncpy(new_path + dir_name_len + 1, path + slash_idx + 1,
name_len);
name = new_path + dir_name_len + 1;
}
sys_path->path = path;
sys_path->path_len = path_len;
sys_path->alloc = new_path;
sys_path->dir_name = dir_name;
sys_path->dir_name_len = dir_name_len;
sys_path->name = name;
sys_path->name_len = name_len;
sys_path->parent = NULL;
sys_path->rlink = NULL;
rc = hash_lookup(dfs_sys, sys_path);
if (rc != 0) {
sys_path_free(dfs_sys, sys_path);
return rc;
}
return rc;
}
static int
init_sys(int mflags, int sflags, dfs_sys_t **_dfs_sys)
{
dfs_sys_t *dfs_sys;
int rc;
uint32_t hash_feats = D_HASH_FT_EPHEMERAL;
bool no_cache = false;
bool no_lock = false;
if (_dfs_sys == NULL)
return EINVAL;
if (sflags & DFS_SYS_NO_CACHE) {
D_DEBUG(DB_TRACE, "mount: DFS_SYS_NO_CACHE.\n");
no_cache = true;
sflags &= ~DFS_SYS_NO_CACHE;
}
if (sflags & DFS_SYS_NO_LOCK) {
D_DEBUG(DB_TRACE, "mount: DFS_SYS_NO_LOCK.\n");
no_lock = true;
sflags &= ~DFS_SYS_NO_LOCK;
}
if (sflags != 0) {
D_DEBUG(DB_TRACE, "mount: invalid sflags.\n");
return EINVAL;
}
D_ALLOC_PTR(dfs_sys);
if (dfs_sys == NULL)
return ENOMEM;
*_dfs_sys = dfs_sys;
if (no_cache)
return 0;
/* Initialize the hash */
if (no_lock)
hash_feats |= D_HASH_FT_NOLOCK;
else
hash_feats |= D_HASH_FT_RWLOCK;
rc = d_hash_table_create(hash_feats, DFS_SYS_HASH_SIZE, NULL, &hash_hdl_ops,
&dfs_sys->hash);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to create hash table "
DF_RC"\n", DP_RC(rc));
D_GOTO(err_dfs_sys, rc = daos_der2errno(rc));
}
return 0;
err_dfs_sys:
D_FREE(dfs_sys);
return rc;
}
int
dfs_sys_connect(const char *pool, const char *sys, const char *cont, int mflags, int sflags,
dfs_attr_t *attr, dfs_sys_t **_dfs_sys)
{
dfs_sys_t *dfs_sys;
int rc;
rc = init_sys(mflags, sflags, &dfs_sys);
if (rc)
return rc;
/* Mount dfs */
rc = dfs_connect(pool, sys, cont, mflags, attr, &dfs_sys->dfs);
if (rc != 0) {
D_DEBUG(DB_TRACE, "dfs_connect() failed (%d)\n", rc);
D_GOTO(err_dfs_sys, rc);
}
*_dfs_sys = dfs_sys;
return rc;
err_dfs_sys:
if (dfs_sys->hash != NULL)
d_hash_table_destroy(dfs_sys->hash, false);
D_FREE(dfs_sys);
return rc;
}
static int
fini_sys(dfs_sys_t *dfs_sys, bool disconnect)
{
int rc;
d_list_t *rlink;
if (dfs_sys == NULL)
return EINVAL;
if (dfs_sys->hash != NULL) {
/* Decrease each reference by one. */
while (1) {
rlink = d_hash_rec_first(dfs_sys->hash);
if (rlink == NULL)
break;
d_hash_rec_decref(dfs_sys->hash, rlink);
}
rc = d_hash_table_destroy(dfs_sys->hash, false);
if (rc) {
D_DEBUG(DB_TRACE, "failed to destroy hash table: "DF_RC"\n", DP_RC(rc));
return rc;
}
dfs_sys->hash = NULL;
}
if (dfs_sys->dfs != NULL) {
if (disconnect) {
rc = dfs_disconnect(dfs_sys->dfs);
if (rc) {
D_DEBUG(DB_TRACE, "dfs_disconnect() failed (%d)\n", rc);
return rc;
}
} else {
rc = dfs_umount(dfs_sys->dfs);
if (rc) {
D_DEBUG(DB_TRACE, "dfs_umount() failed (%d)\n", rc);
return rc;
}
}
dfs_sys->dfs = NULL;
}
/* Only free if umount was successful */
D_FREE(dfs_sys);
return 0;
}
int
dfs_sys_disconnect(dfs_sys_t *dfs_sys)
{
return fini_sys(dfs_sys, true);
}
int
dfs_sys_mount(daos_handle_t poh, daos_handle_t coh, int mflags, int sflags,
dfs_sys_t **_dfs_sys)
{
dfs_sys_t *dfs_sys;
int rc;
rc = init_sys(mflags, sflags, &dfs_sys);
if (rc)
return rc;
/* Mount dfs */
rc = dfs_mount(poh, coh, mflags, &dfs_sys->dfs);
if (rc != 0) {
D_DEBUG(DB_TRACE, "dfs_mount() failed (%d)\n", rc);
D_GOTO(err_dfs_sys, rc);
}
*_dfs_sys = dfs_sys;
return rc;
err_dfs_sys:
if (dfs_sys->hash != NULL)
d_hash_table_destroy(dfs_sys->hash, false);
D_FREE(dfs_sys);
return rc;
}
/**
* Unmount a file system with dfs_mount and destroy the hash.
*/
int
dfs_sys_umount(dfs_sys_t *dfs_sys)
{
return fini_sys(dfs_sys, false);
}
int
dfs_sys_local2global_all(dfs_sys_t *dfs_sys, d_iov_t *glob)
{
if (dfs_sys == NULL)
return EINVAL;
/* TODO serialize the dfs_sys flags as well */
return dfs_local2global_all(dfs_sys->dfs, glob);
}
int
dfs_sys_global2local_all(int mflags, int sflags, d_iov_t glob, dfs_sys_t **_dfs_sys)
{
dfs_sys_t *dfs_sys;
int rc;
rc = init_sys(mflags, sflags, &dfs_sys);
if (rc)
return rc;
rc = dfs_global2local_all(mflags, glob, &dfs_sys->dfs);
if (rc != 0) {
D_DEBUG(DB_TRACE, "dfs_global2local() failed (%d)\n", rc);
D_GOTO(err_dfs_sys, rc);
}
*_dfs_sys = dfs_sys;
return rc;
err_dfs_sys:
if (dfs_sys->hash != NULL)
d_hash_table_destroy(dfs_sys->hash, false);
D_FREE(dfs_sys);
return rc;
}
int
dfs_sys_local2global(dfs_sys_t *dfs_sys, d_iov_t *glob)
{
if (dfs_sys == NULL)
return EINVAL;
/* TODO serialize the dfs_sys flags as well */
return dfs_local2global(dfs_sys->dfs, glob);
}
int
dfs_sys_global2local(daos_handle_t poh, daos_handle_t coh, int mflags,
int sflags, d_iov_t glob, dfs_sys_t **_dfs_sys)
{
dfs_sys_t *dfs_sys;
int rc;
rc = init_sys(mflags, sflags, &dfs_sys);
if (rc)
return rc;
rc = dfs_global2local(poh, coh, mflags, glob, &dfs_sys->dfs);
if (rc != 0) {
D_DEBUG(DB_TRACE, "dfs_global2local() failed (%d)\n", rc);
D_GOTO(err_dfs_sys, rc);
}
*_dfs_sys = dfs_sys;
return rc;
err_dfs_sys:
if (dfs_sys->hash != NULL)
d_hash_table_destroy(dfs_sys->hash, false);
D_FREE(dfs_sys);
return rc;
}
int
dfs_sys2base(dfs_sys_t *dfs_sys, dfs_t **_dfs)
{
if (dfs_sys == NULL)
return EINVAL;
*_dfs = dfs_sys->dfs;
return 0;
}
int
dfs_sys_access(dfs_sys_t *dfs_sys, const char *path, int mask, int flags)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
mode_t mode;
int lookup_flags = O_RDWR;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
if (flags & AT_EACCESS)
return ENOTSUP;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* If not following symlinks then lookup the obj first
* and return success for a symlink.
*/
if ((sys_path.name != NULL) && (flags & O_NOFOLLOW)) {
lookup_flags |= O_NOFOLLOW;
/* Lookup the obj and get it's mode */
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent,
sys_path.name, lookup_flags, &obj,
&mode, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
dfs_release(obj);
/* A link itself is always accessible */
if (S_ISLNK(mode))
D_GOTO(out_free_path, rc = 0);
}
/* Either we are following symlinks, the obj is root,
* or the obj is not a symlink. So just call dfs_access.
*/
rc = dfs_access(dfs_sys->dfs, sys_path.parent, sys_path.name, mask);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_chmod(dfs_sys_t *dfs_sys, const char *path, mode_t mode)
{
int rc;
struct sys_path sys_path;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
rc = dfs_chmod(dfs_sys->dfs, sys_path.parent, sys_path.name, mode);
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_setattr(dfs_sys_t *dfs_sys, const char *path, struct stat *stbuf,
int flags, int sflags)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
int lookup_flags = O_RDWR;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* No need to lookup the root */
if (sys_path.name == NULL) {
obj = sys_path.parent;
goto setattr;
}
if (sflags & O_NOFOLLOW)
lookup_flags |= O_NOFOLLOW;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent,
sys_path.name, lookup_flags, &obj, NULL, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
setattr:
rc = dfs_osetattr(dfs_sys->dfs, obj, stbuf, flags);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to setattr %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_close_obj, rc);
}
out_close_obj:
if (sys_path.name != NULL)
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_utimens(dfs_sys_t *dfs_sys, const char *path,
const struct timespec times[2], int flags)
{
int rc;
struct stat stbuf;
stbuf.st_atim = times[0];
stbuf.st_mtim = times[1];
rc = dfs_sys_setattr(dfs_sys, path, &stbuf,
DFS_SET_ATTR_ATIME | DFS_SET_ATTR_MTIME,
flags);
return rc;
}
int
dfs_sys_stat(dfs_sys_t *dfs_sys, const char *path, int flags,
struct stat *buf)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
int lookup_flags = O_RDWR;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* No need to lookup root */
if (sys_path.name == NULL) {
rc = dfs_ostat(dfs_sys->dfs, sys_path.parent, buf);
D_GOTO(out_free_path, rc);
}
if (flags & O_NOFOLLOW)
lookup_flags |= O_NOFOLLOW;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent,
sys_path.name, lookup_flags, &obj, NULL, buf);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_mknod(dfs_sys_t *dfs_sys, const char *path, mode_t mode,
daos_oclass_id_t cid, daos_size_t chunk_size)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
rc = dfs_open(dfs_sys->dfs, sys_path.parent, sys_path.name, mode,
O_CREAT | O_EXCL, cid, chunk_size, NULL, &obj);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to open %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_listxattr(dfs_sys_t *dfs_sys, const char *path, char *list,
daos_size_t *size, int flags)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
daos_size_t got_size = *size;
int lookup_flags = O_RDONLY;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* No need to lookup root */
if (sys_path.name == NULL) {
obj = sys_path.parent;
goto listxattr;
}
if (flags & O_NOFOLLOW)
lookup_flags |= O_NOFOLLOW;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent, sys_path.name,
lookup_flags, &obj, NULL, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
listxattr:
rc = dfs_listxattr(dfs_sys->dfs, obj, list, &got_size);
if (rc != 0)
D_GOTO(out_free_obj, rc);
if (*size < got_size)
rc = ERANGE;
*size = got_size;
out_free_obj:
if (sys_path.name != NULL)
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_getxattr(dfs_sys_t *dfs_sys, const char *path, const char *name,
void *value, daos_size_t *size, int flags)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
daos_size_t got_size = *size;
int lookup_flags = O_RDONLY;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* No need to lookup root */
if (sys_path.name == NULL) {
obj = sys_path.parent;
goto getxattr;
}
if (flags & O_NOFOLLOW)
lookup_flags |= O_NOFOLLOW;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent, sys_path.name,
lookup_flags, &obj, NULL, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
getxattr:
rc = dfs_getxattr(dfs_sys->dfs, obj, name, value, &got_size);
if (rc != 0)
D_GOTO(out_free_obj, rc);
if (*size < got_size)
rc = ERANGE;
*size = got_size;
out_free_obj:
if (sys_path.name != NULL)
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_setxattr(dfs_sys_t *dfs_sys, const char *path, const char *name,
const void *value, daos_size_t size, int flags, int sflags)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
int lookup_flags = O_RDWR;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* No need to lookup root */
if (sys_path.name == NULL) {
obj = sys_path.parent;
goto setxattr;
}
if (sflags & O_NOFOLLOW)
lookup_flags |= O_NOFOLLOW;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent, sys_path.name,
lookup_flags, &obj, NULL, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
setxattr:
rc = dfs_setxattr(dfs_sys->dfs, obj, name, value, size, flags);
if (rc != 0)
D_GOTO(out_free_obj, rc);
out_free_obj:
if (sys_path.name != NULL)
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_removexattr(dfs_sys_t *dfs_sys, const char *path, const char *name,
int flags)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
int lookup_flags = O_RDWR;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* No need to lookup root */
if (sys_path.name == NULL) {
obj = sys_path.parent;
goto removexattr;
}
if (flags & O_NOFOLLOW)
lookup_flags |= O_NOFOLLOW;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent, sys_path.name,
lookup_flags, &obj, NULL, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
removexattr:
rc = dfs_removexattr(dfs_sys->dfs, obj, name);
if (rc != 0)
D_GOTO(out_free_obj, rc);
out_free_obj:
if (sys_path.name != NULL)
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_readlink(dfs_sys_t *dfs_sys, const char *path, char *buf,
daos_size_t *size)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
int lookup_flags = O_RDONLY | O_NOFOLLOW;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent, sys_path.name,
lookup_flags, &obj, NULL, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
rc = dfs_get_symlink_value(obj, buf, size);
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_symlink(dfs_sys_t *dfs_sys, const char *target, const char *path)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj = NULL;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
rc = dfs_open(dfs_sys->dfs, sys_path.parent, sys_path.name,
S_IFLNK, O_CREAT | O_EXCL,
0, 0, target, &obj);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to open %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
if (obj)
dfs_release(obj);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_open(dfs_sys_t *dfs_sys, const char *path, mode_t mode, int flags,
daos_oclass_id_t cid, daos_size_t chunk_size,
const char *value, dfs_obj_t **_obj)
{
int rc;
struct sys_path sys_path;
mode_t actual_mode;
dfs_obj_t *obj;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
if ((mode & S_IFMT) == 0)
mode |= S_IFREG;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* If this is root, just dup the handle */
if (sys_path.name == NULL) {
if (flags & (O_CREAT | O_EXCL))
D_GOTO(out_free_path, rc = EEXIST);
if (!S_ISDIR(mode))
D_GOTO(out_free_path, rc = ENOTDIR);
rc = dfs_dup(dfs_sys->dfs, sys_path.parent, mode,
_obj);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to dup %s: (%d)\n",
sys_path.name, rc);
}
D_GOTO(out_free_path, rc);
}
/* If creating or not following symlinks, call dfs_open.
* Note that this does not handle the case of following a symlink
* and creating the target pointed to.
*/
if ((flags & O_CREAT) || (flags & O_NOFOLLOW)) {
rc = dfs_open(dfs_sys->dfs, sys_path.parent, sys_path.name,
mode, flags, cid, chunk_size, value, _obj);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to open %s: (%d)\n",
sys_path.name, rc);
}
D_GOTO(out_free_path, rc);
}
/* Call dfs_lookup_rel to follow symlinks */
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent, sys_path.name,
flags, &obj, &actual_mode, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
/* Make sure the type is the same */
if ((mode & S_IFMT) != (actual_mode & S_IFMT)) {
dfs_release(obj);
D_GOTO(out_free_path, rc = EINVAL);
}
*_obj = obj;
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_close(dfs_obj_t *obj)
{
int rc = 0;
rc = dfs_release(obj);
if (rc == ENOMEM)
dfs_release(obj);
return rc;
}
int
dfs_sys_read(dfs_sys_t *dfs_sys, dfs_obj_t *obj, void *buf, daos_off_t off,
daos_size_t *size, daos_event_t *ev)
{
d_iov_t iov;
d_sg_list_t sgl;
if (dfs_sys == NULL)
return EINVAL;
if (buf == NULL)
return EINVAL;
if (size == NULL)
return EINVAL;
d_iov_set(&iov, buf, *size);
sgl.sg_nr = 1;
sgl.sg_iovs = &iov;
sgl.sg_nr_out = 1;
return dfs_read(dfs_sys->dfs, obj, &sgl, off, size, ev);
}
int
dfs_sys_write(dfs_sys_t *dfs_sys, dfs_obj_t *obj, const void *buf,
daos_off_t off, daos_size_t *size, daos_event_t *ev)
{
d_iov_t iov;
d_sg_list_t sgl;
if (dfs_sys == NULL)
return EINVAL;
if (buf == NULL)
return EINVAL;
if (size == NULL)
return EINVAL;
d_iov_set(&iov, (void *)buf, *size);
sgl.sg_nr = 1;
sgl.sg_iovs = &iov;
sgl.sg_nr_out = 1;
return dfs_write(dfs_sys->dfs, obj, &sgl, off, ev);
}
int
dfs_sys_punch(dfs_sys_t *dfs_sys, const char *path,
daos_off_t offset, daos_off_t len)
{
int rc;
struct sys_path sys_path;
dfs_obj_t *obj;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
rc = dfs_open(dfs_sys->dfs, sys_path.parent, sys_path.name,
S_IFREG, O_RDWR, 0, 0, NULL, &obj);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to open %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out, rc);
}
rc = dfs_punch(dfs_sys->dfs, obj, offset, len);
dfs_release(obj);
out:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_remove(dfs_sys_t *dfs_sys, const char *path, bool force,
daos_obj_id_t *oid)
{
return dfs_sys_remove_type(dfs_sys, path, force, 0, oid);
}
int
dfs_sys_remove_type(dfs_sys_t *dfs_sys, const char *path, bool force,
mode_t mode, daos_obj_id_t *oid)
{
int rc;
struct sys_path sys_path;
struct stat stbuf;
mode_t type_mask = mode & S_IFMT;
if (dfs_sys == NULL)
return EINVAL;
if (path == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, path);
if (rc != 0)
return rc;
/* Can't delete root */
if (sys_path.name == NULL)
D_GOTO(out_free_path, rc = EBUSY);
/* Only check the type if passed in */
if (type_mask == 0)
goto remove;
/* Stat the object and make sure it is the correct type */
rc = dfs_stat(dfs_sys->dfs, sys_path.parent, sys_path.name, &stbuf);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to stat %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
if (type_mask != (mode & S_IFMT))
D_GOTO(out_free_path, rc = EINVAL);
remove:
rc = dfs_remove(dfs_sys->dfs, sys_path.parent, sys_path.name,
force, oid);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to remove %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
if ((dfs_sys->hash != NULL) &&
(type_mask == 0 || type_mask == S_IFDIR)) {
bool deleted;
/* TODO - Ideally, we should return something like EBUSY
* if there are still open handles to the directory.
* TODO - if force=true then we need to delete any child
* directories as well.
*/
deleted = d_hash_rec_delete(dfs_sys->hash, sys_path.path,
sys_path.path_len);
D_DEBUG(DB_TRACE, "d_hash_rec_delete() %s = %d\n",
sys_path.path, deleted);
}
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_mkdir(dfs_sys_t *dfs_sys, const char *dir, mode_t mode,
daos_oclass_id_t cid)
{
int rc;
struct sys_path sys_path;
if (dfs_sys == NULL)
return EINVAL;
if (dir == NULL)
return EINVAL;
rc = sys_path_parse(dfs_sys, &sys_path, dir);
if (rc != 0)
return rc;
/* Root always already exists */
if (sys_path.name == NULL)
D_GOTO(out_free_path, rc = EEXIST);
rc = dfs_mkdir(dfs_sys->dfs, sys_path.parent, sys_path.name,
mode, cid);
out_free_path:
sys_path_free(dfs_sys, &sys_path);
return rc;
}
int
dfs_sys_opendir(dfs_sys_t *dfs_sys, const char *dir, int flags, DIR **_dirp)
{
int rc;
struct sys_path sys_path;
struct dfs_sys_dir *sys_dir;
mode_t mode;
int lookup_flags = O_RDWR;
if (dfs_sys == NULL)
return EINVAL;
if (dir == NULL)
return EINVAL;
D_ALLOC_PTR(sys_dir);
if (sys_dir == NULL)
return ENOMEM;
rc = sys_path_parse(dfs_sys, &sys_path, dir);
if (rc != 0)
D_GOTO(out_free_dir, rc);
/* If this is root, just dup the handle */
if (sys_path.name == NULL) {
rc = dfs_dup(dfs_sys->dfs, sys_path.parent, O_RDWR,
&sys_dir->obj);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to dup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
D_GOTO(out, rc);
}
if (flags & O_NOFOLLOW)
lookup_flags |= O_NOFOLLOW;
rc = dfs_lookup_rel(dfs_sys->dfs, sys_path.parent, sys_path.name,
lookup_flags, &sys_dir->obj, &mode, NULL);
if (rc != 0) {
D_DEBUG(DB_TRACE, "failed to lookup %s: (%d)\n",
sys_path.name, rc);
D_GOTO(out_free_path, rc);
}
if (!S_ISDIR(mode)) {
dfs_release(sys_dir->obj);
D_GOTO(out_free_path, rc = ENOTDIR);
}
out:
*_dirp = (DIR *)sys_dir;
sys_path_free(dfs_sys, &sys_path);
return rc;
out_free_path:
sys_path_free(dfs_sys, &sys_path);
out_free_dir:
D_FREE(sys_dir);
return rc;
}
int
dfs_sys_closedir(DIR *dirp)
{
int rc;
struct dfs_sys_dir *sys_dir;
if (dirp == NULL)
return EINVAL;
sys_dir = (struct dfs_sys_dir *)dirp;
rc = dfs_release(sys_dir->obj);
if (rc == ENOMEM)
dfs_release(sys_dir->obj);
D_FREE(sys_dir);
return rc;
}
int
dfs_sys_readdir(dfs_sys_t *dfs_sys, DIR *dirp, struct dirent **_dirent)
{
int rc = 0;
struct dfs_sys_dir *sys_dir;
if (dfs_sys == NULL)
return EINVAL;
if (dirp == NULL)
return EINVAL;
sys_dir = (struct dfs_sys_dir *)dirp;
if (sys_dir->num_ents)
D_GOTO(out, rc = 0);
sys_dir->num_ents = DFS_SYS_NUM_DIRENTS;
while (!daos_anchor_is_eof(&sys_dir->anchor)) {
rc = dfs_readdir(dfs_sys->dfs, sys_dir->obj,
&sys_dir->anchor, &sys_dir->num_ents,
sys_dir->ents);
if (rc != 0)
D_GOTO(out_null, rc);
/* We have an entry, so return it */
if (sys_dir->num_ents != 0)
D_GOTO(out, rc);
}
out_null:
sys_dir->num_ents = 0;
*_dirent = NULL;
return rc;
out:
sys_dir->num_ents--;
*_dirent = &sys_dir->ents[sys_dir->num_ents];
return rc;
}
| 20.791055 | 92 | 0.66778 | [
"object"
] |
85f3e8e2d27af3b5d0b82044e1c088ebd05e0b96 | 15,813 | h | C | Janus/PropertyDef.h | alwinw/Janus | d80ec94af69e17e41718b94eea91e5419e600da2 | [
"MIT"
] | 7 | 2020-04-07T20:05:03.000Z | 2022-02-04T10:36:28.000Z | Janus/PropertyDef.h | alwinw/Janus | d80ec94af69e17e41718b94eea91e5419e600da2 | [
"MIT"
] | null | null | null | Janus/PropertyDef.h | alwinw/Janus | d80ec94af69e17e41718b94eea91e5419e600da2 | [
"MIT"
] | 1 | 2022-02-12T10:17:51.000Z | 2022-02-12T10:17:51.000Z | #ifndef _PROPERTYDEF_H_
#define _PROPERTYDEF_H_
//
// DST Janus Library (Janus DAVE-ML Interpreter Library)
//
// Defence Science and Technology (DST) Group
// Department of Defence, Australia.
// 506 Lorimer St
// Fishermans Bend, VIC
// AUSTRALIA, 3207
//
// Copyright 2005-2021 Commonwealth of Australia
//
// 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.
//
//------------------------------------------------------------------------//
// Title: Janus/PropertyDef
// Class: PropertyDef
// Module: PropertyDef.h
// First Date: 2015-11-15
// Reference: Janus Reference Manual
//------------------------------------------------------------------------//
/**
* \file PropertyDef.h
*
* A PropertyDef instance holds in its allocated memory data
* derived from a \em propertyDef element of a DOM corresponding to
* a DAVE-ML compliant XML dataset source file. It includes descriptive,
* alphanumeric identification and cross-reference data.
* This class sets up a structure that manages the \em propertyDef content.
*
* The PropertyDef class is only used within the janus namespace, and should
* only be referenced through the Janus class.
*/
/*
* Author: G Brian
*
*/
// C++ Includes
// Ute Includes
// Local Includes
#include "XmlElementDefinition.h"
#include "Provenance.h"
namespace janus {
class Janus;
/**
* A #PropertyDef instance holds in its allocated memory data
* derived from a \em propertyDef element of a DOM corresponding to
* a DAVE-ML compliant XML dataset source file. It includes descriptive,
* alphanumeric identification and cross-reference data.
*
* The #PropertyDef class is only used within the janus namespace, and should
* only be referenced through the Janus class.
*
* To determine the characteristics of a dataset's variables, typical usage is:
\code
Janus test( xmlFileName );
vector<PropertyDef> propertyDef = test.getPropertyDef();
for ( size_t i = 0 ; i < propertyDef.size() ; i++ ) {
cout << " Property " << i << " : \n"
<< " ID : "
<< propertyDef.at( i ).getPtyID() << "\n"
<< " Name : "
<< propertyDef.at( i ).getName() << "\n"
<< " Description : "
<< propertyDef.at( i ).getDescription() << "\n"
<< "\n";
}
\endcode
*/
class PropertyDef : public XmlElementDefinition
{
public:
/**
* The empty constructor can be used to instance the #PropertyDef class
* without supplying the DOM \em propertyDef element from which the instance
* is constructed, but in this state is not useful for any class functions.
* It is necessary to populate the class from a DOM containing a
* \em propertyDef element before any further use of the instanced class.
*
* This form of the constructor is principally for use within higher level
* instances, where memory needs to be allocated before the data to fill
* it is specified.
*
* \sa initialiseDefinition
*/
PropertyDef( );
/**
* The constructor, when called with an argument pointing to a \em propertyDef
* element within a DOM, instantiates the #PropertyDef class and fills
* it with alphanumeric data from the DOM.
*
* \param elementDefinition is an address of a \em propertyDef
* component within the DOM.
* \param janus is a pointer to the owning Janus instance, used
* within this class to set up cross-references depending on the instance
* state.
*/
PropertyDef( Janus* janus, const DomFunctions::XmlNode& elementDefinition);
/**
* An uninitialised instance of #PropertyDef is filled with data from a
* particular \em propertyDef element within a DOM by this function. If
* another \em propertyDef element pointer is supplied to an
* instance that has already been initialised, data corruption may occur.
*
* \param elementDefinition is an address of a \em propertyDef
* component within the DOM.
* \param janus is a pointer to the owning Janus instance, used
* within this class to set up cross-references depending on the instance
* state.
*/
void initialiseDefinition( Janus* janus, const DomFunctions::XmlNode& elementDefinition);
/**
* This function provides access to the \em name attribute of the
* \em propertyDef element represented by this VariableDef instance.
* A property's \em name attribute is a string of arbitrary
* length, but normally short. It is not used for indexing, and therefore
* need not be unique (although uniqueness may aid both programmer and
* user), but should comply with the ANSI/AIAA S-119-2011 standard\latexonly
* \cite{aiaa_data}\endlatexonly . If the instance has not been
* initialised from a DOM, an empty string is returned.
*
* \return The \em name string is returned by reference.
*/
const dstoute::aString& getName( ) const { return name_; }
/**
* This function provides access to the \em ptyID attribute
* of the \em propertyDef element represented by this #PropertyDef instance.
* A property's \em varID attribute is normally a short
* string without whitespace, such as "MACH02", that uniquely defines the
* property. It is used for indexing variables within an XML dataset,
* and provides underlying cross-references for most of the Janus library
* functionality. If the instance has not been initialised
* from a DOM, an empty string is returned.
*
* \return The \em ptyID string is returned by reference.
*/
const dstoute::aString& getPtyID( ) const { return ptyID_; }
/**
* The \em refID attribute is an optional document reference for a
* \em propertyDef. It may be used for cross-referencing a list
* of references contained in the \em fileHeader. This function returns the
* \em refID of a \em propertyDef, if one has been supplied in the
* XML dataset. If not, it returns an empty string.
*
* \return The \em refID string is returned by reference.
*
* \sa Reference
* \sa FileHeader
*/
const dstoute::aString& getRefID( ) const { return refID_; }
/**
* This function provides access to the optional \em description of the
* \em propertyDef element represented by this #PropertyDef instance.
* A \em propertyDef's \em description child element consists
* of a string of arbitrary length, which can include tabs and new lines as
* well as alphanumeric data. This means text formatting of the XML source
* will also appear in the returned description. If no description
* is specified in the XML dataset, or the #PropertyDef has not been
* initialised from the DOM, an empty string is returned.
*
* \return The \em description string is returned by reference.
*/
const dstoute::aString& getDescription( ) const { return description_; }
/**
* This function indicates whether a \em propertyDef element of a
* DAVE-ML dataset includes either \em provenance or \em provenanceRef.
*
* \return A boolean variable, 'true' if the \em function includes a
* provenance, defined either directly or by reference.
*
* \sa Provenance
*/
const bool& hasProvenance( ) const { return hasProvenance_; }
/**
* This function provides access to the Provenance instance
* associated with a #PropertyDef instance. There may be zero or one
* of these elements for each variable definition in a valid dataset,
* either provided directly or cross-referenced through a
* \em provenanceRef element.
*
* \return The Provenance instance is returned by reference.
*
* \sa Provenance
*/
const Provenance& getProvenance( ) const { return provenance_; }
/**
* This function provides access to the \em property content of the
* #PropertyDef element represented by this #PropertyDef instance.
*
* A \em propertyDef's \em property child element consists
* of a string of arbitrary length, which can include tabs and new lines as
* well as alphanumeric data. This means pretty formatting of the XML source
* will also appear in the returned description. If no property element
* is specified in the XML dataset, or the #PropertyDef has not been
* initialised from the DOM, an empty string is returned.
*
* \return The \em property string is returned by reference.
*/
const dstoute::aString& getProperty() const { return propertyList_.front();}
/**
* This function provides access to the \em property list content of the
* #PropertyDef element represented by this #PropertyDef instance.
*
* A \em propertyDef's \em property child elements consists
* of a string of arbitrary length, which can include tabs and new lines as
* well as alphanumeric data. This means pretty formatting of the XML source
* will also appear in the returned description. If no property element
* is specified in the XML dataset, or the #PropertyDef has not been
* initialised from the DOM, an empty string is returned.
*
* \return The \em property list is returned by reference.
*/
const dstoute::aStringList& getPropertyList() const { return propertyList_;}
/**
* This function permits the \em name attribute
* of the \em propertyDef element to be reset for this #PropertyDef instance.
*
* If the instance has not been initialised from a DOM then this function
* permits it to be set before being written to an output XML based file.
*
* \param name a string representation of the \em name attribute.
*/
void setName( const dstoute::aString& name) { name_ = name; }
/**
* This function permits the \em ptyID attribute
* of the \em propertyDef element to be reset for this #PropertyDef instance.
* A \em ptyID attribute is normally a short
* string without whitespace, such as "MACH02", that uniquely defines the
* propertyDef. It is used for indexing property elements within an XML dataset,
* and provides underlying cross-references if required.
*
* If the instance has not been initialised from a DOM then this function
* permits it to be set before being written to an output XML based file.
*
* \param ptyID a string representation of the \em ptyID identifier.
*/
void setPtyID( const dstoute::aString& ptyID) { ptyID_ = ptyID; }
/**
* This function permits the \em refID attribute of the
* of the \em propertyDef element to be reset for this #PropertyDef instance.
*
* The \em refID attribute is an optional document reference for a
* \em propertyDef. It may be used for cross-referencing a list
* of references contained in the \em fileHeader.
* A \em refID attribute is normally a short
* string without whitespace, such as "MACH02", that uniquely defines the
* reference.
*
* If the instance has not been initialised from a DOM then this function
* permits it to be set before being written to an output XML based file.
*
* \param refID a string representation of the \em refID identifier.
*/
void setRefID( const dstoute::aString& refID) { refID_ = refID; }
/**
* This function permits the optional \em description of the
* \em propertyDef element to be reset for this #PropertyDef instance.
* A \em propertyDef's \em description child element consists
* of a string of arbitrary length, which can include tabs and new lines as
* well as alphanumeric data. This means pretty formatting of the XML source
* will also appear in the returned description.
*
* If the instance has not been initialised from a DOM then this function
* permits it to be set before being written to an output XML based file.
*
* \param description a string representation of the description.
*/
void setDescription( const dstoute::aString& description)
{ description_ = description; }
/**
* This function provides the means to set the content of the property
* element within this #PropertyDef instance.
*
* \param property is a string containing the content to set for the property
* element of this #PropertyDef instance.
*/
void setProperty( const dstoute::aString& property)
{ propertyList_.clear(); propertyList_.push_back( property);}
/**
* This function provides the means to set the content of the property
* elements within this #PropertyDef instance.
*
* \param propertyList is a string list containing the contents to set for the property
* elements of this #PropertyDef instance.
*/
void setPropertyList( const dstoute::aStringList& propertyList)
{ propertyList_ = propertyList;}
/**
* This function is used to export the \em propertyDef data to a DAVE-ML
* compliant XML dataset file as defined by the DAVE-ML
* document type definition (DTD).
*
* \param documentElement an address to the parent DOM node/element.
*/
void exportDefinition( DomFunctions::XmlNode& documentElement);
// ---- Display functions. ----
// This function displays the contents of the class
friend std::ostream& operator<< ( std::ostream& os,
const PropertyDef& propertyDef);
// ---- Internally reference functions. ----
// Virtual functions overloading functions in the DomFunctions class.
void readDefinitionFromDom( const DomFunctions::XmlNode& elementDefinition );
bool compareElementID( const DomFunctions::XmlNode& xmlElement,
const dstoute::aString& elementID,
const size_t &documentElementReferenceIndex = 0);
// Function to reset the Janus pointer in the lower level classes
void resetJanus( Janus* janus);
protected:
// ---- Internally reference functions. ----
// private:
// ---- Internally reference functions. ----
/************************************************************************
* These are the variableDef elements, set up during instantiation.
*/
Janus* janus_;
ElementDefinitionEnum elementType_;
dstoute::aString name_;
dstoute::aString ptyID_;
dstoute::aString refID_;
dstoute::aString description_;
dstoute::aStringList propertyList_;
bool isProvenanceRef_;
bool hasProvenance_;
Provenance provenance_;
};
typedef std::vector<PropertyDef> PropertyDefList;
}
#endif /* _PROPERTYDEF_H_ */
| 40.966321 | 93 | 0.676722 | [
"vector"
] |
85f4418696e4d3aa8748c489d375e0b688281a49 | 51,252 | h | C | src/OrbitVulkanLayer/SubmissionTracker.h | mfkiwl/orbit | 59324e837ead5f4d47a7ee3fd8159cfdc7c2603e | [
"BSD-2-Clause"
] | null | null | null | src/OrbitVulkanLayer/SubmissionTracker.h | mfkiwl/orbit | 59324e837ead5f4d47a7ee3fd8159cfdc7c2603e | [
"BSD-2-Clause"
] | null | null | null | src/OrbitVulkanLayer/SubmissionTracker.h | mfkiwl/orbit | 59324e837ead5f4d47a7ee3fd8159cfdc7c2603e | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2020 The Orbit 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 ORBIT_VULKAN_LAYER_SUBMISSION_TRACKER_H_
#define ORBIT_VULKAN_LAYER_SUBMISSION_TRACKER_H_
#include <absl/container/flat_hash_map.h>
#include <absl/container/flat_hash_set.h>
#include <absl/synchronization/mutex.h>
#include <vulkan/vulkan.h>
#include <functional>
#include <queue>
#include <stack>
#include "OrbitBase/Logging.h"
#include "OrbitBase/Profiling.h"
#include "OrbitBase/ThreadUtils.h"
#include "VulkanLayerProducer.h"
namespace orbit_vulkan_layer {
/*
* This class is responsible for tracking command buffer and debug marker timings.
* To do so, it keeps track of command-buffer allocations, destructions, begins, ends as well as
* submissions.
* If we are capturing on `VkBeginCommandBuffer` and `VkEndCommandBuffer` it will insert write
* timestamp commands (`VkCmdWriteTimestamp`). The same is done for debug marker begins and ends.
* All that data will be gathered together at a queue submission (`VkQueueSubmit`).
*
* Upon every `VkQueuePresentKHR` it will check if the last timestamp of a certain submission is
* already available, and if so, it will assume that all timestamps are available and it will send
* the results over to the `VulkanLayerProducer`.
*
* See also `DispatchTable` (for vulkan dispatch), `TimerQueryPool` (to manage the timestamp slots),
* and `DeviceManager` (to retrieve device properties).
*
* Thread-Safety: This class is internally synchronized (using read/write locks), and can be
* safely accessed from different threads. This is needed, as in Vulkan submits and command buffer
* modifications can happen from multiple threads.
*/
template <class DispatchTable, class DeviceManager, class TimerQueryPool>
class SubmissionTracker : public VulkanLayerProducer::CaptureStatusListener {
public:
// On a submission (vkQueueSubmit), all pointers to command buffers become invalid/can be reused
// for a the next submission. The struct `QueueSubmission` gathers information (like timestamps
// and timer slots) about a concrete submission and their corresponding command buffers and debug
// markers. This way the information is "persistent" across submissions. We will create this
// struct at `vkQueuePresent` (right before the call into the driver -- and only if we are
// capturing) and add some information (in particular markers and a timestamp) right after the
// driver call. So, we will use `QueueSubmission` as a return value, and therefore these structs
// need to be public in the `SubmissionTracker`.
// Stores meta information about a submit (VkQueueSubmit), e.g. to allow to identify the matching
// Gpu tracepoint.
struct SubmissionMetaInformation {
uint64_t pre_submission_cpu_timestamp;
uint64_t post_submission_cpu_timestamp;
int32_t thread_id;
int32_t process_id;
};
// A persistent version of a command buffer that was submitted and its begin/end slot in the
// `TimerQueryPool`. Note that the begin is optional, as it might not be part of the capture.
// This struct is created if we capture the submission, so if we haven't captured the end,
// we also haven't captured the begin, and don't need to store info about that command buffer at
// all. The list of all `SubmittedCommandBuffer`s is stored in a `QueueSubmission`, and can so be
// associated to the `SubmissionMetaInformation`.
struct SubmittedCommandBuffer {
std::optional<uint32_t> command_buffer_begin_slot_index;
std::optional<uint32_t> command_buffer_end_slot_index;
// These are set when the timestamps were queried successfully. When these have values, the
// corresponding slot indices for timestamp queries have been reset. Do not query again in
// that case and only get the timestamps through these members.
std::optional<uint64_t> begin_timestamp;
std::optional<uint64_t> end_timestamp;
};
// A persistent version of a debug marker (either begin or end) that was submitted and its slot
// in the `TimerQueryPool`. `SubmittedMarkers` are used in `MarkerState` to identify the "begin"
// or "end" marker. All markers (`MarkerState`s) that gets *completed* within a certain submission
// are stored in the `QueueSubmission`.
// Note that we also store the `SubmissionMetaInformation` as "begin" markers can originate from
// different submissions than the matching end markers. This allows us e.g. to match the markers
// to a specific submission tracepoint.
struct SubmittedMarker {
SubmissionMetaInformation meta_information;
uint32_t slot_index;
// This is set when the timestamp was queried successfully. When this has a value, the
// corresponding slot index for the timestamp query has been reset. Do not query again in
// that case and only get the timestamp through this member.
std::optional<uint64_t> timestamp;
};
// Represents a color to be used to in debug markers. The values are all in range [0.f, 1.f].
struct Color {
float red;
float green;
float blue;
float alpha;
};
// Identifies a particular debug marker region that has been submitted via `vkQueueSubmit`.
// Note that we only store the state into `QueueSubmission`, if at that time we have a value for
// the end_info. Beside the information about the begin/end, it also stores the label name, color
// and the depth of the marker.
struct SubmittedMarkerSlice {
std::optional<SubmittedMarker> begin_info;
SubmittedMarker end_info;
std::string label_name;
Color color;
size_t depth;
};
// A single submission (VkQueueSubmit) can contain multiple `SubmitInfo`s. We keep this structure.
struct SubmitInfo {
std::vector<SubmittedCommandBuffer> command_buffers;
};
// Wraps up all the data that needs to be persistent upon a submission (VkQueueSubmit).
// `completed_markers` are all the debug markers that got completed (via "End") within this
// submission. Their "Begin" might still be in a different submission.
struct QueueSubmission {
VkQueue queue;
SubmissionMetaInformation meta_information;
std::vector<SubmitInfo> submit_infos;
std::vector<SubmittedMarkerSlice> completed_markers;
uint32_t num_begin_markers = 0;
};
explicit SubmissionTracker(DispatchTable* dispatch_table, TimerQueryPool* timer_query_pool,
DeviceManager* device_manager,
uint32_t max_local_marker_depth_per_command_buffer)
: dispatch_table_(dispatch_table),
timer_query_pool_(timer_query_pool),
device_manager_(device_manager),
max_local_marker_depth_per_command_buffer_(max_local_marker_depth_per_command_buffer) {
CHECK(dispatch_table_ != nullptr);
CHECK(timer_query_pool_ != nullptr);
CHECK(device_manager_ != nullptr);
}
// Sets a producer to be used to enqueue capture events and asks if we are capturing.
// We will also register ourselves as CaptureStatusListener, in order to get notified on
// capture finish (OnCaptureFinished). That's when we will reset the open query slots.
void SetVulkanLayerProducer(VulkanLayerProducer* vulkan_layer_producer) {
// De-register from the previous VulkanLayerProducer.
if (vulkan_layer_producer_ != nullptr) {
vulkan_layer_producer_->SetCaptureStatusListener(nullptr);
}
vulkan_layer_producer_ = vulkan_layer_producer;
// Register to the new VulkanLayerProducer.
if (vulkan_layer_producer_ != nullptr) {
vulkan_layer_producer_->SetCaptureStatusListener(this);
}
}
// Sets the maximum depth of debug markers within one command buffer. If set to 0, all debug
// markers will be discarded. If set to to std::numeric_limits<uint32_t>::max(), no debug marker
// will be discarded.
void SetMaxLocalMarkerDepthPerCommandBuffer(uint32_t max_local_marker_depth_per_command_buffer) {
max_local_marker_depth_per_command_buffer_ = max_local_marker_depth_per_command_buffer;
}
void TrackCommandBuffers(VkDevice device, VkCommandPool pool,
const VkCommandBuffer* command_buffers, uint32_t count) {
absl::WriterMutexLock lock(&mutex_);
auto associated_cbs_it = pool_to_command_buffers_.find(pool);
if (associated_cbs_it == pool_to_command_buffers_.end()) {
associated_cbs_it = pool_to_command_buffers_.try_emplace(pool).first;
}
for (uint32_t i = 0; i < count; ++i) {
VkCommandBuffer cb = command_buffers[i];
associated_cbs_it->second.insert(cb);
command_buffer_to_device_[cb] = device;
}
}
void UntrackCommandBuffers(VkDevice device, VkCommandPool pool,
const VkCommandBuffer* command_buffers, uint32_t count) {
absl::WriterMutexLock lock(&mutex_);
CHECK(pool_to_command_buffers_.contains(pool));
absl::flat_hash_set<VkCommandBuffer>& associated_command_buffers =
pool_to_command_buffers_.at(pool);
for (uint32_t i = 0; i < count; ++i) {
VkCommandBuffer command_buffer = command_buffers[i];
associated_command_buffers.erase(command_buffer);
// vkFreeCommandBuffers (and thus this method) can be also called on command bufers in
// "recording" or executable state and has similar effect as vkResetCommandBuffer has.
// In `OnCaptureFinished`, we reset all the timer slots left in `command_buffer_to_state_`.
// If we would not reset them here and clear the state, we would try to reset those command
// buffers there. However, the mapping to the device (which is needed) would be missing.
if (command_buffer_to_state_.contains(command_buffer)) {
// Note: This will "rollback" the slot indices (rather then actually resetting them on the
// Gpu). This is fine, as we remove the command buffer state right after submission. Thus,
// There can not be a value in the respective slot.
ResetCommandBufferUnsafe(command_buffer);
command_buffer_to_state_.erase(command_buffer);
}
CHECK(command_buffer_to_device_.contains(command_buffer));
CHECK(command_buffer_to_device_.at(command_buffer) == device);
command_buffer_to_device_.erase(command_buffer);
}
if (associated_command_buffers.empty()) {
pool_to_command_buffers_.erase(pool);
}
}
void MarkCommandBufferBegin(VkCommandBuffer command_buffer) {
absl::WriterMutexLock lock(&mutex_);
// Even when we are not capturing we create state for this command buffer to allow the
// debug marker tracking. In order to compute the correct depth of a debug marker and being able
// to match an "end" marker with the corresponding "begin" marker, we maintain a stack of all
// debug markers of a queue. The order of the markers is determined upon submission based on the
// order within the submitted command buffers. Thus, even when not capturing, we create an empty
// state here that allows us to store the debug markers into it and maintain that stack on
// submission. We will not write timestamps in this case and thus don't store any information
// other than the debug markers then.
{
if (command_buffer_to_state_.contains(command_buffer)) {
// We end up in this case, if we have used the command buffer before and want to write new
// commands to it without resetting the command buffer. Per specification,
// "vkBeginCommandBuffer" does also reset the command buffer, in addition to putting it
// into the executable state.
ResetCommandBufferUnsafe(command_buffer);
}
command_buffer_to_state_[command_buffer] = {};
}
if (!is_capturing_) {
return;
}
uint32_t slot_index;
if (RecordTimestamp(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, &slot_index)) {
CHECK(command_buffer_to_state_.contains(command_buffer));
command_buffer_to_state_.at(command_buffer).command_buffer_begin_slot_index =
std::make_optional(slot_index);
}
}
void MarkCommandBufferEnd(VkCommandBuffer command_buffer) {
absl::WriterMutexLock lock(&mutex_);
if (!is_capturing_) {
return;
}
if (!command_buffer_to_state_.contains(command_buffer)) {
ERROR_ONCE(
"Calling vkEndCommandBuffer on a command buffer that is in the initial state "
"(i.e. either freshly allocated or reset with vkResetCommandBuffer).");
return;
}
uint32_t slot_index;
if (RecordTimestamp(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, &slot_index)) {
// MarkCommandBufferBegin/End are called from within the same submit, and as the
// `MarkCommandBufferBegin` will always insert the state, we can assume that it is there.
CHECK(command_buffer_to_state_.contains(command_buffer));
CommandBufferState& command_buffer_state = command_buffer_to_state_.at(command_buffer);
command_buffer_state.command_buffer_end_slot_index = std::make_optional(slot_index);
}
}
void MarkDebugMarkerBegin(VkCommandBuffer command_buffer, const char* text, Color color) {
absl::WriterMutexLock lock(&mutex_);
// It is ensured by the Vulkan spec. that `text` must not be nullptr.
CHECK(text != nullptr);
bool marker_depth_exceeds_maximum;
{
if (!command_buffer_to_state_.contains(command_buffer)) {
ERROR_ONCE(
"Calling vkCmdDebugMarkerBeginEXT/vkCmdBeginDebugUtilsLabelEXT on a command buffer "
"that is in the initial state (i.e. either freshly allocated or reset with "
"vkResetCommandBuffer).");
return;
}
CHECK(command_buffer_to_state_.contains(command_buffer));
CommandBufferState& state = command_buffer_to_state_.at(command_buffer);
++state.local_marker_stack_size;
marker_depth_exceeds_maximum =
state.local_marker_stack_size > max_local_marker_depth_per_command_buffer_;
Marker marker{.type = MarkerType::kDebugMarkerBegin,
.label_name = std::string(text),
.color = color,
.cut_off = marker_depth_exceeds_maximum};
state.markers.emplace_back(std::move(marker));
}
if (!is_capturing_ || marker_depth_exceeds_maximum) {
return;
}
uint32_t slot_index;
if (RecordTimestamp(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, &slot_index)) {
CHECK(command_buffer_to_state_.contains(command_buffer));
CommandBufferState& state = command_buffer_to_state_.at(command_buffer);
state.markers.back().slot_index = std::make_optional(slot_index);
}
}
void MarkDebugMarkerEnd(VkCommandBuffer command_buffer) {
absl::WriterMutexLock lock(&mutex_);
bool marker_depth_exceeds_maximum;
if (!command_buffer_to_state_.contains(command_buffer)) {
ERROR_ONCE(
"Calling vkCmdDebugMarkerEndEXT/vkCmdEndDebugUtilsLabelEXT on a command buffer "
"that is in the initial state (i.e. either freshly allocated or reset with "
"vkResetCommandBuffer).");
return;
}
CHECK(command_buffer_to_state_.contains(command_buffer));
CommandBufferState& state = command_buffer_to_state_.at(command_buffer);
marker_depth_exceeds_maximum =
state.local_marker_stack_size > max_local_marker_depth_per_command_buffer_;
Marker marker{.type = MarkerType::kDebugMarkerEnd, .cut_off = marker_depth_exceeds_maximum};
state.markers.emplace_back(std::move(marker));
// We might see more "ends" than "begins", as the "begins" can be on a different command
// buffer.
if (state.local_marker_stack_size > 0) {
--state.local_marker_stack_size;
}
if (!is_capturing_ || marker_depth_exceeds_maximum) {
return;
}
uint32_t slot_index;
if (RecordTimestamp(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, &slot_index)) {
CHECK(command_buffer_to_state_.contains(command_buffer));
CommandBufferState& state = command_buffer_to_state_.at(command_buffer);
state.markers.back().slot_index = std::make_optional(slot_index);
}
}
// After command buffers are submitted into a queue, they can be reused for further operations.
// Thus, our identification via the pointers becomes invalid. We will use the vkQueueSubmit
// to make our data persistent until we have processed the results of the execution of these
// command buffers (which will be done in the vkQueuePresentKHR).
// If we are not capturing, that method will do nothing and return `nullopt`.
// Otherwise, it will create and return an QueueSubmission object, holding the
// information about all command buffers recorded in this submission.
// It also takes a timestamp before the execution of the driver code for the submission.
// This allows us to map submissions from the Vulkan layer to the driver submissions.
[[nodiscard]] std::optional<QueueSubmission> PersistCommandBuffersOnSubmit(
VkQueue queue, uint32_t submit_count, const VkSubmitInfo* submits) {
absl::WriterMutexLock lock(&mutex_);
if (!is_capturing_) {
// `OnCaptureFinished` has already been called and has taken care of resetting slots.
return std::nullopt;
}
VkDevice device = VK_NULL_HANDLE;
// Collect slots of command buffer "begins" that are baked into the command buffer but for which
// the "end" is missing. We will never read those, but need to wait until the command buffer
// gets reset.
std::vector<uint32_t> query_slots_not_needed_to_read;
QueueSubmission queue_submission;
queue_submission.queue = queue;
queue_submission.meta_information.pre_submission_cpu_timestamp =
orbit_base::CaptureTimestampNs();
queue_submission.meta_information.thread_id = orbit_base::GetCurrentThreadId();
queue_submission.meta_information.process_id = orbit_base::GetCurrentProcessId();
for (uint32_t submit_index = 0; submit_index < submit_count; ++submit_index) {
VkSubmitInfo submit_info = submits[submit_index];
queue_submission.submit_infos.emplace_back();
SubmitInfo& submitted_submit_info = queue_submission.submit_infos.back();
for (uint32_t command_buffer_index = 0; command_buffer_index < submit_info.commandBufferCount;
++command_buffer_index) {
VkCommandBuffer command_buffer = submit_info.pCommandBuffers[command_buffer_index];
PersistSingleCommandBufferOnSubmit(device, command_buffer, &queue_submission,
&submitted_submit_info, &query_slots_not_needed_to_read);
}
}
// Slots here will not be reset twice, but remain marked as unavailable until the command
// buffers are done executing and "vkResetCommandBuffer" was called. The slots are still baked
// into the command buffers that were sent to the GPU. Using the same slots again would likely
// lead to wrong results.
if (!query_slots_not_needed_to_read.empty()) {
timer_query_pool_->MarkQuerySlotsDoneReading(device, query_slots_not_needed_to_read);
}
return queue_submission;
}
// This method is supposed to be called right after the driver call of `vkQueuePresent`.
// At that point in time we can complete the submission meta information (add the timestamp) and
// know the order of the debug markers across command buffers. We will maintain the debug marker
// stack in `queue_to_markers_` and if capturing also write the information about completed debug
// markers into the `QueueSubmission`, to make it persistent across submissions and such that it
// can be picked up later (on a vkQueuePresentKHR) to retrieve the timer results and send the data
// to the client.
//
// We assume to be capturing if `queue_submission_optional` has content, i.e. we were capturing
// on this VkQueueSubmit before calling into the driver.
// The meta information allows us to map submissions from the Vulkan layer to the driver
// submissions.
void PersistDebugMarkersOnSubmit(VkQueue queue, uint32_t submit_count,
const VkSubmitInfo* submits,
std::optional<QueueSubmission> queue_submission_optional) {
absl::WriterMutexLock lock(&mutex_);
if (!queue_to_markers_.contains(queue)) {
queue_to_markers_[queue] = {};
}
CHECK(queue_to_markers_.contains(queue));
QueueMarkerState& markers = queue_to_markers_.at(queue);
// If we consider that we are still capturing, take a cpu timestamp as "post submission" such
// that the submission "meta information" is complete. We can then attach that also to each
// debug marker, as they may span across different submissions.
if (queue_submission_optional.has_value()) {
queue_submission_optional->meta_information.post_submission_cpu_timestamp =
orbit_base::CaptureTimestampNs();
}
std::vector<uint32_t> marker_slots_not_needed_to_read;
VkDevice device = VK_NULL_HANDLE;
for (uint32_t submit_index = 0; submit_index < submit_count; ++submit_index) {
VkSubmitInfo submit_info = submits[submit_index];
for (uint32_t command_buffer_index = 0; command_buffer_index < submit_info.commandBufferCount;
++command_buffer_index) {
VkCommandBuffer command_buffer = submit_info.pCommandBuffers[command_buffer_index];
if (device == VK_NULL_HANDLE) {
CHECK(command_buffer_to_device_.contains(command_buffer));
device = command_buffer_to_device_.at(command_buffer);
}
PersistDebugMarkersOfASingleCommandBufferOnSubmit(
command_buffer, &queue_submission_optional, &markers, &marker_slots_not_needed_to_read);
}
}
if (!marker_slots_not_needed_to_read.empty()) {
timer_query_pool_->MarkQuerySlotsDoneReading(device, marker_slots_not_needed_to_read);
}
if (!queue_submission_optional.has_value()) {
return;
}
if (!queue_to_submission_priority_queue_.contains(queue)) {
queue_to_submission_priority_queue_.emplace(queue, kPreSubmissionCpuTimestampComparator);
}
queue_to_submission_priority_queue_.at(queue).emplace(
std::move(queue_submission_optional.value()));
}
// This method is responsible for retrieving all the timestamps for the "completed" submissions,
// for transforming the information of those submissions (in particular about the command buffers
// and debug markers) into the `GpuQueueSubmission` proto, and for sending it to the
// `VulkanLayerProducer`. We consider a submission to be "completed" when all timestamps that are
// associated with this submission are ready.
// We maintain a priority queue (for every `VkQueue`) `submissions_queue_` and process submissions
// with the oldest CPU timestamp, until we encounter the first "incomplete" submission.
// This way, we ensure that we will send the submission information per queue ordered by the
// CPU timestamp.
// Beside the timestamps of command buffers and the meta information of the submission, the proto
// also contains the debug markers, "begin" (even if submitted in a different submission) and
// "end", that got completed in this submission.
// See also `WriteMetaInfo`, `WriteCommandBufferTimings` and `WriteDebugMarkers`.
// This method also resets all the timer slots that have been read.
// It is assumed to be called periodically, e.g. on `vkQueuePresentKHR`.
void CompleteSubmits(VkDevice device) {
absl::WriterMutexLock lock(&mutex_);
VkQueryPool query_pool = timer_query_pool_->GetQueryPool(device);
if (queue_to_submission_priority_queue_.empty()) {
return;
}
VkPhysicalDevice physical_device = device_manager_->GetPhysicalDeviceOfLogicalDevice(device);
const float timestamp_period =
device_manager_->GetPhysicalDeviceProperties(physical_device).limits.timestampPeriod;
std::vector<uint32_t> query_slots_done_reading = {};
std::vector<QueueSubmission> submissions_to_send = {};
// The submits of a specific queue in `submissions_queue_` are sorted by "pre submission CPU"
// timestamp and we want to make sure we send events to the client in that order. Therefore, we
// stop as soon as a query failed.
for (auto& [unused_queue, submissions] : queue_to_submission_priority_queue_) {
while (!submissions.empty()) {
QueueSubmission completed_submission = submissions.top();
submissions.pop();
bool command_buffer_queries_succeeded = QueryCommandBufferTimestamps(
&completed_submission, &query_slots_done_reading, device, query_pool, timestamp_period);
// We only need to read the debug marker timestamps, if querying the command buffers
// succeeded.
bool marker_queries_succeeded = false;
if (command_buffer_queries_succeeded) {
marker_queries_succeeded =
QueryDebugMarkerTimestamps(&completed_submission, &query_slots_done_reading, device,
query_pool, timestamp_period);
}
if (command_buffer_queries_succeeded && marker_queries_succeeded) {
submissions_to_send.emplace_back(std::move(completed_submission));
} else {
submissions.emplace(std::move(completed_submission));
break;
}
}
}
for (const auto& completed_submission : submissions_to_send) {
orbit_grpc_protos::ProducerCaptureEvent capture_event;
orbit_grpc_protos::GpuQueueSubmission* submission_proto =
capture_event.mutable_gpu_queue_submission();
WriteMetaInfo(completed_submission.meta_information, submission_proto->mutable_meta_info());
bool has_command_buffer_timestamps =
WriteCommandBufferTimings(completed_submission, submission_proto);
bool has_debug_marker_timestamps = WriteDebugMarkers(completed_submission, submission_proto);
if (vulkan_layer_producer_ != nullptr &&
(has_command_buffer_timestamps || has_debug_marker_timestamps)) {
vulkan_layer_producer_->EnqueueCaptureEvent(std::move(capture_event));
}
}
if (!query_slots_done_reading.empty()) {
timer_query_pool_->MarkQuerySlotsDoneReading(device, query_slots_done_reading);
}
}
void ResetCommandBuffer(VkCommandBuffer command_buffer) {
absl::WriterMutexLock lock(&mutex_);
ResetCommandBufferUnsafe(command_buffer);
}
void ResetCommandPool(VkCommandPool command_pool) {
absl::flat_hash_set<VkCommandBuffer> command_buffers;
{
absl::ReaderMutexLock lock(&mutex_);
if (!pool_to_command_buffers_.contains(command_pool)) {
return;
}
CHECK(pool_to_command_buffers_.contains(command_pool));
command_buffers = pool_to_command_buffers_.at(command_pool);
}
for (const auto& command_buffer : command_buffers) {
ResetCommandBuffer(command_buffer);
}
}
void OnCaptureStart(orbit_grpc_protos::CaptureOptions capture_options) override {
absl::WriterMutexLock lock(&mutex_);
SetMaxLocalMarkerDepthPerCommandBuffer(
capture_options.max_local_marker_depth_per_command_buffer());
is_capturing_ = true;
}
void OnCaptureStop() override {}
void OnCaptureFinished() override {
absl::WriterMutexLock lock(&mutex_);
std::vector<uint32_t> slots_not_needed_to_read_anymore;
VkDevice device = VK_NULL_HANDLE;
for (auto& [command_buffer, command_buffer_state] : command_buffer_to_state_) {
if (command_buffer_state.pre_submission_cpu_timestamp.has_value()) continue;
if (device == VK_NULL_HANDLE) {
CHECK(command_buffer_to_device_.contains(command_buffer));
device = command_buffer_to_device_.at(command_buffer);
}
if (command_buffer_state.command_buffer_begin_slot_index.has_value()) {
slots_not_needed_to_read_anymore.push_back(
command_buffer_state.command_buffer_begin_slot_index.value());
command_buffer_state.command_buffer_begin_slot_index.reset();
}
if (command_buffer_state.command_buffer_end_slot_index.has_value()) {
slots_not_needed_to_read_anymore.push_back(
command_buffer_state.command_buffer_end_slot_index.value());
command_buffer_state.command_buffer_end_slot_index.reset();
}
for (Marker& marker : command_buffer_state.markers) {
if (marker.slot_index.has_value()) {
slots_not_needed_to_read_anymore.push_back(marker.slot_index.value());
marker.slot_index.reset();
}
}
}
if (!slots_not_needed_to_read_anymore.empty()) {
timer_query_pool_->MarkQuerySlotsDoneReading(device, slots_not_needed_to_read_anymore);
}
is_capturing_ = false;
}
private:
enum class MarkerType { kDebugMarkerBegin = 0, kDebugMarkerEnd };
struct Marker {
MarkerType type;
std::optional<uint32_t> slot_index;
std::optional<std::string> label_name;
std::optional<Color> color;
bool cut_off;
};
// We have a stack of all markers of a queue that gets updated upon a submission (VkQueueSubmit).
// So on a submitted "begin" marker, we create that struct and push it to the stack. On an "end",
// we pop from that stack, and if we are capturing we complete the information and move it to the
// completed markers of a `QueueSubmission`.
// If a debug marker begin was discarded because of its depth, `depth_exceeds_maximum` is set to
// true. This allows end markers on a different submission to also throw the end marker away.
//
// Example: Max Depth = 1
// Submission 1: Begin("Foo"), Begin("Bar) -- For "Bar" we set `depth_exceeds_maximum` to true.
// Submission 2: End("Bar"), End("Foo") -- We now know that the first end needs to be thrown away.
struct MarkerState {
std::optional<SubmittedMarker> begin_info;
std::string label_name;
Color color;
size_t depth;
bool depth_exceeds_maximum;
};
struct QueueMarkerState {
std::stack<MarkerState> marker_stack;
};
struct CommandBufferState {
std::optional<uint32_t> command_buffer_begin_slot_index;
std::optional<uint32_t> command_buffer_end_slot_index;
std::optional<uint64_t> pre_submission_cpu_timestamp;
std::vector<Marker> markers;
uint32_t local_marker_stack_size;
};
bool RecordTimestamp(VkCommandBuffer command_buffer, VkPipelineStageFlagBits pipeline_stage_flags,
uint32_t* slot_index) {
mutex_.AssertReaderHeld();
VkDevice device;
{
CHECK(command_buffer_to_device_.contains(command_buffer));
device = command_buffer_to_device_.at(command_buffer);
}
VkQueryPool query_pool = timer_query_pool_->GetQueryPool(device);
if (!timer_query_pool_->NextReadyQuerySlot(device, slot_index)) {
// TODO(b/192998580): Send an appropriate CaptureEvent to notify the client that the Vulkan
// layer was out of query slots in a certain time range.
return false;
}
dispatch_table_->CmdWriteTimestamp(command_buffer)(command_buffer, pipeline_stage_flags,
query_pool, *slot_index);
return true;
}
std::optional<uint64_t> QueryGpuTimestampNs(VkDevice device, VkQueryPool query_pool,
uint32_t slot_index, float timestamp_period) {
static constexpr VkDeviceSize kResultStride = sizeof(uint64_t);
uint64_t timestamp = 0;
VkResult result_status = dispatch_table_->GetQueryPoolResults(device)(
device, query_pool, slot_index, 1, sizeof(timestamp), ×tamp, kResultStride,
VK_QUERY_RESULT_64_BIT);
if (result_status != VK_SUCCESS) {
return std::nullopt;
}
return static_cast<uint64_t>(static_cast<double>(timestamp) * timestamp_period);
}
static void WriteMetaInfo(const SubmissionMetaInformation& meta_info,
orbit_grpc_protos::GpuQueueSubmissionMetaInfo* target_proto) {
target_proto->set_tid(meta_info.thread_id);
target_proto->set_pid(meta_info.process_id);
target_proto->set_pre_submission_cpu_timestamp(meta_info.pre_submission_cpu_timestamp);
target_proto->set_post_submission_cpu_timestamp(meta_info.post_submission_cpu_timestamp);
}
[[nodiscard]] bool QuerySingleCommandBufferTimestamps(SubmittedCommandBuffer* command_buffer,
std::vector<uint32_t>* query_slots_to_reset,
VkDevice device, VkQueryPool query_pool,
float timestamp_period) {
CHECK(command_buffer != nullptr);
if (!command_buffer->end_timestamp.has_value()) {
CHECK(command_buffer->command_buffer_end_slot_index.has_value());
uint32_t slot_index = command_buffer->command_buffer_end_slot_index.value();
std::optional<uint64_t> end_timestamp =
QueryGpuTimestampNs(device, query_pool, slot_index, timestamp_period);
if (end_timestamp.has_value()) {
command_buffer->end_timestamp = end_timestamp;
query_slots_to_reset->push_back(slot_index);
} else {
return false;
}
}
// It's possible that the command begin was not recorded, so we have to check if there is even
// a query slot index for the begin timestamp before we try to query it.
if (!command_buffer->command_buffer_begin_slot_index.has_value()) {
return true;
}
if (!command_buffer->begin_timestamp.has_value()) {
uint32_t slot_index = command_buffer->command_buffer_begin_slot_index.value();
std::optional<uint64_t> begin_timestamp =
QueryGpuTimestampNs(device, query_pool, slot_index, timestamp_period);
if (begin_timestamp.has_value()) {
command_buffer->begin_timestamp = begin_timestamp;
query_slots_to_reset->push_back(slot_index);
} else {
return false;
}
}
return true;
}
[[nodiscard]] bool QueryCommandBufferTimestamps(QueueSubmission* completed_submission,
std::vector<uint32_t>* query_slots_to_reset,
VkDevice device, VkQueryPool query_pool,
float timestamp_period) {
for (auto& completed_submit : completed_submission->submit_infos) {
for (auto& completed_command_buffer : completed_submit.command_buffers) {
bool queries_succeeded = QuerySingleCommandBufferTimestamps(
&completed_command_buffer, query_slots_to_reset, device, query_pool, timestamp_period);
if (!queries_succeeded) return false;
}
}
return true;
}
[[nodiscard]] bool QuerySingleDebugMarkerTimestamps(SubmittedMarkerSlice* marker_slice,
std::vector<uint32_t>* query_slots_to_reset,
VkDevice device, VkQueryPool query_pool,
float timestamp_period) {
CHECK(marker_slice != nullptr);
if (!marker_slice->end_info.timestamp.has_value()) {
std::optional<uint64_t> end_timestamp = QueryGpuTimestampNs(
device, query_pool, marker_slice->end_info.slot_index, timestamp_period);
if (end_timestamp.has_value()) {
marker_slice->end_info.timestamp = end_timestamp;
query_slots_to_reset->push_back(marker_slice->end_info.slot_index);
} else {
return false;
}
}
if (!marker_slice->begin_info.has_value()) {
return true;
}
if (!marker_slice->begin_info->timestamp.has_value()) {
std::optional<uint64_t> begin_timestamp = QueryGpuTimestampNs(
device, query_pool, marker_slice->begin_info->slot_index, timestamp_period);
if (begin_timestamp.has_value()) {
marker_slice->begin_info->timestamp = begin_timestamp;
query_slots_to_reset->push_back(marker_slice->begin_info->slot_index);
} else {
return false;
}
}
return true;
}
[[nodiscard]] bool QueryDebugMarkerTimestamps(QueueSubmission* completed_submission,
std::vector<uint32_t>* query_slots_to_reset,
VkDevice device, VkQueryPool query_pool,
float timestamp_period) {
for (auto& marker_slice : completed_submission->completed_markers) {
bool queries_succeeded = QuerySingleDebugMarkerTimestamps(
&marker_slice, query_slots_to_reset, device, query_pool, timestamp_period);
if (!queries_succeeded) return false;
}
return true;
}
[[nodiscard]] bool WriteCommandBufferTimings(
const QueueSubmission& completed_submission,
orbit_grpc_protos::GpuQueueSubmission* submission_proto) {
bool has_at_least_one_timestamp = false;
for (const auto& completed_submit : completed_submission.submit_infos) {
orbit_grpc_protos::GpuSubmitInfo* submit_info_proto = submission_proto->add_submit_infos();
for (const auto& completed_command_buffer : completed_submit.command_buffers) {
orbit_grpc_protos::GpuCommandBuffer* command_buffer_proto =
submit_info_proto->add_command_buffers();
if (completed_command_buffer.command_buffer_begin_slot_index.has_value()) {
// This function must only be called once queries have actually succeeded. If this command
// buffer has a slot index for the begin timestamp, we must have a value here.
CHECK(completed_command_buffer.begin_timestamp.has_value());
command_buffer_proto->set_begin_gpu_timestamp_ns(
completed_command_buffer.begin_timestamp.value());
}
// Similarly here, this function must only be called once timestamp queries have succeeded,
// and therefore we must have an end timestamp here.
CHECK(completed_command_buffer.end_timestamp.has_value());
command_buffer_proto->set_end_gpu_timestamp_ns(
completed_command_buffer.end_timestamp.value());
has_at_least_one_timestamp = true;
}
}
return has_at_least_one_timestamp;
}
[[nodiscard]] bool WriteDebugMarkers(const QueueSubmission& completed_submission,
orbit_grpc_protos::GpuQueueSubmission* submission_proto) {
submission_proto->set_num_begin_markers(completed_submission.num_begin_markers);
bool has_at_least_one_timestamp = false;
for (const auto& marker_state : completed_submission.completed_markers) {
CHECK(marker_state.end_info.timestamp.has_value());
uint64_t end_timestamp = marker_state.end_info.timestamp.value();
has_at_least_one_timestamp = true;
orbit_grpc_protos::GpuDebugMarker* marker_proto = submission_proto->add_completed_markers();
if (vulkan_layer_producer_ != nullptr) {
marker_proto->set_text_key(
vulkan_layer_producer_->InternStringIfNecessaryAndGetKey(marker_state.label_name));
}
auto quantize = [](float value) { return static_cast<uint8_t>(value * 255.f); };
// We have seen near 0.f color values in all four components "in the wild", so we check if the
// quantized values are not zero here to make sure these markers are rendered with an actual
// color.
if (quantize(marker_state.color.red) != 0 || quantize(marker_state.color.green) != 0 ||
quantize(marker_state.color.blue) != 0 || quantize(marker_state.color.alpha) != 0) {
auto* color = marker_proto->mutable_color();
color->set_red(marker_state.color.red);
color->set_green(marker_state.color.green);
color->set_blue(marker_state.color.blue);
color->set_alpha(marker_state.color.alpha);
}
marker_proto->set_depth(marker_state.depth);
marker_proto->set_end_gpu_timestamp_ns(end_timestamp);
// If we haven't captured the begin marker, we'll leave the optional begin_marker empty.
if (!marker_state.begin_info.has_value()) {
continue;
}
orbit_grpc_protos::GpuDebugMarkerBeginInfo* begin_debug_marker_proto =
marker_proto->mutable_begin_marker();
WriteMetaInfo(marker_state.begin_info->meta_information,
begin_debug_marker_proto->mutable_meta_info());
CHECK(marker_state.begin_info->timestamp.has_value());
uint64_t begin_timestamp = marker_state.begin_info->timestamp.value();
begin_debug_marker_proto->set_gpu_timestamp_ns(begin_timestamp);
}
return has_at_least_one_timestamp;
}
// This method does not acquire a lock and MUST NOT be called without holding the `mutex_`.
void ResetCommandBufferUnsafe(VkCommandBuffer command_buffer) {
mutex_.AssertHeld();
if (!command_buffer_to_state_.contains(command_buffer)) {
return;
}
CHECK(command_buffer_to_state_.contains(command_buffer));
CommandBufferState& state = command_buffer_to_state_.at(command_buffer);
CHECK(command_buffer_to_device_.contains(command_buffer));
VkDevice device = command_buffer_to_device_.at(command_buffer);
std::vector<uint32_t> query_slots_to_reset{};
if (state.command_buffer_begin_slot_index.has_value()) {
query_slots_to_reset.push_back(state.command_buffer_begin_slot_index.value());
}
if (state.command_buffer_end_slot_index.has_value()) {
query_slots_to_reset.push_back(state.command_buffer_end_slot_index.value());
}
for (const Marker& marker : state.markers) {
if (marker.slot_index.has_value()) {
query_slots_to_reset.push_back(marker.slot_index.value());
}
}
if (state.pre_submission_cpu_timestamp.has_value()) {
timer_query_pool_->MarkQuerySlotsForReset(device, query_slots_to_reset);
} else {
timer_query_pool_->RollbackPendingQuerySlots(device, query_slots_to_reset);
}
command_buffer_to_state_.erase(command_buffer);
}
void PersistSingleCommandBufferOnSubmit(VkDevice device, VkCommandBuffer command_buffer,
QueueSubmission* queue_submission,
SubmitInfo* submitted_submit_info,
std::vector<uint32_t>* query_slots_not_needed_to_read) {
mutex_.AssertHeld();
CHECK(queue_submission != nullptr);
CHECK(submitted_submit_info != nullptr);
CHECK(query_slots_not_needed_to_read != nullptr);
if (!command_buffer_to_state_.contains(command_buffer)) {
ERROR_ONCE(
"Calling vkQueueSubmit on a command buffer that is in the initial state (i.e. "
"either freshly allocated or reset with vkResetCommandBuffer).");
return;
}
CHECK(command_buffer_to_state_.contains(command_buffer));
CommandBufferState& state = command_buffer_to_state_.at(command_buffer);
bool has_been_submitted_before = state.pre_submission_cpu_timestamp.has_value();
// Mark that this command buffer in the current state was already submitted. If the command
// buffer is being submitted again, without a "vkResetCommandBuffer" call, the same slot
// indices will be used again, so that we can not distinguish the results for the different
// submissions anymore. Thus, this field will be used to ensure to not try to read such a
// slot. Calling "vkResetCommandBuffer" (or "vkBeginCommandBuffer"), will reset this field.
// Note that we are using an std::optional with the submission time to protect us against an
// "OnCaptureFinished" call, right between pre and post submission, which would try to reset
// the slots.
state.pre_submission_cpu_timestamp =
queue_submission->meta_information.pre_submission_cpu_timestamp;
if (device == VK_NULL_HANDLE) {
device = command_buffer_to_device_.at(command_buffer);
}
// If we haven't recorded neither the end nor the begin of a command buffer, we have no
// information to send.
if (!state.command_buffer_end_slot_index.has_value()) {
if (state.command_buffer_begin_slot_index.has_value()) {
// We need to discard the begin slot when we only have a begin slot. This can happen
// if we run out of query slots.
query_slots_not_needed_to_read->push_back(state.command_buffer_begin_slot_index.value());
state.command_buffer_begin_slot_index.reset();
}
return;
}
// If this command buffer was already submitted before (without reset afterwards), its slot
// indices are not unique anymore and can't be used by us. Note, that the slots will be
// marked as "done with reading" when the first submission of this command buffer is done
// and will eventually be reset on a "vkResetCommandBuffer" call.
if (!has_been_submitted_before) {
SubmittedCommandBuffer submitted_command_buffer{
.command_buffer_begin_slot_index = state.command_buffer_begin_slot_index,
.command_buffer_end_slot_index = state.command_buffer_end_slot_index.value()};
submitted_submit_info->command_buffers.emplace_back(submitted_command_buffer);
}
}
void PersistDebugMarkersOfASingleCommandBufferOnSubmit(
VkCommandBuffer command_buffer, std::optional<QueueSubmission>* queue_submission_optional,
QueueMarkerState* markers, std::vector<uint32_t>* marker_slots_not_needed_to_read) {
mutex_.AssertHeld();
CHECK(queue_submission_optional != nullptr);
CHECK(markers != nullptr);
CHECK(marker_slots_not_needed_to_read != nullptr);
if (!command_buffer_to_state_.contains(command_buffer)) {
ERROR_ONCE(
"Calling vkQueueSubmit on a command buffer that is in the initial state (i.e. "
"either freshly allocated or reset with vkResetCommandBuffer).");
return;
}
CHECK(command_buffer_to_state_.contains(command_buffer));
const CommandBufferState& state = command_buffer_to_state_.at(command_buffer);
for (const Marker& marker : state.markers) {
std::optional<SubmittedMarker> submitted_marker = std::nullopt;
CHECK(!queue_submission_optional->has_value() ||
state.pre_submission_cpu_timestamp.has_value());
if (marker.slot_index.has_value() && queue_submission_optional->has_value() &&
(state.pre_submission_cpu_timestamp.value() ==
queue_submission_optional->value().meta_information.pre_submission_cpu_timestamp)) {
submitted_marker = {.meta_information = queue_submission_optional->value().meta_information,
.slot_index = marker.slot_index.value()};
}
switch (marker.type) {
case MarkerType::kDebugMarkerBegin: {
if (queue_submission_optional->has_value() && marker.slot_index.has_value()) {
++queue_submission_optional->value().num_begin_markers;
}
CHECK(marker.label_name.has_value());
CHECK(marker.color.has_value());
MarkerState marker_state{.begin_info = submitted_marker,
.label_name = marker.label_name.value(),
.color = marker.color.value(),
.depth = markers->marker_stack.size(),
.depth_exceeds_maximum = marker.cut_off};
markers->marker_stack.push(std::move(marker_state));
break;
}
case MarkerType::kDebugMarkerEnd: {
MarkerState marker_state = markers->marker_stack.top();
markers->marker_stack.pop();
// If there is a begin marker slot from a previous submission, this is our chance to
// state that we will not read the slot anymore. We can reset is as soon as the
// command buffer itself gets reset.
if (marker_state.begin_info.has_value() && !queue_submission_optional->has_value()) {
marker_slots_not_needed_to_read->push_back(marker_state.begin_info->slot_index);
}
// If the begin marker was discarded for exceeding the maximum depth, but the end
// marker was not (as it is in a different submission), we will not read the slot in
// "CompleteSubmits". We can reset is as soon as the command buffer itself gets reset.
if (marker_state.depth_exceeds_maximum && marker.slot_index.has_value()) {
marker_slots_not_needed_to_read->push_back(marker.slot_index.value());
}
if (queue_submission_optional->has_value() && marker.slot_index.has_value() &&
!marker_state.depth_exceeds_maximum) {
CHECK(submitted_marker.has_value());
queue_submission_optional->value().completed_markers.emplace_back(
SubmittedMarkerSlice{.begin_info = marker_state.begin_info,
.end_info = submitted_marker.value(),
.label_name = std::move(marker_state.label_name),
.color = marker_state.color,
.depth = marker_state.depth});
}
break;
}
}
}
}
absl::Mutex mutex_;
absl::flat_hash_map<VkCommandPool, absl::flat_hash_set<VkCommandBuffer>> pool_to_command_buffers_;
absl::flat_hash_map<VkCommandBuffer, VkDevice> command_buffer_to_device_;
absl::flat_hash_map<VkCommandBuffer, CommandBufferState> command_buffer_to_state_;
static constexpr auto kPreSubmissionCpuTimestampComparator =
[](const QueueSubmission& lhs, const QueueSubmission& rhs) -> bool {
return lhs.meta_information.pre_submission_cpu_timestamp >
rhs.meta_information.pre_submission_cpu_timestamp;
};
absl::flat_hash_map<VkQueue,
std::priority_queue<QueueSubmission, std::vector<QueueSubmission>,
std::function<bool(QueueSubmission, QueueSubmission)>>>
queue_to_submission_priority_queue_;
absl::flat_hash_map<VkQueue, QueueMarkerState> queue_to_markers_;
DispatchTable* dispatch_table_;
TimerQueryPool* timer_query_pool_;
DeviceManager* device_manager_;
// We use std::numeric_limits<uint32_t>::max() to disable filtering of markers and 0 to discard
// all debug markers.
uint32_t max_local_marker_depth_per_command_buffer_ = std::numeric_limits<uint32_t>::max();
VulkanLayerProducer* vulkan_layer_producer_ = nullptr;
// This boolean is precisely true between a call to OnCaptureStart and OnCaptureFinished. In
// particular, OnCaptureFinished changes command buffer state and resets query slots, and we
// must ensure state remains consistent with respect to calls to marking begins and ends of
// command buffers and debug markers. A consistent state allows proper cleanup of query slots
// either in OnCaptureFinished or when completing submits. Note that calling
// vulkan_layer_producer_->IsCapturing() is not a correct replacement for checking this boolean.
bool is_capturing_ = false;
};
} // namespace orbit_vulkan_layer
#endif // ORBIT_VULKAN_LAYER_SUBMISSION_TRACKER_H_
| 47.72067 | 100 | 0.714567 | [
"object",
"vector"
] |
122c7b75944324e50226a52345e597007eb351e8 | 3,896 | h | C | libNCUI/transfer/IPCTransfer.h | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | 24 | 2018-11-20T14:45:57.000Z | 2021-12-30T13:38:42.000Z | libNCUI/transfer/IPCTransfer.h | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | null | null | null | libNCUI/transfer/IPCTransfer.h | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | 11 | 2018-11-29T00:09:14.000Z | 2021-11-23T08:13:17.000Z | // Created by amoylel on 08/13/2017.
// Copyright (c) 2017 amoylel All rights reserved.
#ifndef AMO_IPCTRANSFER_H__
#define AMO_IPCTRANSFER_H__
#include <amo/singleton.hpp>
#include "transfer/ClassTransfer.hpp"
namespace amo {
/*!
* @class ipc
*
* @extend Object
*
* @brief 进程间通信类,你可以通过该类发其他页面发送消息.<br>
* 但要注意的是不能在消息处理函数中调用任何导致UI阻塞的函数如(弹出窗口 alert dialog)<br>
* 工作线程:**UI线程**.
* @example
*
```
include('ipc');
ipc.unique('ipc.exec', function(){
console.log(arguments);
return 'hello';
});
ipc.unique('ipc.sync', function(){
console.log(arguments);
return 'ipc.sync';
});
ipc.unique('ipc.async', function(){
console.log(arguments)
return 'ipc.async';
});
ipc.unique('ipc.test', function(){
console.log(arguments);
return 666;
});
```
*/
class IPCTransfer
: public ClassTransfer
, public amo::singleton<IPCTransfer> {
public:
IPCTransfer();
/*!
* @fn Any IPCTransfer::exec(IPCMessage::SmartType msg);
*
* @tag static
*
* @brief 发送一条消息.
*
* @param #Args... 要发送的内容.
*
* @return 无.
*
* @example
*
```
include('ipc');
ipc.exec('ipc.exec', 12, '88', 12.33);
```
*/
Any exec(IPCMessage::SmartType msg);
/*!
* @fn Any IPCTransfer::sync(IPCMessage::SmartType msg);
*
* @tag static sync
*
* @brief 发送一条同步消息.
*
* @param #Args... 要发送的内容.
*
* @return #Any 消息返回的结果,只会返回第一个监听函数的返回值.
*
* @example
*
```
include('ipc');
var cc = ipc.sync('ipc.sync', 12);
console.log(cc);
console.assert(ipc.sync('ipc.sync', 12) == 'ipc.sync');
console.assert(ipc.sync('ipc.async', 'test') == 'ipc.async');
```
*/
Any sync(IPCMessage::SmartType msg);
/*!
* @fn Any IPCTransfer::async(IPCMessage::SmartType msg);
*
* @tag static
*
* @brief 发送一条异步消息,可以通过回调函数获取结果.
*
* @param #Args... 要发送的内容.
*
* @param #Function 要接收消息返回值的回调函数,任意位置都可以,但只能有一个, 只会返回第一个监听函数的返回值.
*
* @return 无.
*
* @example
*
```
include('ipc');
ipc.async('ipc.sync', function(val){console.assert(val == 'ipc.sync');});
ipc.async('ipc.async', function(val){console.assert(val == 'ipc.async');}, '2382934', 888);
```
*/
Any async(IPCMessage::SmartType msg);
/*!
* @fn Any IPCTransfer::dispatchEvent(IPCMessage::SmartType msg);
*
* @brief 向所有页面的document发送自定义事件.
*
* @param #String 事件名.
* @param #JsonObject 事件内容,CustomEvent的detail字段
*
* @return 无.
*/
Any dispatchEvent(IPCMessage::SmartType msg);
Any joinChannel(IPCMessage::SmartType msg);
Any getChannel(IPCMessage::SmartType msg);
AMO_CEF_MESSAGE_TRANSFER_BEGIN(IPCTransfer, ClassTransfer)
AMO_CEF_MESSAGE_TRANSFER_FUNC(exec, TransferFuncStatic | TransferExecNormal)
AMO_CEF_MESSAGE_TRANSFER_FUNC(sync, TransferFuncStatic | TransferExecSync)
AMO_CEF_MESSAGE_TRANSFER_FUNC(async, TransferFuncStatic | TransferExecAsync)
AMO_CEF_MESSAGE_TRANSFER_FUNC(dispatchEvent, TransferFuncStatic | TransferExecNormal)
AMO_CEF_MESSAGE_TRANSFER_END()
};
}
#endif // AMO_IPCTRANSFER_H__
| 25.631579 | 103 | 0.504877 | [
"object"
] |
1232cbdeebec9e4e803f26c4f1bc4c4924e1a3cd | 384 | h | C | MedicineClient/Classes/MycollectionCell.h | XYGDeveloper/FreelyHealth_Medical | 3616f537e32a93f3144e2a1ea6acfac865e9fddb | [
"MIT"
] | 1 | 2019-04-24T07:31:26.000Z | 2019-04-24T07:31:26.000Z | MedicineClient/Classes/MycollectionCell.h | XYGDeveloper/FreelyHealth_Medical | 3616f537e32a93f3144e2a1ea6acfac865e9fddb | [
"MIT"
] | null | null | null | MedicineClient/Classes/MycollectionCell.h | XYGDeveloper/FreelyHealth_Medical | 3616f537e32a93f3144e2a1ea6acfac865e9fddb | [
"MIT"
] | null | null | null | //
// MycollectionCell.h
// MedicineClient
//
// Created by xyg on 2017/8/29.
// Copyright © 2017年 深圳乐易住智能科技股份有限公司. All rights reserved.
//
#import <UIKit/UIKit.h>
@class MyCollectionModel;
@class MyAuswerModel;
@interface MycollectionCell : UITableViewCell
- (void)cellDataWithcollModel:(MyCollectionModel *)model;
- (void)cellDataWithausModel:(MyAuswerModel *)model;
@end
| 18.285714 | 59 | 0.747396 | [
"model"
] |
123332923b960cf8ede9e0e276a71aa61217ed49 | 2,106 | h | C | tools/build/v2/engine/hash.h | juslee/boost-svn | 6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb | [
"BSL-1.0"
] | 1 | 2018-12-15T19:55:56.000Z | 2018-12-15T19:55:56.000Z | tools/build/v2/engine/hash.h | smart-make/boost | 46509a094f8a844eefd5bb8a0030b739a04d79e1 | [
"BSL-1.0"
] | null | null | null | tools/build/v2/engine/hash.h | smart-make/boost | 46509a094f8a844eefd5bb8a0030b739a04d79e1 | [
"BSL-1.0"
] | null | null | null | /*
* Copyright 1993, 1995 Christopher Seiwald.
*
* This file is part of Jam - see jam.c for Copyright information.
*/
/*
* hash.h - simple in-memory hashing routines
*/
#ifndef BOOST_JAM_HASH_H
#define BOOST_JAM_HASH_H
#include "object.h"
/*
* An opaque struct representing an item in the hash table. The first element of
* every struct stored in the table must be an OBJECT * which is treated as the
* key.
*/
typedef struct hashdata HASHDATA;
/*
* hashinit() - initialize a hash table, returning a handle.
*
* Parameters:
* datalen - item size
* name - used for debugging
*/
struct hash * hashinit( int datalen, char const * name );
/*
* hash_free() - free a hash table, given its handle
*/
void hash_free( struct hash * );
void hashdone( struct hash * );
/*
* hashenumerate() - call f(i, data) on each item, i in the hash table. The
* enumeration order is unspecified.
*/
void hashenumerate( struct hash *, void (* f)( void *, void * ), void * data );
/*
* hash_insert() - insert a new item in a hash table, or return an existing one.
*
* Preconditions:
* - hp must be a hash table created by hashinit()
* - key must be an object created by object_new()
*
* Postconditions:
* - if the key does not already exist in the hash table, *found == 0 and the
* result will be a pointer to an uninitialized item. The key of the new
* item must be set to a value equal to key before any further operations on
* the hash table except hashdone().
* - if the key is present then *found == 1 and the result is a pointer to the
* existing record.
*/
HASHDATA * hash_insert( struct hash *, OBJECT * key, int * found );
/*
* hash_find() - find a record in the table or NULL if none exists
*/
HASHDATA * hash_find( struct hash *, OBJECT * key );
struct hashstats {
int count;
int num_items;
int tab_size;
int item_size;
int sets;
};
void hashstats_init( struct hashstats * stats );
void hashstats_add( struct hashstats * stats, struct hash * );
void hashstats_print( struct hashstats * stats, char const * name );
#endif
| 26.658228 | 80 | 0.676638 | [
"object"
] |
123eecc54acfda720d2f07cfcaa2a2ac94a357bf | 2,001 | h | C | path_planning/frenet_planner/include/quintic_polynomial.h | EatAllBugs/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | 1 | 2022-01-23T13:17:28.000Z | 2022-01-23T13:17:28.000Z | path_planning/frenet_planner/include/quintic_polynomial.h | yinflight/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | null | null | null | path_planning/frenet_planner/include/quintic_polynomial.h | yinflight/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | 1 | 2022-01-23T13:17:16.000Z | 2022-01-23T13:17:16.000Z | /*************************************************************************
> File Name: quintic_polynomial.h
> Author: TAI Lei
> Mail: ltai@ust.hk
> Created Time: Tue Apr 2 20:50:31 2019
************************************************************************/
#ifndef _QUINTIC_POLYNOMIAL_H
#define _QUINTIC_POLYNOMIAL_H
#include<iostream>
#include<vector>
#include<array>
#include<string>
#include<cmath>
#include "../lib/Eigen/Dense"
namespace cpprobotics {
class QuinticPolynomial {
public:
// current parameter at t=0
float xs;
float vxs;
float axs;
// parameters at target t=t_j
float xe;
float vxe;
float axe;
// function parameters
float a0, a1, a2, a3, a4, a5;
QuinticPolynomial() {};
// polynomial parameters
QuinticPolynomial(float xs_, float vxs_, float axs_, float xe_, float vxe_,
float axe_, float T): xs(xs_), vxs(vxs_), axs(axs_), xe(xe_), vxe(vxe_),
axe(axe_), a0(xs_), a1(vxs_), a2(axs_ / 2.0) {
Eigen::Matrix3f A;
A << std::pow(T, 3), std::pow(T, 4), std::pow(T, 5),
3 * std::pow(T, 2), 4 * std::pow(T, 3), 5 * std::pow(T, 4),
6 * T, 12 * std::pow(T, 2), 20 * std::pow(T, 3);
Eigen::Vector3f B;
B << xe - a0 - a1 *T - a2 *std::pow(T, 2),
vxe - a1 - 2 * a2 *T,
axe - 2 * a2;
Eigen::Vector3f c_eigen = A.colPivHouseholderQr().solve(B);
a3 = c_eigen[0];
a4 = c_eigen[1];
a5 = c_eigen[2];
};
float calc_point(float t) {
return a0 + a1 * t + a2 * std::pow(t, 2) + a3 * std::pow(t,
3) + a4 * std::pow(t, 4) + a5 * std::pow(t, 5);
};
float calc_first_derivative(float t) {
return a1 + 2 * a2 * t + 3 * a3 * std::pow(t, 2) + 4 * a4 * std::pow(t,
3) + a5 * std::pow(t, 4);
};
float calc_second_derivative(float t) {
return 2 * a2 + 6 * a3 * t + 12 * a4 * std::pow(t, 2) + 20 * a5 * std::pow(t,
3);
};
float calc_third_derivative(float t) {
return 6 * a3 + 24 * a4 * t + 60 * a5 * std::pow(t, 2);
};
};
}
#endif
| 25.987013 | 81 | 0.525237 | [
"vector"
] |
123ef2924cd4b52c503e4ac65169d78825ffa40a | 1,705 | h | C | ProcessLib/BoundaryCondition/DirichletBoundaryCondition.h | mjamoein/ogs | 52e4d1bcf3bc21a44ee7710fc9900d8729334ad4 | [
"BSD-4-Clause"
] | null | null | null | ProcessLib/BoundaryCondition/DirichletBoundaryCondition.h | mjamoein/ogs | 52e4d1bcf3bc21a44ee7710fc9900d8729334ad4 | [
"BSD-4-Clause"
] | null | null | null | ProcessLib/BoundaryCondition/DirichletBoundaryCondition.h | mjamoein/ogs | 52e4d1bcf3bc21a44ee7710fc9900d8729334ad4 | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#pragma once
#include "BoundaryCondition.h"
namespace BaseLib
{
class ConfigTree;
}
namespace ProcessLib
{
template <typename T>
struct Parameter;
// TODO docu
/// The DirichletBoundaryCondition class describes a constant in space
/// and time Dirichlet boundary condition.
/// The expected parameter in the passed configuration is "value" which, when
/// not present defaults to zero.
class DirichletBoundaryCondition final : public BoundaryCondition
{
public:
DirichletBoundaryCondition(
Parameter<double> const& parameter, MeshLib::Mesh const& bc_mesh,
NumLib::LocalToGlobalIndexMap const& dof_table_bulk,
int const variable_id, int const component_id);
void getEssentialBCValues(
const double t, GlobalVector const& x,
NumLib::IndexValueVector<GlobalIndexType>& bc_values) const override;
private:
Parameter<double> const& _parameter;
MeshLib::Mesh const& _bc_mesh;
std::unique_ptr<NumLib::LocalToGlobalIndexMap const> _dof_table_boundary;
int const _variable_id;
int const _component_id;
};
std::unique_ptr<DirichletBoundaryCondition> createDirichletBoundaryCondition(
BaseLib::ConfigTree const& config, MeshLib::Mesh const& bc_mesh,
NumLib::LocalToGlobalIndexMap const& dof_table_bulk, int const variable_id,
int const component_id,
const std::vector<std::unique_ptr<ProcessLib::ParameterBase>>& parameters);
} // namespace ProcessLib
| 29.912281 | 79 | 0.739003 | [
"mesh",
"vector"
] |
124059303cda3aeb9d8c509b62d5a6c7e37ac372 | 3,768 | h | C | mordor/streams/buffer.h | cgaebel/mordor | df05e6ecb0be2cf286bbd0b18ea8a4eb1a9061b5 | [
"BSD-3-Clause"
] | 2 | 2015-11-05T04:45:34.000Z | 2019-04-16T09:05:47.000Z | mordor/streams/buffer.h | cgaebel/mordor | df05e6ecb0be2cf286bbd0b18ea8a4eb1a9061b5 | [
"BSD-3-Clause"
] | null | null | null | mordor/streams/buffer.h | cgaebel/mordor | df05e6ecb0be2cf286bbd0b18ea8a4eb1a9061b5 | [
"BSD-3-Clause"
] | null | null | null | #ifndef __MORDOR_BUFFER_H__
#define __MORDOR_BUFFER_H__
#include <list>
#include <vector>
#include <boost/shared_array.hpp>
#include <boost/function.hpp>
#include "mordor/socket.h"
namespace Mordor {
struct Buffer
{
private:
struct SegmentData
{
friend struct Buffer;
public:
SegmentData();
SegmentData(size_t length);
SegmentData(void *buffer, size_t length);
SegmentData slice(size_t start, size_t length = ~0);
const SegmentData slice(size_t start, size_t length = ~0) const;
void extend(size_t len);
public:
void *start() { return m_start; }
const void *start() const { return m_start; }
size_t length() const { return m_length; }
private:
void start(void *p) { m_start = p; }
void length(size_t l) { m_length = l; }
void *m_start;
size_t m_length;
private:
boost::shared_array<unsigned char> m_array;
};
struct Segment
{
friend struct Buffer;
public:
Segment(size_t len);
Segment(SegmentData);
Segment(void *buffer, size_t length);
size_t readAvailable() const;
size_t writeAvailable() const;
size_t length() const;
void produce(size_t length);
void consume(size_t length);
void truncate(size_t length);
void extend(size_t length);
const SegmentData readBuffer() const;
const SegmentData writeBuffer() const;
SegmentData writeBuffer();
private:
size_t m_writeIndex;
SegmentData m_data;
void invariant() const;
};
public:
Buffer();
Buffer(const Buffer ©);
Buffer(const char *string);
Buffer(const std::string &string);
Buffer(const void *data, size_t length);
size_t readAvailable() const;
size_t writeAvailable() const;
// Primarily for unit tests
size_t segments() const;
void adopt(void *buffer, size_t length);
void reserve(size_t length);
void compact();
void clear(bool clearWriteAvailableAsWell = true);
void produce(size_t length);
void consume(size_t length);
void truncate(size_t length);
const std::vector<iovec> readBuffers(size_t length = ~0) const;
const iovec readBuffer(size_t length, bool reallocate) const;
std::vector<iovec> writeBuffers(size_t length = ~0);
iovec writeBuffer(size_t length, bool reallocate);
void copyIn(const Buffer& buf, size_t length = ~0);
void copyIn(const char* string);
void copyIn(const void* data, size_t length);
void copyOut(Buffer &buffer, size_t length) const
{ buffer.copyIn(*this, length); }
void copyOut(void* buffer, size_t length) const;
ptrdiff_t find(char delimiter, size_t length = ~0) const;
ptrdiff_t find(const std::string &string, size_t length = ~0) const;
std::string getDelimited(char delimiter, bool eofIsDelimiter = true,
bool includeDelimiter = true);
std::string getDelimited(const std::string &delimiter,
bool eofIsDelimiter = true, bool includeDelimiter = true);
void visit(boost::function<void (const void *, size_t)> dg, size_t length = ~0) const;
bool operator== (const Buffer &rhs) const;
bool operator!= (const Buffer &rhs) const;
bool operator== (const std::string &str) const;
bool operator!= (const std::string &str) const;
bool operator== (const char *str) const;
bool operator!= (const char *str) const;
private:
std::list<Segment> m_segments;
size_t m_readAvailable;
size_t m_writeAvailable;
std::list<Segment>::iterator m_writeIt;
int opCmp(const Buffer &rhs) const;
int opCmp(const char *string, size_t length) const;
void invariant() const;
};
}
#endif
| 28.330827 | 90 | 0.656847 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.