repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
josehu07/hux-kernel | user/lib/types.h | /**
* Type identification functions on characters.
*/
#ifndef TYPES_H
#define TYPES_H
#include <stdbool.h>
bool isdigit(char c);
bool isxdigit(char c);
bool isalpha(char c);
bool islower(char c);
bool isupper(char c);
bool isspace(char c);
#endif
|
josehu07/hux-kernel | src/boot/multiboot.h | /**
* Multiboot1 related structures.
* See https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
* See https://www.gnu.org/software/grub/manual/multiboot/html_node/Example-OS-code.html
*/
#ifndef MULTIBOOT_H
#define MULTIBOOT_H
#include <stdint.h>
#define MULTIBOOT_HEADER_MAGIC 0x1BADB002
#define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002 /** Should be in %eax. */
/**
* Multiboot1 header.
* See https://www.gnu.org/software/grub/manual/multiboot/multiboot.html#Header-layout
*/
struct multiboot_header {
uint32_t magic; /* Must be header magic 0x1BADB002. */
uint32_t flags; /* Feature flags. */
uint32_t checksum; /* The above fields + this one must == 0 mod 2^32. */
/**
* More optional fields below. Not used now, so omitted here.
* ...
*/
} __attribute__((packed));
typedef struct multiboot_header multiboot_header_t;
/**
* The section header table for ELF format. "These indicate where the section
* header table from an ELF kernel is, the size of each entry, number of
* entries, and the string table used as the index of names", stated on GRUB
* multiboot1 specification.
* See https://www.gnu.org/software/grub/manual/multiboot/multiboot.html#Boot-information-format
*/
struct multiboot_elf_section_header_table {
uint32_t num;
uint32_t size;
uint32_t addr;
uint32_t shndx;
} __attribute__((packed));
typedef struct multiboot_elf_section_header_table multiboot_elf_section_header_table_t;
/**
* Multiboot1 information.
* See https://www.gnu.org/software/grub/manual/multiboot/multiboot.html#Boot-information-format
*/
struct multiboot_info {
uint32_t flags; /* Multiboot info version number. */
uint32_t mem_lower; /* Available memory from BIOS. */
uint32_t mem_upper;
uint32_t boot_device; /* The "root" partition. */
uint32_t cmdline; /* Kernel command line. */
uint32_t mods_count; /* Boot-Module list. */
uint32_t mods_addr;
/** We use ELF, so not including "a.out" format support. */
multiboot_elf_section_header_table_t elf_sht;
/**
* More fields below. Not used now, so omitted here.
* ...
*/
} __attribute__((packed));
typedef struct multiboot_info multiboot_info_t;
#endif
|
josehu07/hux-kernel | src/common/debug.c | <gh_stars>10-100
/**
* Common debugging utilities.
*/
#include <stdint.h>
#include <stddef.h>
#include "debug.h"
#include "printf.h"
#include "../boot/multiboot.h"
#include "../boot/elf.h"
#include "../common/string.h"
#include "../process/layout.h"
/** Initialized at 'debug_init'. */
static elf_symbol_t *elf_symtab;
static size_t elf_symtab_size;
static const char *elf_strtab;
static size_t elf_strtab_size;
/** For marking the end of all sections. Kernel heap begins above this. */
uint32_t elf_sections_end = 0x0;
/** Look up an address in symbols map and return its function name. */
static const char *
_lookup_symbol_name(uint32_t addr)
{
size_t symtab_len = elf_symtab_size / sizeof(elf_symbol_t);
for (size_t i = 0; i < symtab_len; ++i) {
if ((ELF_SYM_TYPE(elf_symtab[i].info) == ELF_SYM_TYPE_FUNC)
&& (addr >= elf_symtab[i].value)
&& (addr <= elf_symtab[i].value + elf_symtab[i].size)) {
return elf_strtab + elf_symtab[i].name;
}
}
return "name_unresolved";
}
/**
* Pull out the symbols table and strings table from a multiboot information
* structure pointer.
*/
void
debug_init(multiboot_info_t *mbi)
{
/** Get the section header table as an array of section headers. */
elf_section_header_t *sht = (elf_section_header_t *) mbi->elf_sht.addr;
size_t sht_len = (size_t) mbi->elf_sht.num;
/**
* The section header at index 'shndx' in the table is a meta section
* header. It contains a list of section header names in the table. We
* should look for section header names ".symtab" & ".strtab".
*/
const char *sh_names = (const char *) sht[mbi->elf_sht.shndx].addr;
/**
* Loop through the table and look for ".symtab" & ".strtab".
*
* Also records the highest address seen across all sections, which will
* later determine the starting point of kernel heap.
*/
for (size_t i = 0; i < sht_len; ++i) {
const char *name = sh_names + sht[i].name;
if (strncmp(name, ".symtab", 7) == 0) {
elf_symtab = (elf_symbol_t *) sht[i].addr;
elf_symtab_size = sht[i].size;
} else if (strncmp(name, ".strtab", 7) == 0) {
elf_strtab = (const char *) sht[i].addr;
elf_strtab_size = sht[i].size;
}
if (sht[i].addr + sht[i].size > elf_sections_end)
elf_sections_end = sht[i].addr + sht[i].size;
}
}
/** Print stack tracing to terminal. */
void
stack_trace()
{
uint32_t *ebp;
unsigned int id = 0;
asm volatile ( "movl %%ebp, %0" : "=r" (ebp) );
while (ebp != NULL && (uint32_t) (ebp + 1) < USER_MAX) {
uint32_t addr = *(ebp + 1);
printf(" %2u) [%p] %s\n", id++, addr, _lookup_symbol_name(addr));
ebp = (uint32_t *) *ebp;
}
}
/**
* Stack smashing protector (stack canary) support.
* Build with `-fstack-protector` to enable this. Using a static canary
* value here to maintain simplicity.
*/
#define STACK_CHK_GUARD 0xCF10A8CB
uintptr_t __stack_chk_guard = STACK_CHK_GUARD;
__attribute__((noreturn))
void
__stack_chk_fail(void)
{
panic("stack smashing detected");
}
|
josehu07/hux-kernel | src/filesys/block.c | <filename>src/filesys/block.c
/**
* Block-level I/O general request layer.
*/
#include <stdint.h>
#include <stdbool.h>
#include "block.h"
#include "vsfs.h"
#include "../common/debug.h"
#include "../common/string.h"
#include "../device/idedisk.h"
/**
* Helper function for reading blocks of data from disk into memory.
* Uses an internal request buffer, so not zero-copy I/O. DST is the
* destination buffer, and DISK_ADDR and LEN are both in bytes.
*/
static bool
_block_read(char *dst, uint32_t disk_addr, uint32_t len, bool boot)
{
block_request_t req;
uint32_t bytes_read = 0;
while (len > bytes_read) {
uint32_t bytes_left = len - bytes_read;
uint32_t start_addr = disk_addr + bytes_read;
uint32_t block_no = ADDR_BLOCK_NUMBER(start_addr);
uint32_t req_offset = ADDR_BLOCK_OFFSET(start_addr);
uint32_t next_addr = ADDR_BLOCK_ROUND_DN(start_addr) + BLOCK_SIZE;
uint32_t effective = next_addr - start_addr;
if (bytes_left < effective)
effective = bytes_left;
req.valid = false;
req.dirty = false;
req.block_no = block_no;
bool success = boot ? idedisk_do_req_at_boot(&req)
: idedisk_do_req(&req);
if (!success) {
warn("block_read: reading IDE disk block %u failed", block_no);
return false;
}
memcpy(dst + bytes_read, req.data + req_offset, effective);
bytes_read += effective;
}
return true;
}
bool
block_read(char *dst, uint32_t disk_addr, uint32_t len)
{
return _block_read(dst, disk_addr, len, false);
}
bool
block_read_at_boot(char *dst, uint32_t disk_addr, uint32_t len)
{
return _block_read(dst, disk_addr, len, true);
}
/**
* Helper function for writing blocks of data from memory into disk.
* Uses an internal request buffer, so not zero-copy I/O. SRC is the
* source buffer, and DISK_ADDR and LEN are both in bytes.
*/
bool
block_write(char *src, uint32_t disk_addr, uint32_t len)
{
block_request_t req;
uint32_t bytes_written = 0;
while (len > bytes_written) {
uint32_t bytes_left = len - bytes_written;
uint32_t start_addr = disk_addr + bytes_written;
uint32_t block_no = ADDR_BLOCK_NUMBER(start_addr);
uint32_t req_offset = ADDR_BLOCK_OFFSET(start_addr);
uint32_t next_addr = ADDR_BLOCK_ROUND_DN(start_addr) + BLOCK_SIZE;
uint32_t effective = next_addr - start_addr;
if (bytes_left < effective)
effective = bytes_left;
/**
* If writing less than a block, first read out the block to
* avoid corrupting what's already on disk.
*/
if (effective < BLOCK_SIZE) {
if (!block_read((char *) req.data, ADDR_BLOCK_ROUND_DN(start_addr),
BLOCK_SIZE)) {
warn("block_write: failed to read out old block %u", block_no);
return false;
}
}
memcpy(req.data + req_offset, src + bytes_written, effective);
req.valid = true;
req.dirty = true;
req.block_no = block_no;
if (!idedisk_do_req(&req)) {
warn("block_write: writing IDE disk block %u failed", block_no);
return false;
}
bytes_written += effective;
}
return true;
}
/**
* Allocate a free data block and mark it in use. Returns the block
* disk address allocated, or 0 (which is invalid for a data block)
* on failures.
*/
uint32_t
block_alloc(void)
{
/** Get a free block from data bitmap. */
uint32_t slot = bitmap_alloc(&data_bitmap);
if (slot == data_bitmap.slots) {
warn("block_alloc: no free data block left");
return 0;
}
if (!data_bitmap_update(slot)) {
warn("block_alloc: failed to persist data bitmap");
return 0;
}
uint32_t disk_addr = DISK_ADDR_DATA_BLOCK(slot);
/** Zero the block out for safety. */
char buf[BLOCK_SIZE];
memset(buf, 0, BLOCK_SIZE);
if (!block_write(buf, disk_addr, BLOCK_SIZE)) {
warn("block_alloc: failed to zero out block %p", disk_addr);
bitmap_clear(&data_bitmap, slot);
data_bitmap_update(slot); /** Ignores error. */
return 0;
}
return disk_addr;
}
/** Free a disk data block. */
void
block_free(uint32_t disk_addr)
{
assert(disk_addr >= DISK_ADDR_DATA_BLOCK(0));
uint32_t slot = (disk_addr / BLOCK_SIZE) - superblock.data_start;
bitmap_clear(&data_bitmap, slot);
data_bitmap_update(slot); /** Ignores error. */
/** Zero the block out for safety. */
char buf[BLOCK_SIZE];
memset(buf, 0, BLOCK_SIZE);
if (!block_write(buf, ADDR_BLOCK_ROUND_DN(disk_addr), BLOCK_SIZE))
warn("block_free: failed to zero out block %p", disk_addr);
}
|
josehu07/hux-kernel | src/interrupt/syscall.c | <filename>src/interrupt/syscall.c
/**
* System call-related definitions and handler wrappers.
*/
#include <stdint.h>
#include <stddef.h>
#include "syscall.h"
#include "../common/debug.h"
#include "../display/sysdisp.h"
#include "../device/sysdev.h"
#include "../interrupt/isr.h"
#include "../memory/sysmem.h"
#include "../process/layout.h"
#include "../process/process.h"
#include "../process/scheduler.h"
#include "../process/sysproc.h"
#include "../filesys/sysfile.h"
/** Array of individual handlers: void -> int32_t functions. */
static syscall_t syscall_handlers[] = {
[SYSCALL_GETPID] syscall_getpid,
[SYSCALL_FORK] syscall_fork,
[SYSCALL_EXIT] syscall_exit,
[SYSCALL_SLEEP] syscall_sleep,
[SYSCALL_WAIT] syscall_wait,
[SYSCALL_KILL] syscall_kill,
[SYSCALL_TPRINT] syscall_tprint,
[SYSCALL_UPTIME] syscall_uptime,
[SYSCALL_KBDSTR] syscall_kbdstr,
[SYSCALL_SETHEAP] syscall_setheap,
[SYSCALL_OPEN] syscall_open,
[SYSCALL_CLOSE] syscall_close,
[SYSCALL_CREATE] syscall_create,
[SYSCALL_REMOVE] syscall_remove,
[SYSCALL_READ] syscall_read,
[SYSCALL_WRITE] syscall_write,
[SYSCALL_CHDIR] syscall_chdir,
[SYSCALL_GETCWD] syscall_getcwd,
[SYSCALL_EXEC] syscall_exec,
[SYSCALL_FSTAT] syscall_fstat,
[SYSCALL_SEEK] syscall_seek
};
#define NUM_SYSCALLS ((int32_t) (sizeof(syscall_handlers) / sizeof(syscall_t)))
/**
* Centralized syscall handler entry.
* - The trap state holds the syscall number in register EAX
* and the arguments on user stack;
* - Returns a return code back to register EAX.
*
* User syscall library should do syscalls following this rule.
*/
void
syscall(interrupt_state_t *state)
{
int32_t syscall_no = state->eax;
if (syscall_no <= 0 || syscall_no >= NUM_SYSCALLS) {
warn("syscall: unknwon syscall number %d", syscall_no);
state->eax = SYS_FAIL_RC;
} else if (syscall_handlers[syscall_no] == NULL) {
warn("syscall: null handler for syscall # %d", syscall_no);
state->eax = SYS_FAIL_RC;
} else {
syscall_t handler = syscall_handlers[syscall_no];
state->eax = handler();
}
}
/** Helpers for getting something from user memory address. */
bool
sysarg_addr_int(uint32_t addr, int32_t *ret)
{
process_t *proc = running_proc();
if (addr < proc->stack_low || addr + 4 > USER_MAX) {
warn("sysarg_addr_int: invalid arg addr %p for %s", addr, proc->name);
return false;
}
*ret = *((int32_t *) addr);
return true;
}
bool
sysarg_addr_uint(uint32_t addr, uint32_t *ret)
{
process_t *proc = running_proc();
if (addr < proc->stack_low || addr + 4 > USER_MAX) {
warn("sysarg_addr_uint: invalid arg addr %p for %s", addr, proc->name);
return false;
}
*ret = *((uint32_t *) addr);
return true;
}
bool
sysarg_addr_mem(uint32_t addr, char **mem, size_t len)
{
process_t *proc = running_proc();
if (addr >= USER_MAX || addr + len > USER_MAX || addr < USER_BASE
|| (addr >= proc->heap_high && addr < proc->stack_low)
|| (addr + len > proc->heap_high && addr + len <= proc->stack_low)
|| (addr < proc->heap_high && addr + len > proc->heap_high)) {
warn("sysarg_addr_mem: invalid mem %p w/ len %d for %s",
addr, len, proc->name);
return false;
}
*mem = (char *) addr;
return true;
}
int32_t
sysarg_addr_str(uint32_t addr, char **str)
{
process_t *proc = running_proc();
if (addr >= USER_MAX || addr < USER_BASE
|| (addr >= proc->heap_high && addr < proc->stack_low)) {
warn("sysarg_get_str: invalid str %p for %s",
addr, proc->name);
return -1;
}
char *bound = addr < proc->heap_high ? (char *) proc->heap_high
: (char *) USER_MAX;
for (char *c = (char *) addr; c < bound; ++c) {
if (*c == '\0') {
*str = (char *) addr;
return c - (char *) addr;
}
}
return -1;
}
/**
* Get syscall arguments on the user stack.
* - state->esp is the current user ESP;
* - 0(state->esp) is the return address, so skip;
* - starting from 4(state->esp) are the arguments, from stack
* bottom -> top are user lib arguments from left -> right.
*/
/**
* Fetch the n-th (starting from 0-th) 32bit integer. Returns true on
* success and false if address not in user stack.
*/
bool
sysarg_get_int(int8_t n, int32_t *ret)
{
process_t *proc = running_proc();
uint32_t addr = (proc->trap_state->esp) + 4 + (4 * n);
return sysarg_addr_int(addr, ret);
}
/** Same but for uint32_t. */
bool
sysarg_get_uint(int8_t n, uint32_t *ret)
{
process_t *proc = running_proc();
uint32_t addr = (proc->trap_state->esp) + 4 + (4 * n);
return sysarg_addr_uint(addr, ret);
}
/**
* Fetch the n-th (starting from 0-th) 32-bit argument and interpret as
* a pointer to a bytes array of length `len`. Returns true on success
* and false if address invalid.
*/
bool
sysarg_get_mem(int8_t n, char **mem, size_t len)
{
uint32_t ptr;
if (!sysarg_get_int(n, (int32_t *) &ptr)) {
warn("sysarg_get_mem: inner sysarg_get_int failed");
return false;
}
return sysarg_addr_mem(ptr, mem, len);
}
/**
* Fetch the n-th (starting from 0-th) 32-bit argument and interpret as
* a pointer to a string. Returns the length of string actually parsed
* on success, and -1 if address invalid or the string is not correctly
* null-terminated.
*/
int32_t
sysarg_get_str(int8_t n, char **str)
{
uint32_t ptr;
if (!sysarg_get_int(n, (int32_t *) &ptr)) {
warn("sysarg_get_str: inner sysarg_get_int failed");
return -1;
}
return sysarg_addr_str(ptr, str);
}
|
josehu07/hux-kernel | src/interrupt/isr.c | <gh_stars>10-100
/**
* Interrupt service routines (ISR) handler implementation.
*/
#include <stdint.h>
#include "isr.h"
#include "idt.h"
#include "syscall.h"
#include "../common/port.h"
#include "../common/printf.h"
#include "../common/debug.h"
#include "../display/vga.h"
#include "../interrupt/syscall.h"
#include "../process/scheduler.h"
/** Table of ISRs. Unregistered entries MUST be NULL. */
isr_t isr_table[NUM_GATE_ENTRIES] = {NULL};
/** Exposed to other parts for them to register ISRs. */
inline void
isr_register(uint8_t int_no, isr_t handler)
{
if (isr_table[int_no] != NULL) {
error("isr: handler for interrupt # %#x already registered", int_no);
return;
}
isr_table[int_no] = handler;
}
/** Send back PIC end-of-interrupt (EOI) signal. */
static void
_pic_send_eoi(uint8_t irq_no)
{
if (irq_no >= 8)
outb(0xA0, 0x20); /** If is slave IRQ, should send to both. */
outb(0x20, 0x20);
}
/** Print interrupt state information. */
static void
_print_interrupt_state(interrupt_state_t *state)
{
info("interrupt state:");
process_t *proc = running_proc();
printf(" Current process: %d - %s\n", proc->pid, proc->name);
printf(" INT#: %d ERRCODE: %#010X EFLAGS: %#010X\n",
state->int_no, state->err_code, state->eflags);
printf(" EAX: %#010X EIP: %#010X ESP: %#010X\n",
state->eax, state->eip, state->esp);
printf(" DS: %#010X CS: %#010X SS: %#010X\n",
state->ds, state->cs, state->ss);
}
/**
* Decide what to do on a missing handler:
* - In kernel context: we have done something wrong, panic
* - In user process context: user process misbehaved, exit it
*/
static void
_missing_handler(interrupt_state_t *state)
{
_print_interrupt_state(state);
process_t *proc = running_proc();
bool kernel_context = (state->cs & 0x3) == 0 /** DPL field is zero. */
|| proc == NULL;
if (kernel_context)
error("isr: missing handler for interrupt # %#x", state->int_no);
else {
warn("isr: missing handler for interrupt # %#x", state->int_no);
process_exit();
}
}
/**
* ISR handler written in C.
*
* Receives a pointer to a structure of interrupt state. Handles the
* interrupt and simply returns. Can modify interrupt state through
* this pointer if necesary.
*/
void
isr_handler(interrupt_state_t *state)
{
uint8_t int_no = state->int_no;
/** An exception interrupt. */
if (int_no <= 31) {
/** Panic if no actual ISR is registered. */
if (isr_table[int_no] == NULL)
_missing_handler(state);
else
isr_table[int_no](state);
/** An IRQ-translated interrupt from external device. */
} else if (int_no <= 47) {
uint8_t irq_no = state->int_no - 32;
/** Call actual ISR if registered. */
if (isr_table[int_no] == NULL)
_missing_handler(state);
else {
/**
* Send back timer interrupt EOI to PIC early because it may
* yield in the timer interrupt to the scheduler, leaving
* the PIT timer blocked for the next few processes scheduled.
*/
if (state->int_no == INT_NO_TIMER)
_pic_send_eoi(irq_no);
isr_table[int_no](state);
if (state->int_no != INT_NO_TIMER)
_pic_send_eoi(irq_no);
}
/** Syscall trap. */
} else if (int_no == INT_NO_SYSCALL) {
process_t *proc = running_proc();
if (proc->killed)
process_exit();
/** Point proc->trap_state to this trap. */
proc->trap_state = state;
/**
* Call the syscall handler in `syscall.c`.
*
* Interrupt state contains the syscall number in EAX and the
* arguments on the user stack. Returns an integer return code
* back to EAX.
*/
syscall(state);
if (proc->killed)
process_exit();
/** Unknown interrupt number. */
} else
_missing_handler(state);
}
|
josehu07/hux-kernel | user/init.c | /**
* The init user program to be embedded. Runs in user mode.
*/
#include <stdint.h>
#include <stddef.h>
#include "lib/syscall.h"
#include "lib/debug.h"
void
main(void)
{
// info("init: starting the shell process...");
int8_t shell_pid = fork(0);
if (shell_pid < 0) {
error("init: failed to fork a child process");
exit();
}
if (shell_pid == 0) {
/** Child: exec the command line shell. */
char *argv[2];
argv[0] = "shell";
argv[1] = NULL;
exec("shell", argv);
error("init: failed to exec the shell program");
} else {
/** Parent: loop in catching zombie processes. */
int8_t wait_pid;
do {
wait_pid = wait();
if (wait_pid > 0 && wait_pid != shell_pid)
warn("init: caught zombie process %d", wait_pid);
} while (wait_pid > 0 && wait_pid != shell_pid);
error("init: the shell process exits, should not happen");
}
}
|
josehu07/hux-kernel | src/common/printf.h | <gh_stars>10-100
/**
* Common formatted printing utilities.
*
* Format specifier := %[special][width][.precision][length]<type>. Only
* limited features are provided (documented in the wiki page).
*/
#ifndef PRINTF_H
#define PRINTF_H
#include <stdbool.h>
#include "../display/vga.h"
#include "../display/terminal.h"
void printf(const char *fmt, ...);
void cprintf(vga_color_t fg, const char *fmt, ...);
void snprintf(char *buf, size_t count, const char *fmt, ...);
/** Extern to `debug.h`. */
extern bool printf_to_hold_lock;
#endif
|
josehu07/hux-kernel | src/filesys/vsfs.h | /**
* Very simple file system (VSFS) data structures & Layout.
*
* This part borrows code heavily from xv6.
*/
#ifndef VSFS_H
#define VSFS_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "sysfile.h"
#include "../common/bitmap.h"
/** Root directory must be the 0-th inode. */
#define ROOT_INUMBER 0
/**
* VSFS of Hux has the following on-disk layout:
*
* - Block 0 is the superblock holding meta information of the FS;
* - Block 1~6 are the inode slots bitmap;
* - Block 7~38 are the data blocks bitmap;
* - Blocks 39~6143 (upto 6 MiB offset) are inode blocks;
* - All the rest blocks up to 256 MiB are data blocks.
*
* * Block size is 1 KiB = 2 disk sectors
* * Inode structure is 128 bytes, so an inode block has 8 slots
* * File system size is 256 MiB = 262144 blocks
* * Inode 0 is the root path directory "/"
*
* The mkfs script builds an initial VSFS disk image which should follow
* the above description.
*/
struct superblock {
uint32_t fs_blocks; /** Should be 262144. */
uint32_t inode_bitmap_start; /** Should be 1. */
uint32_t inode_bitmap_blocks; /** Should be 6. */
uint32_t data_bitmap_start; /** Should be 7. */
uint32_t data_bitmap_blocks; /** Should be 32. */
uint32_t inode_start; /** Should be 39. */
uint32_t inode_blocks; /** Should be 6105. */
uint32_t data_start; /** Should be 6144. */
uint32_t data_blocks; /** Should be 256000. */
} __attribute__((packed));
typedef struct superblock superblock_t;
/** Extern to `file.c`. */
extern superblock_t superblock;
extern bitmap_t inode_bitmap;
extern bitmap_t data_bitmap;
/**
* An inode points to 16 direct blocks, 8 singly-indirect blocks, and
* 1 doubly-indirect block. With an FS block size of 1KB, the maximum
* file size = 1 * 256^2 + 8 * 256 + 16 KiB = 66MiB 16KiB.
*/
#define NUM_DIRECT 16
#define NUM_INDIRECT1 8
#define NUM_INDIRECT2 1
#define UINT32_PB (BLOCK_SIZE / 4)
#define FILE_MAX_BLOCKS (NUM_INDIRECT2 * UINT32_PB*UINT32_PB \
+ NUM_INDIRECT1 * UINT32_PB \
+ NUM_DIRECT)
/** On-disk inode structure of exactly 128 bytes in size. */
#define INODE_SIZE 128
#define INODE_TYPE_EMPTY 0
#define INODE_TYPE_FILE 1
#define INODE_TYPE_DIR 2
struct inode {
uint32_t type; /** 0 = empty, 1 = file, 2 = directory. */
uint32_t size; /** File size in bytes. */
uint32_t data0[NUM_DIRECT]; /** Direct blocks. */
uint32_t data1[NUM_INDIRECT1]; /** 1-level indirect blocks. */
uint32_t data2[NUM_INDIRECT2]; /** 2-level indirect blocks. */
/** Rest bytes are unused. */
} __attribute__((packed));
typedef struct inode inode_t;
/** Helper macros for calculating on-disk address. */
#define DISK_ADDR_INODE(i) (superblock.inode_start * BLOCK_SIZE + (i) * INODE_SIZE)
#define DISK_ADDR_DATA_BLOCK(d) ((superblock.data_start + (d)) * BLOCK_SIZE)
/**
* Directory entry structure. A directory's data is simply a contiguous
* array of such 128-bytes entry structures.
*/
#define DENTRY_SIZE 128
#define MAX_FILENAME 100
struct dentry {
uint32_t valid; /** 0 = unused, 1 = valid. */
uint32_t inumber; /** Inumber of the file. */
char filename[DENTRY_SIZE - 8]; /** String name. */
} __attribute__((packed));
typedef struct dentry dentry_t;
void filesys_init();
int8_t filesys_open(char *path, uint32_t mode);
bool filesys_close(int8_t fd);
bool filesys_create(char *path, uint32_t mode);
bool filesys_remove(char *path);
int32_t filesys_read(int8_t fd, char *dst, size_t len);
int32_t filesys_write(int8_t fd, char *dst, size_t len);
bool filesys_chdir(char *path);
bool filesys_getcwd(char *buf, size_t limit);
bool filesys_exec(char *path, char **argv);
bool filesys_fstat(int8_t fd, file_stat_t *stat);
bool filesys_seek(int8_t fd, size_t offset);
bool inode_bitmap_update(uint32_t slot_no);
bool data_bitmap_update(uint32_t slot_no);
#endif
|
josehu07/hux-kernel | src/common/debug.h | <gh_stars>10-100
/**
* Common debugging utilities.
*/
#ifndef DEBUG_H
#define DEBUG_H
#include <stdbool.h>
#include "printf.h"
#include "../display/vga.h"
#include "../display/terminal.h"
#include "../boot/multiboot.h"
/** For marking the begin of kernel heap. */
extern uint32_t elf_sections_end;
void debug_init(multiboot_info_t *mbi);
void stack_trace();
/** Panicking macro. */
#define panic(fmt, args...) do { \
asm volatile ( "cli" ); \
cprintf(VGA_COLOR_MAGENTA, "PANIC: " fmt "\n", \
##args); \
stack_trace(); \
while (1) \
asm volatile ( "hlt" ); \
__builtin_unreachable(); \
} while (0)
/** Assertion macro. */
#define assert(condition) do { \
if (!(condition)) { \
printf_to_hold_lock = false; \
panic("assertion failed @ function '%s'," \
" file '%s': line %d", \
__FUNCTION__, __FILE__, __LINE__); \
} \
} while (0)
/** Error prompting macro. */
#define error(fmt, args...) do { \
cprintf(VGA_COLOR_RED, "ERROR: " fmt "\n", \
##args); \
panic("error occurred @ function '%s'," \
" file '%s': line %d", \
__FUNCTION__, __FILE__, __LINE__); \
} while (0)
/** Warning prompting macro. */
#define warn(fmt, args...) do { \
cprintf(VGA_COLOR_MAGENTA, "WARN: " fmt "\n", \
##args); \
} while (0)
/** Info prompting macro. */
#define info(fmt, args...) do { \
cprintf(VGA_COLOR_CYAN, "INFO: " fmt "\n", \
##args); \
} while (0)
#endif
|
josehu07/hux-kernel | src/filesys/file.h | <gh_stars>10-100
/**
* In-memory structures and operations on open files.
*/
#ifndef FILE_H
#define FILE_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "vsfs.h"
#include "sysfile.h"
#include "../common/spinlock.h"
#include "../common/parklock.h"
/** In-memory copy of open inode, be sure struct size <= 128 bytes. */
struct mem_inode {
uint8_t ref_cnt; /** Reference count (from file handles). */
uint32_t inumber; /** Inode number identifier of `d_inode`. */
parklock_t lock; /** Parking lock held when waiting for disk I/O. */
inode_t d_inode; /** Read in on-disk inode structure. */
};
typedef struct mem_inode mem_inode_t;
/** Maximum number of in-memory cached inodes. */
#define MAX_MEM_INODES 100
/** Open file handle structure. */
struct file {
uint8_t ref_cnt; /** Reference count (from forked processes). */
bool readable; /** Open as readable? */
bool writable; /** Open as writable? */
mem_inode_t *inode; /** Inode structure of the file. */
uint32_t offset; /** Current file offset in bytes. */
};
typedef struct file file_t;
/** Maximum number of open files in the system. */
#define MAX_OPEN_FILES 200
/** Maximum number of open files per process. */
#define MAX_FILES_PER_PROC 16
/** Extern the tables to `vsfs.c`. */
extern mem_inode_t icache[];
extern spinlock_t icache_lock;
extern file_t ftable[];
extern spinlock_t ftable_lock;
void inode_lock(mem_inode_t *m_inode);
void inode_unlock(mem_inode_t *m_inode);
mem_inode_t *inode_get(uint32_t inumber);
mem_inode_t *inode_get_at_boot(uint32_t inumber);
void inode_ref(mem_inode_t *m_inode);
void inode_put(mem_inode_t *m_inode);
mem_inode_t *inode_alloc(uint32_t type);
void inode_free(mem_inode_t *m_inode);
size_t inode_read(mem_inode_t *m_inode, char *dst, uint32_t offset, size_t len);
size_t inode_write(mem_inode_t *m_inode, char *src, uint32_t offset, size_t len);
file_t *file_get();
void file_ref(file_t *file);
void file_put(file_t *file);
void file_stat(file_t *file, file_stat_t *stat);
#endif
|
josehu07/hux-kernel | src/memory/kheap.c | <filename>src/memory/kheap.c<gh_stars>10-100
/**
* Kernel Heap Memory "Next-Fit" Allocator.
*/
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "kheap.h"
#include "paging.h"
#include "../common/printf.h"
#include "../common/string.h"
#include "../common/debug.h"
#include "../common/spinlock.h"
static uint32_t kheap_btm;
static uint32_t kheap_top;
/** Global state of the free-list. */
static fl_header_t *bottom_most_header; /** Address-wise smallest node. */
static fl_header_t *last_search_header; /** Where the last search ends. */
static size_t free_list_length = 1;
static spinlock_t kheap_lock;
/** For debug printing the state of the free-list. */
__attribute__((unused))
static void
_print_free_list_state(void)
{
spinlock_acquire(&kheap_lock);
fl_header_t *header_curr = bottom_most_header;
info("Kheap free-list length = %d, last_search = %p, nodes:",\
free_list_length, last_search_header);
do {
printf(" node header %p { size: %d, next: %p }\n",
header_curr, header_curr->size, header_curr->next);
header_curr = (fl_header_t *) header_curr->next;
} while (header_curr != bottom_most_header);
spinlock_release(&kheap_lock);
}
/**
* Allocate a piece of heap memory (an object) of given size. Adopts
* the "next-fit" allocation policy. Returns 0 on failure.
*/
uint32_t
kalloc(size_t size)
{
spinlock_acquire(&kheap_lock);
if (free_list_length == 0) {
warn("kalloc: kernel flexible heap all used up");
spinlock_release(&kheap_lock);
return 0;
}
fl_header_t *header_last = last_search_header;
fl_header_t *header_curr = (fl_header_t *) header_last->next;
fl_header_t *header_begin = header_curr;
do {
/** If this node is not large enough, skip. */
if (header_curr->size < size) {
header_last = header_curr;
header_curr = (fl_header_t *) header_curr->next;
continue;
}
/**
* Else, split this node if it is larger than `size` + meta bytes
* (after split, the rest of it can be made a smaller free chunk).
*/
if (header_curr->size > size + sizeof(fl_header_t)) {
/** Split out a new node. */
fl_header_t *header_new = (fl_header_t *)
((uint32_t) header_curr + size + sizeof(fl_header_t));
header_new->size = (header_curr->size - size) - sizeof(fl_header_t);
header_new->magic = KHEAP_MAGIC;
header_new->free = true;
/** Don't forget to update the current node's size. */
header_curr->size = size;
/**
* Now, update the links between nodes. The special case of list
* only having one node needs to be taken care of.
*
* If only one node in list, then `header_last` == `header_curr`,
* so `last_search_header` should be the new node, not the current
* node (that is about to be returned as an object).
*/
if (free_list_length == 1) {
header_new->next = header_new;
last_search_header = header_new;
} else {
header_new->next = header_curr->next;
header_last->next = header_new;
last_search_header = header_last;
}
/** Update smallest-address node. */
if (header_curr == bottom_most_header)
bottom_most_header = header_new;
} else {
/** Not splitting, then just take this node off the list. */
header_last->next = header_curr->next;
free_list_length--;
/** Update smallest-address node. */
if (header_curr == bottom_most_header)
bottom_most_header = header_curr->next;
}
/** `header_curr` is now the chunk to return. */
header_curr->next = NULL;
header_curr->free = false;
uint32_t object = HEADER_TO_OBJECT((uint32_t) header_curr);
spinlock_release(&kheap_lock);
// _print_free_list_state();
return object;
} while (header_curr != header_begin);
/** No free chunk is large enough, time to panic. */
warn("kalloc: no free chunk large enough for size %d\n", size);
spinlock_release(&kheap_lock);
return 0;
}
/**
* Free a previously allocated object address, and merges it into the
* free-list if any neighboring chunk is free at the time.
*/
void
kfree(void *addr)
{
fl_header_t *header = (fl_header_t *) OBJECT_TO_HEADER((uint32_t) addr);
if ((uint32_t) addr < kheap_btm || (uint32_t) addr >= kheap_top) {
error("kfree: object %p is out of heap range", addr);
return;
}
if (header->magic != KHEAP_MAGIC) {
error("kfree: object %p corrupted its header magic", addr);
return;
}
/** Fill with zero bytes to catch dangling pointers use. */
header->free = true;
memset((char *) addr, 0, header->size);
spinlock_acquire(&kheap_lock);
/**
* Special case of empty free-list (all bytes exactly allocated before
* this `kfree()` call). If so, just add this free'd obejct as a node.
*/
if (free_list_length == 0) {
header->next = header;
bottom_most_header = header;
last_search_header = header;
free_list_length++;
/**
* Else, traverse the free-list starting form the bottom-most node to
* find the proper place to insert this free'd node, and then check if
* any of its up- & down-neighbor is free. If so, coalesce with them
* into a bigger free chunk.
*
* This linked-list traversal is not quite efficient and there are tons
* of ways to optimize the free-list structure, e.g., using a balanced
* binary search tree. Left as future work.
*/
} else {
/**
* Locate down-neighbor. Will get the top-most node if the free'd
* object is located below the current bottom-most node.
*/
fl_header_t *dn_header = bottom_most_header;
while (dn_header->next != bottom_most_header) {
if (dn_header < header && dn_header->next > header)
break;
dn_header = dn_header->next;
}
bool dn_coalesable = dn_header > header ? false
: HEADER_TO_OBJECT((uint32_t) dn_header) + dn_header->size == (uint32_t) header;
/**
* Locate up-neighbor. Will get the bottom-most node if the free'd
* object is located above all the free nodes.
*/
fl_header_t *up_header = dn_header > header ? bottom_most_header
: dn_header->next;
bool up_coalesable = up_header < header ? false
: HEADER_TO_OBJECT((uint32_t) header) + header->size == (uint32_t) up_header;
/** Case #1: Both coalesable. */
if (dn_coalesable && up_coalesable) {
/** Remove up-neighbor from list. */
dn_header->next = up_header->next;
free_list_length--;
/** Extend down-neighbor to cover the whole region. */
dn_header->size +=
header->size + up_header->size + 2 * sizeof(fl_header_t);
/** Update last search node. */
if (last_search_header == up_header)
last_search_header = dn_header;
/** Case #2: Only with down-neighbor. */
} else if (dn_coalesable) {
/** Extend down-neighbor to cover me. */
dn_header->size += header->size + sizeof(fl_header_t);
/** Case #3: Only with up neighbor. */
} else if (up_coalesable) {
/** Update dn-neighbor to point to me. */
dn_header->next = header;
/** Extend myself to cover up-neighbor. */
header->size += up_header->size + sizeof(fl_header_t);
header->next = up_header->next;
/** Update bottom-most node. */
if (bottom_most_header > header)
bottom_most_header = header;
/** Update last search node. */
if (last_search_header == up_header)
last_search_header = header;
/** Case #4: With neither. */
} else {
/** Link myself in the list. */
dn_header->next = header;
header->next = up_header;
free_list_length++;
/** Update bottom-most node. */
if (bottom_most_header > header)
bottom_most_header = header;
}
}
spinlock_release(&kheap_lock);
// _print_free_list_state();
}
/** Initialize the kernel heap allocator. */
void
kheap_init(void)
{
/**
* Initially, everything from `kheap_curr` (page rounded-up) upto 8MiB
* are free heap memory available to use. Initialize it as one big
* free chunk.
*/
kheap_btm = kheap_curr;
kheap_top = KHEAP_MAX;
fl_header_t *header = (fl_header_t *) kheap_btm;
uint32_t size = (kheap_top - kheap_btm) - sizeof(fl_header_t);
memset((char *) (HEADER_TO_OBJECT(kheap_btm)), 0, size);
header->size = size;
header->free = true;
header->next = header; /** Point to self initially. */
header->magic = KHEAP_MAGIC;
bottom_most_header = header;
last_search_header = header;
free_list_length = 1;
spinlock_init(&kheap_lock, "kheap_lock");
}
|
gastonfeng/bootloader_stm32 | firmata_client.h | <filename>firmata_client.h
#ifndef RTE_KB1277_REMOTE
#define RTE_KB1277_REMOTE
#include "mFirmata.h"
#include "rtos.h"
using u8 = unsigned char;
using namespace firmata;
class firmata_client : public mFirmata {
public:
int begin(Stream *s) {
stream = s;
rtos::create_thread_run("fc", 512, PriorityNormal, (void *) thd_loop, s);
return 0;
}
static int get_var_bool(int index, u16 len);
static int get_var_int(int index, short *value, u16 len);
static int get_var_float(int index, float *value, u16 len);
static int set_var_bool(int index, u8 value);
static int set_var_int(int index, int value);
static int set_var_float(int index, float value);
void *thd{};
static Stream *stream;
[[noreturn]] static void thd_loop(void *arg);
static int get_plc_var(int index);
void sendSysex(byte command, uint16_t bytec, byte *bytev) {
FirmataClass::sendSysex(stream, command, bytec, bytev);
}
static int set_plc_var(int index, byte *value, int);
};
extern firmata_client fm_client;
#endif //RTE_KB1277_REMOTE
|
gastonfeng/bootloader_stm32 | socketFirmata.h | <reponame>gastonfeng/bootloader_stm32<gh_stars>1-10
#ifndef SOCKETFIRMATA_H
#define SOCKETFIRMATA_H
#if defined(USE_LWIP) || defined(windows_x86) || defined(SYLIXOS)
#include <vector>
#ifdef RTE_APP
#include "smodule.h"
#include "logger_rte.h"
#include "plc_rte.h"
#include "rtos.h"
#endif
#include "mFirmata.h"
#ifdef USE_LWIP
#include "lwip/tcpip.h"
#include "lwip/sockets.h"
#endif
#ifdef SYLIXOS
#include "lwip/tcpip.h"
#include "lwip/sockets.h"
#define closesocket close
#endif
#include <csignal>
#define MAX_CLIENTS 3
#define DATA_MAXSIZE MAX_DATA_BYTES
#ifndef INET_ADDRSTRLEN
#define INET_ADDRSTRLEN 16
#endif
#ifndef windows_x86
extern "C" const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);
#endif
#undef write
#undef read
#undef close
class socketFirmata : public Stream, public smodule {
public:
virtual ~socketFirmata() = default;
int begin(mFirmata *);
int begin(u32 tick) override;
int run(u32 tick) override;
int diag(u32 tick) override;
size_t write(u8 c) override;
int available() override;
int read() override;
int peek() override;
/* Start listening socket sock. */
int start_listen_socket(int *sock);
void shutdown_properly(int code);
int handle_new_connection();
int receive_from_peer(void *peer);
int handle_received_message();
int loop();
[[noreturn]] static void thread(const void *arg) {
auto *debug = (socketFirmata *) arg;
debug->loop();
}
void flush() override;
void report();
int connect_server(const char *host, int port);
private:
std::vector<u8> txbuf;
mFirmata *firm;
};
#endif
#endif |
gastonfeng/bootloader_stm32 | mFirmata.h | <reponame>gastonfeng/bootloader_stm32<filename>mFirmata.h
#ifndef RTE_KT1269_MFIRMATA_H
#define RTE_KT1269_MFIRMATA_H
#undef write
#undef read
#include <smodule.h>
#include "Firmata.h"
#include "../firmata/Firmata.h"
#if defined(RTE_APP) || defined(PLC)
#include "plc_rte.h"
#include <smodule.h>
#endif
using u8 = unsigned char;
using u16 = unsigned short;
using u32 = unsigned int;
struct i2c_device_info {
byte addr;
int reg;
byte bytes;
byte stopTX;
};
enum {
CB_GET_LOG_NUMBER = 0x0,
CB_GET_LOG,
CB_GET_REMAIN_MEM,
CB_GET_RTE_VERSION,
CB_GET_BOOT_VERSION,
CB_PLC_START,
CB_PLC_STOP,
CB_GET_RTC,
CB_SET_RTC,
CB_GET_IP,
CB_SET_IP,
CB_RESET,
CB_YMODEM,
CB_THREAD_INFO,
CB_SET_FORCE,
CB_SET_V,
CB_GET_V,
CB_SET_SERIAL_RX,
CB_SET_SERIAL_TX_HIGH,
CB_SET_SERIAL_TX_LOW,
FM_GET_TASK_NRS,
FM_GET_TASK_NAME,
FM_GET_TASK_DETAIL,
FM_GET_PLC_STATE,
REPORT_PLC_MD5,
CB_PLC_LOAD,
CB_PLC_REPAIR,
CB_CLEAR_V,
CB_READ_KEY,
CB_WRITE_KEY,
CB_RM_KEY,
CB_SET_TSL_RANGE,
CB_SET_TSL_START,
CB_SET_TSL_END,
CB_GET_TSL,
CB_GET_TSL_COUNT,
CB_TSL_REMOVE,
FM_SOEM_SCAN,
CB_SET_PLC_FILE,
CB_CPU_USAGE,
CB_REMOVE_FILE,
CB_WIFI_LIST,
CB_WIFI_SET_PASS,
CB_GOTO_IAP,
FM_PUT_DATA_BLOCK,
FM_GET_LOC_SIZE,
FM_GET_LOC,
FM_SET_LOC,
FM_GET_DBG_SIZE,
FM_GET_DBG,
FM_SET_DBG,
FM_GET_CPU_SN,
FM_GET_PLC_INFO,
FM_FLASH_CLEAR,
FM_READ_LOC,
FM_WRITE_LOC,
FM_LOG_SET_LEVEL,
FM_READ_MEM,
FM_WRITE_MEM,
FM_READ_VALUE,
FM_READ_VALUE_REP,
FM_WRITE_VALUE,
FM_WRITE_VALUE_REP,
FM_READ_BIT,
FM_READ_BIT_REP,
FM_WRITE_BIT,
FM_WRITE_BIT_REP,
FM_GET_NET_BUF_STAT,
FM_GET_LOCATION,
FM_SET_LOCATION,
FM_LIST_KEY,
FM_READ_KEY_BYTES,
FM_WRITE_KEY_BYTES,
FM_LAST
};
class mFirmata : public firmata::FirmataClass, public smodule {
public:
mFirmata();
~mFirmata() override = default;
int loop(Stream *FirmataStream);
int run(u32 tick) override;
int begin(u32 tick) override { return 0; }
int diag(u32 tick) override {
return 0;
}
void begin(Stream *FirmataStream) {
//
}
void report(Stream *FirmataStream);
int getPinState(byte pin) override {
return pinState[pin];
}
/**
* Set the pin state. The pin state of an output pin is the pin value. The state of an
* input pin is 0, unless the pin has it's internal pull up resistor enabled, then the value is 1.
* @param pin The pin to set the state of
* @param state Set the state of the specified pin
*/
void setPinState(byte pin, int state) override {
pinState[pin] = state;
}
u32 previousMillis = 0;
// u32 analogInputsToReport = 0;
int queryIndex = -1;
void outputPort(Stream *FirmataStream, byte portNumber, byte portValue, byte forceSend);
#ifdef USE_MEMBLOCK
mem_block *dev = nullptr;
#endif
//时序数据库操作
#ifdef USE_KVDB
struct tsdb_sec_info sector{};
uint32_t traversed_len{};
#endif
systemCallbackFunction i_am_here_cb;
int setValue(Stream *FirmataStream, int index, void *valBuf, u8 size);
int get_flag(u16 cmd);
int clr_flag(u16 cmd);
int set_flag(u16 cmd);
u8 respose[FM_LAST / 8 + 1]{};
int getValue(Stream *pStream, int index, u8 *value_buf, u16 len);
int getBit(Stream *pStream, int index, u8 *value_buf, u16 len);
u8 valueBuf[8]{};
char valueLen{};
u32 last_tick;
};
extern mFirmata ifirmata;
#endif |
Guenael/tinybeacon-1300 | config.h | /*
* FreeBSD License
* Copyright (c) 2016, Guenael
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#pragma once
/* CPU frequency -- DO NOT CHANGE */
#define F_CPU 10000000UL
/* Standard definition used almost everywhere */
#include <stdint.h>
/* Beacon config -- Callsign / Locator / Frequencies */
#define PI4_MESSAGE "VA2NQ " // UPDATE with your Callsign (8 chars, padding with spaces)
#define PI4_FREQUENCY 1296500000.0 // UPDATE with frequency aligned with the frequency bands
#define MORSE_MESSAGE "VA2NQ FN35NL " // UPDATE with your Callsign + Locator
#define MORSE_FREQUENCY 1296500000.0 // UPDATE with frequency aligned with the frequency bands ( Propagation Beacons Exclusive )
#define WSPR_CALLSIGN "VA2NQ " // Exactly 6 characters (Padding with space at start. Ex " K1AB " or " K1ABC" or "VE1ABC")
#define WSPR_LOCATOR "FN35" // Exactly 4 characters (First part of the locator)
#define WSPR_POWER 33 // Numerical value in dBm (range 0-60, check allowed values)
#define WSPR_FREQUENCY 1296501450.0 // UPDATE with frequency aligned with the wspr frequencies
/* | |
| Example : VA2NQ Beacon -- Frequency band plan |
| |
| BAND | CW/PI4 Frequency | WSPR Frequency |
|--------|------------------|---------------------|
| 50MHz | 50295000.0 | 50294450.0 |
| 70MHz | NA, Region 2 | NA, Region 2 |
| 144MHz | 144491000.0 | 144490450.0 |
| 222MHz | 222295000.0 +1? | 222294450.0 |
| 440MHz | 432302000.0 | 432301450.0 |
| 1.3GHz | 1296500000.0 | 1296501450.0 | */
/* Switch ADI/Si Memo
- pi4.c & wspr.c : change timing 1.0ms 12.0ms
- pll.c : //#define ADI
- config.h : change freq.
*/ |
Guenael/tinybeacon-1300 | pll.c | <gh_stars>1-10
/*
* FreeBSD License
* Copyright (c) 2016, Guenael
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#include "pll.h"
#include "twi.h"
#include <avr/io.h>
#include <util/delay.h>
#define ADI
/* === ADF4355 CODE === */
#ifdef ADI
#define COUNTER_RESET 4 // 5th bit, Register 4
#define AUTOCAL 21 // 22th bit, Register 0
#define RF_OUTPUT_ENABLE 6 // 7th bit, Register 6
#define PLL_UPDATE_DELAY 2
/* Precalculated settings for the PLL */
static uint32_t pllGeneralSettings[13] = {
0x00201CC0, // Register 0
0x0CCCCCC1, // Register 1
0x00000012, // Register 2
0x40000003, // Register 3
0x3000C184, // Register 4
0x00800025, // Register 5
0x35002CF6, // Register 6
0x12000007, // Register 7
0x102D0428, // Register 8
0x14053CF9, // Register 9
0x60C017FA, // Register 10
0x0061300B, // Register 11
0x0000041C // Register 12
};
/* Precalculated settings for the PLL, using 4 Banks */
static uint32_t pllCustomSettings[6][2]; // 6 Tones MAX
void pllTransmitByte(uint8_t data) {
/* Enable PLL LE */
PORTB &= ~_BV(PORTB2);
/* Start transmission */
SPDR = data;
/* Wait for transmission complete */
while(!(SPSR & _BV(SPIF)));
/* Disable PLL LE */
PORTB |= _BV(PORTB2);
}
void pllTransmitWord(uint32_t data) {
/* Enable PLL LE */
PORTB &= ~_BV(PORTB2);
uint8_t *p = (uint8_t*)&data;
for (uint8_t i=0; i<4; i++) {
/* Start transmission */
SPDR = p[3-i]; // Little endian
/* Wait for transmission complete */
while(!(SPSR & _BV(SPIF)));
}
/* Disable PLL LE */
PORTB |= _BV(PORTB2);
}
void pllInit(uint8_t addr) {
DDRB |= _BV(DDB3); /* MOSI - Enable output */
DDRB |= _BV(DDB5); /* SCK - Enable output */
//DDRB &= ~_BV(DDB0); /* PLL_INTR - Set input */
//PORTB |= ~_BV(PORTB0); /* Activate pull-ups in PORTB pin 12 */
DDRB |= _BV(DDB2); /* PLL_LE - Enable output */
PORTB |= _BV(PORTB2); /* PLL_LE disable */
DDRD |= _BV(DDD6); /* PA_EN - Set output */
PORTD &= ~_BV(PORTD6); /* PA_EN disable at start */
/* Enable SPI, as Master, prescaler = Fosc/16 */
SPCR = _BV(SPE) | _BV(MSTR) | _BV(SPR0);
/* General settigs based on Morse freq */
pllSetFreq((MORSE_FREQUENCY * 1000000), 0);
/* First initialisation of the PLL, with the default 0 */
_delay_ms(100);
pllTransmitWord(pllGeneralSettings[12]);
pllTransmitWord(pllGeneralSettings[11]);
pllTransmitWord(pllGeneralSettings[10]);
pllTransmitWord(pllGeneralSettings[9]);
pllTransmitWord(pllGeneralSettings[8]);
pllTransmitWord(pllGeneralSettings[7]);
pllTransmitWord(pllGeneralSettings[6]);
pllTransmitWord(pllGeneralSettings[5]);
pllTransmitWord(pllGeneralSettings[4]);
pllTransmitWord(pllGeneralSettings[3]);
pllTransmitWord(pllGeneralSettings[2]);
pllTransmitWord(pllGeneralSettings[1]);
pllTransmitWord(pllGeneralSettings[0]);
_delay_ms(100);
}
void pllShutdown() {
}
void pllUpdate(uint8_t bank) {
/* Regular way to update the PLL : Documentation ADF4355-2, page 29
http://www.analog.com/media/en/technical-documentation/data-sheets/ADF4355-2.pdf */
pllGeneralSettings[4] |= (1UL<<COUNTER_RESET); // Counter reset enabled [DB4 = 1]
pllTransmitWord(pllGeneralSettings[4]); // Register 4 (counter reset enabled [DB4 = 1])
//pllTransmitWord(pllGeneralSettings[bank][2]); // Register 2
pllTransmitWord(pllCustomSettings[bank][1]); // Register 1
pllCustomSettings[bank][0] &= ~(1UL<<AUTOCAL); // Autocal enable
pllTransmitWord(pllCustomSettings[bank][0]); // Register 0 (autocal disabled [DB21 = 0])
pllGeneralSettings[4] &= ~(1UL<<COUNTER_RESET); // Counter reset disable [DB4 = 0]
pllTransmitWord(pllGeneralSettings[4]); // Register 4 (counter reset disabled [DB4 = 0])
_delay_us(500); // Sleep FIXME
pllCustomSettings[bank][0] |= (1UL<<AUTOCAL); // Autocal enable
pllTransmitWord(pllCustomSettings[bank][0]); // Register 0 (autocal enabled [DB21 = 1])
_delay_us(216); // Align on 1ms
}
void pllUpdateTiny(uint8_t bank) {
/* Quick and dirty update if the delta is very low */
pllTransmitWord(pllCustomSettings[bank][1]); // Register 1
pllCustomSettings[bank][0] |= (1UL<<AUTOCAL); // Autocal enable
pllTransmitWord(pllCustomSettings[bank][0]); // Register 0 (autocal enabled [DB21 = 1])
_delay_us(900); // Align on 1ms
}
void pllSetFreq(uint64_t freq, uint8_t bank) {
/* Calculate the frequency register -- Application 144MHz (Usable only beetween : 106.25 - 212.5 MHz) */
/* NOTE : AVR do NOT support double, and precision of float are insuffisant, so I use uint64... */
/* Output divider */
uint8_t pllDivider = 1;
/* Convert & use freq in MHz */
uint64_t freqMHz = freq / 1000000000000;
if ( freqMHz < (6800/128) ) { // freq < 53.125
pllGeneralSettings[6] |= 0x00C00000;
pllDivider = 128; // Implicit prescaler /2
} else if ( freqMHz < (6800/64) ) { // freq < 106.25
pllGeneralSettings[6] |= 0x00C00000;
pllDivider = 64;
} else if ( freqMHz < (6800/32) ) { // freq < 212.5
pllGeneralSettings[6] |= 0x00A00000;
pllDivider = 32;
} else if ( freqMHz < (6800/16) ) { // freq < 425
pllGeneralSettings[6] |= 0x00800000;
pllDivider = 16;
} else if ( freqMHz < (6800/8) ) { // freq < 850
pllGeneralSettings[6] |= 0x00600000;
pllDivider = 8;
} else if ( freqMHz < (6800/4) ) { // freq < 1700
pllGeneralSettings[6] |= 0x00400000;
pllDivider = 4;
} else if ( freqMHz < (6800/2) ) { // freq < 3400
pllGeneralSettings[6] |= 0x00200000;
pllDivider = 2;
} else { //if ( freqMHz < (6800/1) ) { // freq < 6800
pllGeneralSettings[6] |= 0x00000000; // Useless, but consistency...
pllDivider = 1;
}
uint64_t pllVcoFreq = freq * pllDivider;
uint64_t pllN = pllVcoFreq / 10000000;
uint64_t pllNint1 = pllN / 1000000;
uint64_t pllNfrac1 = ((pllN - (pllNint1*1000000)) * 16777216)/1000000;
uint32_t intN = (uint32_t)pllNint1;
uint32_t intFrac1 = (uint32_t)pllNfrac1;
pllCustomSettings[bank][0] = (intN<<4);
pllCustomSettings[bank][1] = (intFrac1<<4) | 0x00000001;
}
void pllRfOutput(uint8_t enable) {
if (enable)
pllGeneralSettings[6] |= (1UL<<RF_OUTPUT_ENABLE); // Bank 0 used by default
else
pllGeneralSettings[6] &= ~(1UL<<RF_OUTPUT_ENABLE);
pllTransmitWord(pllGeneralSettings[6]);
}
void pllPA(uint8_t enable) {
if (enable)
PORTD |= _BV(PORTD6);
else
PORTD &= ~_BV(PORTD6);
}
uint32_t pllGetTiming() {
return(1);
}
/* === Si5351 CODE === */
#else
#define SI_CLK_ENABLE 3
#define SI_PLL_INPUT_SRC 15
#define SI_CLK_CONTROL 16
#define SI_SYNTH_PLL_A 26 // Multisynth NA
#define SI_SYNTH_PLL_B 34 // Multisynth NB
#define SI_SYNTH_MS_0 42
#define SI_VCXO_PARAM 162
#define SI_PLL_RESET 177
#define XTAL_FREQ 27000000000000
#define TCXO_FREQ 10000000000000
/* Global definition for the I2C GPS address */
static uint8_t pll_si5351c_Addr;
static uint8_t pll_si5351c_BankSettings[6][8];
void pllSendRegister(uint8_t reg, uint8_t data) {
uint8_t tmp[2] = {0};
tmp[0] = reg;
tmp[1] = data;
twi_writeTo(pll_si5351c_Addr, tmp, sizeof(tmp), 1, 0);
_delay_ms(1);
}
void pllInit(uint8_t addr) {
DDRD |= _BV(DDD6); /* PA_EN - Set output */
PORTD &= ~_BV(PORTD6); /* PA_EN disable at start */
DDRB &= ~_BV(DDB0); /* PLL_INTR - Set input */
PORTB |= ~_BV(PORTB0); /* Activate pull-ups in PORTB pin 12 */
DDRB |= _BV(DDB2); /* PLL_LE - Enable output */
PORTB &= ~_BV(PORTB2); /* PLL_LE enable at start for config */
_delay_ms(100);
/* Define I2C address for the PLL */
pll_si5351c_Addr = addr;
pllSendRegister(SI_CLK_ENABLE, 0xFF); // Disable all output
pllSendRegister(SI_PLL_INPUT_SRC, 0x0C); // Use external clock on PLL-A & PLL-B
pllSendRegister(SI_CLK_CONTROL+0, 0x0F); // Turn on CLK0 with PLL-A & 8mA (0x0F)
pllSendRegister(SI_CLK_CONTROL+1, 0x84); // Turn off
pllSendRegister(SI_CLK_CONTROL+2, 0x84); // Turn off
pllSendRegister(SI_CLK_CONTROL+3, 0x84); // Turn off
pllSendRegister(SI_CLK_CONTROL+4, 0x84); // Turn off
pllSendRegister(SI_CLK_CONTROL+5, 0x84); // Turn off
pllSendRegister(SI_CLK_CONTROL+6, 0x84); // Turn off
pllSendRegister(SI_CLK_CONTROL+7, 0x84); // Turn off
/* MultiSynth0
P1 : Integer part
P2 : Fractional numerator
P3 : Fractional denominator
*/
pllSendRegister(SI_SYNTH_MS_0+0, 0x00); // MS0_P3[15:8]
pllSendRegister(SI_SYNTH_MS_0+1, 0x01); // MS0_P3[7:0]
pllSendRegister(SI_SYNTH_MS_0+2, 0x00); // R0_DIV[2:0] + MS0_DIVBY4[1:0] + MS0_P1[17:16]
pllSendRegister(SI_SYNTH_MS_0+3, 0x01); // MS0_P1[15:8]
pllSendRegister(SI_SYNTH_MS_0+4, 0x00); // MS0_P1[7:0]
pllSendRegister(SI_SYNTH_MS_0+5, 0x00); // MS0_P3[19:16] + MS0_P2[19:16]
pllSendRegister(SI_SYNTH_MS_0+6, 0x00); // MS0_P2[15:8]
pllSendRegister(SI_SYNTH_MS_0+7, 0x00); // MS0_P2[7:0]
pllSendRegister(SI_CLK_ENABLE, 0xFE); // Disable all output exept CLK0 (CLK0_OEB)
pllSendRegister(SI_PLL_RESET, 0xA0);
}
void pllShutdown() {
}
void pllUpdate(uint8_t bank) {
pllSendRegister(SI_SYNTH_PLL_A + 0, pll_si5351c_BankSettings[bank][0]);
pllSendRegister(SI_SYNTH_PLL_A + 1, pll_si5351c_BankSettings[bank][1]);
pllSendRegister(SI_SYNTH_PLL_A + 2, pll_si5351c_BankSettings[bank][2]);
pllSendRegister(SI_SYNTH_PLL_A + 3, pll_si5351c_BankSettings[bank][3]);
pllSendRegister(SI_SYNTH_PLL_A + 4, pll_si5351c_BankSettings[bank][4]);
pllSendRegister(SI_SYNTH_PLL_A + 5, pll_si5351c_BankSettings[bank][5]);
pllSendRegister(SI_SYNTH_PLL_A + 6, pll_si5351c_BankSettings[bank][6]);
pllSendRegister(SI_SYNTH_PLL_A + 7, pll_si5351c_BankSettings[bank][7]);
//pllSendRegister(SI_PLL_RESET, 0xA0); // Reset both PLL -- make glitch!!
_delay_us(1702); // 8 commands take : 10.5ms, aling on 12ms
}
void pllUpdateTiny(uint8_t bank) {
pllUpdate(bank);
}
void pllMultiSynth(uint32_t divider, uint8_t rDiv) {
uint32_t P1 = 128 * divider - 512;
uint32_t P2 = 0; // P2 = 0, P3 = 1 forces an integer value for the divider
uint32_t P3 = 1;
pllSendRegister(SI_SYNTH_MS_0 + 0, (P3 & 0x0000FF00) >> 8);
pllSendRegister(SI_SYNTH_MS_0 + 1, (P3 & 0x000000FF));
pllSendRegister(SI_SYNTH_MS_0 + 2, ((P1 & 0x00030000) >> 16) | rDiv);
pllSendRegister(SI_SYNTH_MS_0 + 3, (P1 & 0x0000FF00) >> 8);
pllSendRegister(SI_SYNTH_MS_0 + 4, (P1 & 0x000000FF));
pllSendRegister(SI_SYNTH_MS_0 + 5, ((P3 & 0x000F0000) >> 12) | ((P2 & 0x000F0000) >> 16));
pllSendRegister(SI_SYNTH_MS_0 + 6, (P2 & 0x0000FF00) >> 8);
pllSendRegister(SI_SYNTH_MS_0 + 7, (P2 & 0x000000FF));
}
void pllSetFreq(uint64_t freq, uint8_t bank) {
uint64_t divider = 900000000000000 / freq; // 900 / 144 = 6.25 > 6
if (divider % 2) divider--;
pllMultiSynth(divider, 0); // FIXME !!! 1 time only
uint64_t pllFreq = divider * freq; // 6 * 144 = 864
uint32_t mult = (uint32_t)(pllFreq / TCXO_FREQ); // 864 / 10 = 86.4 > 86 (entre 15 & 90)
uint32_t num = (uint32_t)(((pllFreq % TCXO_FREQ) * 1048575) / TCXO_FREQ); //
uint32_t denom = 1048575;
// FIXME best denom ajust for WSPR
uint32_t P1,P2,P3;
P1 = 128 * mult + ((128 * num) / denom) - 512;
P2 = 128 * num - denom * ((128 * num) / denom);
P3 = denom;
/* Packing */
pll_si5351c_BankSettings[bank][0] = (P3 & 0x0000FF00) >> 8;
pll_si5351c_BankSettings[bank][1] = (P3 & 0x000000FF);
pll_si5351c_BankSettings[bank][2] = (P1 & 0x00030000) >> 16;
pll_si5351c_BankSettings[bank][3] = (P1 & 0x0000FF00) >> 8;
pll_si5351c_BankSettings[bank][4] = (P1 & 0x000000FF);
pll_si5351c_BankSettings[bank][5] = ((P3 & 0x000F0000) >> 12) | ((P2 & 0x000F0000) >> 16);
pll_si5351c_BankSettings[bank][6] = (P2 & 0x0000FF00) >> 8;
pll_si5351c_BankSettings[bank][7] = (P2 & 0x000000FF);
}
void pllRfOutput(uint8_t enable) {
if (enable) {
PORTB &= ~_BV(PORTB2);
} else {
//PORTB |= _BV(PORTB2); // DEBUG always ON
}
}
void pllPA(uint8_t enable) {
if (enable)
PORTD |= _BV(PORTD6);
else
PORTD &= ~_BV(PORTD6);
}
uint32_t pllGetTiming() {
return(12);
}
#endif
|
cosmo0920/ioext_c | ext/ioext/ioext.h | /* ioext */
/* Copyright 2020- <NAME>*/
/* */
/* 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 _IOEXT_H_
#define _IOEXT_H_
#include <ruby.h>
#include <ruby/encoding.h>
#ifdef __GNUC__
#include <w32api.h>
#define MINIMUM_WINDOWS_VERSION WindowsVista
#else /* __GNUC__ */
#define MINIMUM_WINDOWS_VERSION 0x0600 /* Vista */
#endif /* __GNUC__ */
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif /* WIN32_WINNT */
#define _WIN32_WINNT MINIMUM_WINDOWS_VERSION
#include <stdio.h>
VALUE rb_cIOExt;
#endif // _IOEXT_H
|
cosmo0920/ioext_c | ext/ioext/ioext.c | <filename>ext/ioext/ioext.c
/* ioext */
/* Copyright 2020- <NAME>*/
/* */
/* 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. */
#include <ioext.h>
struct IOExt {};
static void ioext_free(void* ioext);
static const rb_data_type_t rb_win_ioext_type = {
"ioext/c_runtime",
{
0,
ioext_free,
0,
},
NULL,
NULL,
RUBY_TYPED_FREE_IMMEDIATELY
};
static void
ioext_free(void* ptr)
{
xfree(ptr);
}
static VALUE
rb_win_ioext_alloc(VALUE klass)
{
VALUE obj;
struct IOExt* ioext;
obj = TypedData_Make_Struct(
klass, struct IOExt, &rb_win_ioext_type, ioext);
return obj;
}
static VALUE
rb_win_ioext_initialize(VALUE self)
{
return Qnil;
}
static VALUE
rb_win_ioext_getmaxstdio(VALUE self)
{
return INT2NUM(_getmaxstdio());
}
static VALUE
rb_win_ioext_setmaxstdio(VALUE self, VALUE newmaxfd)
{
DWORD ret = 0;
const int fdlimit = 2048;
ret = _setmaxstdio(min(NUM2INT(newmaxfd), fdlimit));
return INT2NUM(ret);
}
void
Init_ioext(void)
{
rb_cIOExt = rb_define_class("IOExt", rb_cObject);
rb_define_alloc_func(rb_cIOExt, rb_win_ioext_alloc);
rb_define_const(rb_cIOExt, "IOB_ENTRIES", LONG2NUM(_IOB_ENTRIES));
rb_define_method(rb_cIOExt, "initialize", rb_win_ioext_initialize, 0);
rb_define_method(rb_cIOExt, "maxstdio", rb_win_ioext_getmaxstdio, 0);
rb_define_method(rb_cIOExt, "maxstdio=", rb_win_ioext_setmaxstdio, 1);
rb_define_method(rb_cIOExt, "setmaxstdio", rb_win_ioext_setmaxstdio, 1);
}
|
UTS-CAS/ouster_example | ouster_client/include/ouster/types.h | <reponame>UTS-CAS/ouster_example
/**
* Copyright (c) 2018, Ouster, Inc.
* All rights reserved.
*
* @file
* @brief Ouster client datatypes and constants
*/
#pragma once
#include <Eigen/Core>
#include <array>
#include <cstdint>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "nonstd/optional.hpp"
namespace ouster {
using nonstd::optional;
/**
* For image operations.
*
* @tparam T The data type for the array.
*/
template <typename T>
using img_t = Eigen::Array<T, -1, -1, Eigen::RowMajor>;
/** Used for transformations. */
using mat4d = Eigen::Matrix<double, 4, 4, Eigen::DontAlign>;
namespace sensor {
/** Unit of range from sensor packet, in meters. */
constexpr double range_unit = 0.001;
/** Design values for altitude and azimuth offset angles for gen1 sensors. */
extern const std::vector<double> gen1_altitude_angles;
/** Design values for altitude and azimuth offset angles for gen1 sensors. */
extern const std::vector<double> gen1_azimuth_angles;
/** Design values for imu and lidar to sensor-frame transforms. */
extern const mat4d default_imu_to_sensor_transform;
/** Design values for imu and lidar to sensor-frame transforms. */
extern const mat4d default_lidar_to_sensor_transform;
/**
* Constants used for configuration. Refer to the sensor documentation for the
* meaning of each option.
*/
enum lidar_mode {
MODE_UNSPEC = 0, ///< lidar mode: unspecified
MODE_512x10, ///< lidar mode: 10 scans of 512 columns per second
MODE_512x20, ///< lidar mode: 20 scans of 512 columns per second
MODE_1024x10, ///< lidar mode: 10 scans of 1024 columns per second
MODE_1024x20, ///< lidar mode: 20 scans of 1024 columsn per second
MODE_2048x10 ///< lidar mode: 10 scans of 2048 columns per second
};
/**
* Mode controlling timestamp method. Refer to the sensor documentation for the
* meaning of each option.
*/
enum timestamp_mode {
/**
* Timestamp mode unspecified.
*/
TIME_FROM_UNSPEC = 0,
/**
* Use the internal clock.
*/
TIME_FROM_INTERNAL_OSC,
/**
* A free running counter synced to the SYNC_PULSE_IN input
* counts seconds (# of pulses) and nanoseconds since sensor turn
* on.
*/
TIME_FROM_SYNC_PULSE_IN,
/** Synchronize with an external PTP master. */
TIME_FROM_PTP_1588
};
/**
* Mode controlling sensor operation. Refer to the sensor documentation for the
* meaning of each option.
*/
enum OperatingMode {
OPERATING_NORMAL = 1, ///< Normal sensor operation
OPERATING_STANDBY ///< Standby
};
/**
* Mode controlling ways to input timesync information. Refer to the sensor
* documentation for the meaning of each option.
*/
enum MultipurposeIOMode {
MULTIPURPOSE_OFF = 1, ///< Multipurpose IO is turned off (default)
/**
* Used in conjunction with timestamp_mode::TIME_FROM_SYNC_PULSE_IN
* to enable time pulses in on the multipurpose io input.
*/
MULTIPURPOSE_INPUT_NMEA_UART,
/**
* Output a SYNC_PULSE_OUT signal synchronized with
* the internal clock.
*/
MULTIPURPOSE_OUTPUT_FROM_INTERNAL_OSC,
/**
* Output a SYNC_PULSE_OUT signal synchronized with
* a SYNC_PULSE_IN provided to the unit.
*/
MULTIPURPOSE_OUTPUT_FROM_SYNC_PULSE_IN,
/**
* Output a SYNC_PULSE_OUT signal synchronized with
* an external PTP IEEE 1588 master.
*/
MULTIPURPOSE_OUTPUT_FROM_PTP_1588,
/**
* Output a SYNC_PULSE_OUT signal with a user defined
* rate in an integer number of degrees.
*/
MULTIPURPOSE_OUTPUT_FROM_ENCODER_ANGLE
};
/**
* Polarity represents polarity of NMEA UART and SYNC_PULSE inputs and outputs.
* See sensor docs for more details.
*/
enum Polarity {
POLARITY_ACTIVE_LOW = 1, ///< ACTIVE_LOW
POLARITY_ACTIVE_HIGH ///< ACTIVE_HIGH
};
/**
* Baud rate the sensor attempts for NMEA UART input $GPRMC messages
* See sensor docs for more details.
*/
enum NMEABaudRate {
BAUD_9600 = 1, ///< 9600 bits per second UART baud rate
BAUD_115200 ///< 115200 bits per second UART baud rate
};
/** Profile indicating packet format of lidar data. */
enum UDPProfileLidar {
/** Legacy lidar data */
PROFILE_LIDAR_LEGACY = 1,
/** Dual Returns data */
PROFILE_RNG19_RFL8_SIG16_NIR16_DUAL,
/** Single Returns data */
PROFILE_RNG19_RFL8_SIG16_NIR16,
/** Single Returns Low Data Rate */
PROFILE_RNG15_RFL8_NIR8,
};
/** Profile indicating packet format of IMU data. */
enum UDPProfileIMU {
PROFILE_IMU_LEGACY = 1 ///< Legacy IMU data
};
/**
* Convenience type alias for azimuth windows, the window over which the sensor
* fires in millidegrees.
*/
using AzimuthWindow = std::pair<int, int>;
/**
* Convenience type alias for column windows, the window over which the sensor
* fires in columns.
*/
using ColumnWindow = std::pair<int, int>;
/**
* Struct for sensor configuration parameters.
*/
struct sensor_config {
optional<std::string> udp_dest; ///< The destination address for the
///< lidar/imu data to be sent to
optional<int> udp_port_lidar; ///< The destination port for the lidar data
///< to be sent to
optional<int>
udp_port_imu; ///< The destination port for the imu data to be sent to
// TODO: replace ts_mode and ld_mode when timestamp_mode and
// lidar_mode get changed to CapsCase
/**
* The timestamp mode for the sensor to use.
* Refer to timestamp_mode for more details.
*/
optional<timestamp_mode> ts_mode;
/**
* The lidar mode for the sensor to use.
* Refer to lidar_mode for more details.
*/
optional<lidar_mode> ld_mode;
/**
* The operating mode for the sensor to use.
* Refer to OperatingMode for more details.
*/
optional<OperatingMode> operating_mode;
/**
* The multipurpose io mode for the sensor to use.
* Refer to MultipurposeIOMode for more details.
*/
optional<MultipurposeIOMode> multipurpose_io_mode;
/**
* The azimuth window for the sensor to use.
* Refer to AzimuthWindow for more details.
*/
optional<AzimuthWindow> azimuth_window;
/**
* Multiplier for signal strength of sensor. See the sensor docs for more
* details on usage.
*/
optional<int> signal_multiplier;
/**
* The nmea polarity for the sensor to use.
* Refer to Polarity for more details.
*/
optional<Polarity> nmea_in_polarity;
/**
* Whether NMEA UART input $GPRMC messages should be ignored.
* Refer to the sensor docs for more details.
*/
optional<bool> nmea_ignore_valid_char;
/**
* The nmea baud rate for the sensor to use.
* Refer to Polarity> for more details.
*/
optional<NMEABaudRate> nmea_baud_rate;
/**
* Number of leap seconds added to UDP timestamp.
* See the sensor docs for more details.
*/
optional<int> nmea_leap_seconds;
/**
* Polarity of SYNC_PULSE_IN input.
* See Polarity for more details.
*/
optional<Polarity> sync_pulse_in_polarity;
/**
* Polarity of SYNC_PULSE_OUT output.
* See Polarity for more details.
*/
optional<Polarity> sync_pulse_out_polarity;
/**
* Angle in degrees that sensor traverses between each SYNC_PULSE_OUT pulse.
* See senor docs for more details.
*/
optional<int> sync_pulse_out_angle;
/**
* Width of SYNC_PULSE_OUT pulse in ms.
* See sensor docs for more details.
*/
optional<int> sync_pulse_out_pulse_width;
/**
* Frequency of SYNC_PULSE_OUT pulse in Hz.
* See sensor docs for more details.
*/
optional<int> sync_pulse_out_frequency;
/**
* Whether phase locking is enabled.
* See sensor docs for more details.
*/
optional<bool> phase_lock_enable;
/**
* Angle that sensors are locked to in millidegrees.
* See sensor docs for more details.
*/
optional<int> phase_lock_offset;
/**
* Columns per packet.
* See sensor docs for more details.
*/
optional<int> columns_per_packet;
/**
* The lidar profile for the sensor to use.
* Refer to UDPProfileLidar for more details.
*/
optional<UDPProfileLidar> udp_profile_lidar;
/**
* The imu profile for the sensor to use.
* Refer to UDPProfileIMU for more details.
*/
optional<UDPProfileIMU> udp_profile_imu;
};
/** Stores data format information. */
struct data_format {
uint32_t pixels_per_column; ///< pixels per column
uint32_t columns_per_packet; ///< columns per packet
uint32_t
columns_per_frame; ///< columns per frame, should match with lidar mode
std::vector<int>
pixel_shift_by_row; ///< shift of pixels by row to enable destagger
ColumnWindow column_window; ///< window of columns over which sensor fires
UDPProfileLidar udp_profile_lidar; ///< profile of lidar packet
UDPProfileIMU udp_profile_imu; ///< profile of imu packet
};
/** Stores necessary information from sensor to parse and project sensor data.
*/
struct sensor_info {
[[deprecated]] std::string
name; ///< @deprecated: will be removed in the next version
std::string sn; ///< sensor serial number
std::string fw_rev; ///< fw revision
lidar_mode mode; ///< lidar mode of sensor
std::string prod_line; ///< prod line
data_format format; ///< data format of sensor
std::vector<double>
beam_azimuth_angles; ///< beam azimuth angles for 3D projection
std::vector<double>
beam_altitude_angles; ///< beam altitude angles for 3D projection
double lidar_origin_to_beam_origin_mm; ///< distance between lidar origin
///< and beam origin in mm
mat4d imu_to_sensor_transform; ///< transform between sensor coordinate
///< frame and imu
mat4d lidar_to_sensor_transform; ///< transform between lidar and sensor
///< coordinate frames
mat4d extrinsic; ///< extrinsic matrix
uint32_t init_id; ///< initialization ID updated every reinit
uint16_t udp_port_lidar; ///< the lidar destination port
uint16_t udp_port_imu; ///< the imu destination port
};
/**
* Equality for data_format.
*
* @param[in] lhs The first object to compare.
* @param[in] rhs The second object to compare.
*
* @return lhs == rhs
*/
bool operator==(const data_format& lhs, const data_format& rhs);
/**
* Not-Equality for data_format.
*
* @param[in] lhs The first object to compare.
* @param[in] rhs The second object to compare.
*
* @return lhs != rhs
*/
bool operator!=(const data_format& lhs, const data_format& rhs);
/**
* Equality for sensor_info.
*
* @param[in] lhs The first object to compare.
* @param[in] rhs The second object to compare.
*
* @return lhs == rhs
*/
bool operator==(const sensor_info& lhs, const sensor_info& rhs);
/**
* Not-Equality for sensor_info.
*
* @param[in] lhs The first object to compare.
* @param[in] rhs The second object to compare.
*
* @return lhs != rhs
*/
bool operator!=(const sensor_info& lhs, const sensor_info& rhs);
/**
* Equality for sensor config.
*
* @param[in] lhs The first object to compare.
* @param[in] rhs The second object to compare.
*
* @return lhs == rhs
*/
bool operator==(const sensor_config& lhs, const sensor_config& rhs);
/**
* Not-Equality for sensor config.
*
* @param[in] lhs The first object to compare.
* @param[in] rhs The second object to compare.
*
* @return lhs != rhs
*/
bool operator!=(const sensor_config& lhs, const sensor_config& rhs);
/**
* Get a default sensor_info for the given lidar mode.
*
* @param[in] mode lidar mode to generate default sensor_info for.
*
* @return default sensor_info for the OS1-64.
*/
sensor_info default_sensor_info(lidar_mode mode);
/**
* Get string representation of a lidar mode.
*
* @param[in] mode lidar_mode to get the string representation for.
*
* @return string representation of the lidar mode, or "UNKNOWN".
*/
std::string to_string(lidar_mode mode);
/**
* Get lidar mode from string.
*
* @param[in] s String to decode.
*
* @return lidar mode corresponding to the string, or 0 on error.
*/
lidar_mode lidar_mode_of_string(const std::string& s);
/**
* Get number of columns in a scan for a lidar mode.
*
* @param[in] mode lidar_mode to get the number of columns for.
*
* @return number of columns per rotation for the mode.
*/
uint32_t n_cols_of_lidar_mode(lidar_mode mode);
/**
* Get the lidar rotation frequency from lidar mode.
*
* @param[in] mode Lidar mode to get the rotation frequency from.
*
* @return lidar rotation frequency in Hz.
*/
int frequency_of_lidar_mode(lidar_mode mode);
/**
* Get string representation of a timestamp mode.
*
* @param[in] mode timestamp_mode to get the string representation for.
*
* @return string representation of the timestamp mode, or "UNKNOWN".
*/
std::string to_string(timestamp_mode mode);
/**
* Get timestamp mode from string.
*
* @param[in] s String to decode into a timestamp mode.
*
* @return timestamp mode corresponding to the string, or 0 on error.
*/
timestamp_mode timestamp_mode_of_string(const std::string& s);
/**
* Get string representation of an operating mode.
*
* @param[in] mode Operating mode to get the string representation from.
*
* @return string representation of the operating mode, or "UNKNOWN".
*/
std::string to_string(OperatingMode mode);
/**
* Get operating mode from string.
*
* @param s String to get the operating mode from.
*
* @return operating mode corresponding to the string, or 0 on error.
*/
optional<OperatingMode> operating_mode_of_string(const std::string& s);
/**
* Get string representation of a multipurpose io mode.
*
* @param[in] mode Multipurpose io mode to get a string representation from.
*
* @return string representation of the multipurpose io mode, or "UNKNOWN".
*/
std::string to_string(MultipurposeIOMode mode);
/**
* Get multipurpose io mode from string.
*
* @param[in] s String to decode into a multipurpose io mode.
*
* @return multipurpose io mode corresponding to the string, or 0 on error.
*/
optional<MultipurposeIOMode> multipurpose_io_mode_of_string(
const std::string& s);
/**
* Get string representation of a polarity.
*
* @param[in] polarity The polarity to get the string representation of.
*
* @return string representation of the polarity, or "UNKNOWN".
*/
std::string to_string(Polarity polarity);
/**
* Get polarity from string.
*
* @param[in] s The string to decode into a polarity.
*
* @return polarity corresponding to the string, or 0 on error.
*/
optional<Polarity> polarity_of_string(const std::string& s);
/**
* Get string representation of a NMEA Baud Rate.
*
* @param[in] rate The NNEABaudRate to get the string representation of.
*
* @return string representation of the NMEA baud rate, or "UNKNOWN".
*/
std::string to_string(NMEABaudRate rate);
/**
* Get nmea baud rate from string.
*
* @param[in] s The string to decode into a NMEA baud rate.
*
* @return nmea baud rate corresponding to the string, or 0 on error.
*/
optional<NMEABaudRate> nmea_baud_rate_of_string(const std::string& s);
/**
* Get string representation of an Azimuth Window.
*
* @param[in] azimuth_window The azimuth window to get the string
representation. of
*
* @return string representation of the azimuth window.
*/
std::string to_string(AzimuthWindow azimuth_window);
/**
* Get string representation of a lidar profile.
*
* @param[in] profile The profile to get the string representation of.
*
* @return string representation of the lidar profile.
*/
std::string to_string(UDPProfileLidar profile);
/**
* Get lidar profile from string.
*
* @param[in] s The string to decode into a lidar profile.
*
* @return lidar profile corresponding to the string, or nullopt on error.
*/
optional<UDPProfileLidar> udp_profile_lidar_of_string(const std::string& s);
/**
* Get string representation of an IMU profile.
*
* @param[in] profile The profile to get the string representation of.
*
* @return string representation of the lidar profile.
*/
std::string to_string(UDPProfileIMU profile);
/**
* Get imu profile from string
*
* @param[in] s The string to decode into an imu profile.
*
* @return imu profile corresponding to the string, or nullopt on error.
*/
optional<UDPProfileIMU> udp_profile_imu_of_string(const std::string& s);
/**
* Parse metadata text blob from the sensor into a sensor_info struct.
*
* String and vector fields will have size 0 if the parameter cannot
* be found or parsed, while lidar_mode will be set to 0 (invalid).
*
* @throw runtime_error if the text is not valid json
*
* @param[in] metadata a text blob returned by get_metadata from client.h.
*
* @return a sensor_info struct populated with a subset of the metadata.
*/
sensor_info parse_metadata(const std::string& metadata);
/**
* Parse metadata given path to a json file.
*
* @throw runtime_error if json file does not exist or is malformed.
*
* @param[in] json_file path to a json file containing sensor metadata.
*
* @return a sensor_info struct populated with a subset of the metadata.
*/
sensor_info metadata_from_json(const std::string& json_file);
/**
* Get a string representation of metadata. All fields included.
*
* @param[in] info sensor_info struct
*
* @return a json metadata string
*/
std::string to_string(const sensor_info& info);
/**
* Parse config text blob from the sensor into a sensor_config struct.
*
* All fields are optional, and will only be set if found.
*
* @throw runtime_error if the text is not valid json.
*
* @param[in] config a text blob given by get_config from client.h.
*
* @return a sensor_config struct populated with the sensor config.
* parameters.
*/
sensor_config parse_config(const std::string& config);
/**
* Get a string representation of sensor config. Only set fields will be
* represented.
*
* @param[in] config a struct of sensor config.
*
* @return a json sensor config string.
*/
std::string to_string(const sensor_config& config);
/**
* Convert non-legacy string representation of metadata to legacy.
*
* @param[in] metadata non-legacy string representation of metadata.
*
* @return legacy string representation of metadata.
*/
std::string convert_to_legacy(const std::string& metadata);
/**
* Get client version.
*
* @return client version string
*/
std::string client_version();
/** Tag to identitify a paricular value reported in the sensor channel data
* block. */
enum ChanField {
RANGE = 1, ///< 1st return range
RANGE2 = 2, ///< 2nd return range
INTENSITY = 3, ///< @deprecated (gcc 5.4 doesn't support annotations here)
SIGNAL = 3, ///< 1st return signal
SIGNAL2 = 4, ///< 2nd return signal
REFLECTIVITY = 5, ///< 1st return reflectivity
REFLECTIVITY2 = 6, ///< 2nd return reflectivity
AMBIENT = 7, //< @deprecated, use near_ir instead
NEAR_IR = 7, ///< near_ir
FLAGS = 8, ///< 1st return flags
FLAGS2 = 9, ///< 2nd return flags
RAW32_WORD1 = 60, ///< raw word access to packet for dev use
RAW32_WORD2 = 61, ///< raw word access to packet for dev use
RAW32_WORD3 = 62, ///< raw word access to packet for dev use
RAW32_WORD4 = 63, ///< raw word access to packet for dev use
CHAN_FIELD_MAX = 64, ///< max which allows us to introduce future fields
};
/**
* Get string representation of a channel field.
*
* @param[in] field The field to get the string representation of.
*
* @return string representation of the channel field.
*/
std::string to_string(ChanField field);
/**
* Types of channel fields.
*/
enum ChanFieldType { VOID = 0, UINT8, UINT16, UINT32, UINT64 };
/**
* Table of accessors for extracting data from imu and lidar packets.
*
* In the user guide, refer to section 9 for the lidar packet format and section
* 10 for imu packets.
*
* For 0 <= n < columns_per_packet, nth_col(n, packet_buf) returns a pointer to
* the nth measurement block. For 0 <= m < pixels_per_column, nth_px(m, col_buf)
* returns the mth channel data block.
*
* Use imu_la_{x,y,z} to access the acceleration in the corresponding
* direction. Use imu_av_{x,y,z} to read the angular velocity.
*/
class packet_format final {
packet_format(
const sensor_info& info); //< create packet_format from sensor_info
template <typename T>
T px_field(const uint8_t* px_buf, ChanField i) const;
struct Impl;
std::shared_ptr<const Impl> impl_;
std::vector<std::pair<sensor::ChanField, sensor::ChanFieldType>>
field_types_;
public:
using FieldIter =
decltype(field_types_)::const_iterator; ///< iterator over field types
///< of packet
const UDPProfileLidar
udp_profile_lidar; ///< udp lidar profile of packet format
const size_t lidar_packet_size; ///< lidar packet size
const size_t imu_packet_size; ///< imu packet size
const int columns_per_packet; ///< columns per lidar packet
const int pixels_per_column; ///< pixels per column for lidar
[[deprecated]] const int encoder_ticks_per_rev; ///< @deprecated
/**
* Read the packet type packet header.
*
* @param[in] lidar_buf the lidar buf.
*
* @return the packet type.
*/
uint16_t packet_type(const uint8_t* lidar_buf) const;
/**
* Read the frame_id packet header.
*
* @param[in] lidar_buf the lidar buf.
*
* @return the frame id.
*/
uint16_t frame_id(const uint8_t* lidar_buf) const;
/**
* Read the initialization id packet header.
*
* @param[in] lidar_buf the lidar buf.
*
* @return the init id.
*/
uint32_t init_id(const uint8_t* lidar_buf) const;
/**
* Read the packet serial number header.
*
* @param[in] lidar_buf the lidar buf.
*
* @return the serial number.
*/
uint64_t prod_sn(const uint8_t* lidar_buf) const;
/**
* Get the bit width of the specified channel field.
*
* @param[in] f the channel field to query.
*
* @return a type tag specifying the bitwidth of the requested field or
* ChannelFieldType::VOID if it is not supported by the packet format.
*/
ChanFieldType field_type(ChanField f) const;
/**
* A const forward iterator over field / type pairs.
*/
FieldIter begin() const;
/**
* A const forward iterator over field / type pairs.
*/
FieldIter end() const;
// Measurement block accessors
/**
* Get pointer to nth column of a lidar buffer.
*
* @param[in] n which column.
* @param[in] lidar_buf the lidar buffer.
*
* @return pointer to nth column of lidar buffer.
*/
const uint8_t* nth_col(int n, const uint8_t* lidar_buf) const;
/**
* Read column timestamp from column buffer.
*
* @param[in] col_buf the column buffer.
*
* @return column timestamp.
*/
uint64_t col_timestamp(const uint8_t* col_buf) const;
/**
* Read measurement id from column buffer.
*
* @param[in] col_buf the column buffer.
*
* @return column measurement id.
*/
uint16_t col_measurement_id(const uint8_t* col_buf) const;
/**
* Read column status from column buffer.
*
* @param[in] col_buf the column buffer.
*
* @return column status.
*/
uint32_t col_status(const uint8_t* col_buf) const;
[[deprecated]] uint32_t col_encoder(
const uint8_t* col_buf) const; ///< @deprecated
[[deprecated]] uint16_t col_frame_id(
const uint8_t* col_buf) const; ///< @deprecated
/**
* Copy the specified channel field out of a packet measurement block.
*
* @tparam T T should be an unsigned integer type large enough to store
* values of the specified field. Otherwise, data will be truncated.
*
* @param[in] col_buf a measurement block pointer returned by `nth_col()`.
* @param[in] f the channel field to copy.
* @param[out] dst destination array of size pixels_per_column * dst_stride.
* @param[in] dst_stride stride for writing to the destination array.
*/
template <typename T,
typename std::enable_if<std::is_unsigned<T>::value, T>::type = 0>
void col_field(const uint8_t* col_buf, ChanField f, T* dst,
int dst_stride = 1) const;
// Per-pixel channel data block accessors
/**
* Get pointer to nth pixel of a column buffer.
*
* @param[in] n which pixel.
* @param[in] col_buf the column buffer.
*
* @return pointer to nth pixel of a column buffer.
*/
const uint8_t* nth_px(int n, const uint8_t* col_buf) const;
/**
* Read range from pixel buffer.
*
* @param[in] px_buf the pixel buffer.
*
* @return range from pixel buffer.
*/
uint32_t px_range(const uint8_t* px_buf) const;
/**
* Read reflectivity from pixel buffer.
*
* @param[in] px_buf the pixel buffer.
*
* @return reflectivity from pixel buffer.
*/
uint16_t px_reflectivity(const uint8_t* px_buf) const;
/**
* Read signal from pixel buffer.
*
* @param[in] px_buf the pixel buffer.
*
* @return signal from pixel buffer.
*/
uint16_t px_signal(const uint8_t* px_buf) const;
// TODO switch to px_near_ir
/**
* Read ambient from pixel buffer.
*
* @param[in] px_buf the pixel buffer.
*
* @return ambient from pixel buffer.
*/
uint16_t px_ambient(const uint8_t* px_buf) const;
// IMU packet accessors
/**
* Read sys ts from imu packet buffer.
* @param[in] imu_buf the imu packet buffer.
*
* @return sys ts from imu pacet buffer.
*/
uint64_t imu_sys_ts(const uint8_t* imu_buf) const;
/**
* Read acceleration timestamp.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return acceleration ts from imu packet buffer.
*/
uint64_t imu_accel_ts(const uint8_t* imu_buf) const;
/**
* Read gyro timestamp.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return gyro ts from imu packet buffer.
*/
uint64_t imu_gyro_ts(const uint8_t* imu_buf) const;
/**
* Read acceleration in x.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return acceleration in x.
*/
float imu_la_x(const uint8_t* imu_buf) const;
/**
* Read acceleration in y.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return acceleration in y.
*/
float imu_la_y(const uint8_t* imu_buf) const;
/**
* Read acceleration in z.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return acceleration in z.
*/
float imu_la_z(const uint8_t* imu_buf) const;
/**
* Read angular velocity in x.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return angular velocity in x.
*/
float imu_av_x(const uint8_t* imu_buf) const;
/**
* Read angular velocity in y.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return angular velocity in y.
*/
float imu_av_y(const uint8_t* imu_buf) const;
/**
* Read angular velocity in z.
*
* @param[in] imu_buf the imu packet buffer.
*
* @return angular velocity in z.
*/
float imu_av_z(const uint8_t* imu_buf) const;
/** Declare get_format as friend. */
friend const packet_format& get_format(const sensor_info&);
};
/**
* Get a packet parser for a particular data format.
*
* @param[in] info parameters provided by the sensor.
*
* @return a packet_format suitable for parsing UDP packets sent by the sensor.
*/
const packet_format& get_format(const sensor_info& info);
} // namespace sensor
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_client/include/ouster/image_processing.h | <filename>ouster_client/include/ouster/image_processing.h<gh_stars>0
/**
* Copyright (c) 2018, Ouster, Inc.
* All rights reserved.
*
* @file
* @brief Utilities for post-processing image data
*/
#pragma once
#include <Eigen/Core>
#include "ouster/types.h"
namespace ouster {
namespace viz {
/** Adjusts brightness to between 0 and 1. */
class AutoExposure {
const double lo_percentile, hi_percentile; // percentiles used for scaling
const int ae_update_every;
double lo_state = -1.0;
double hi_state = -1.0;
double lo = -1.0;
double hi = -1.0;
bool initialized = false;
int counter = 0;
template <typename T>
void update(Eigen::Ref<img_t<T>> image, bool update_state);
public:
/** Default constructor using default percentile and update values. */
AutoExposure();
/**
* Constructor specifying update modulo, and using default percentiles.
*
* @param[in] update_every update every this number of frames.
*/
AutoExposure(int update_every);
/**
* Constructor specifying low and high percentiles, and update modulo.
*
* @param[in] lo_percentile low percentile to use for adjustment.
* @param[in] hi_percentile high percentile to use for adjustment.
* @param[in] update_every update every this number of frames.
*/
AutoExposure(double lo_percentile, double hi_percentile, int update_every);
/**
* Scales the image so that contrast is stretched between 0 and 1.
*
* The top percentile is 1 - hi_percentile and the bottom percentile is
* lo_percentile. Similar to linear 'contrast-stretch', i.e. normalization.
*
* @param[in] image Reference to the image, modified in place.
* @param[in] update_state Update lo/hi percentiles if true.
*/
void operator()(Eigen::Ref<img_t<float>> image, bool update_state = true);
/**
* Scales the image so that contrast is stretched between 0 and 1.
*
* The top percentile is 1 - hi_percentile and the bottom percentile is
* lo_percentile. Similar to linear 'contrast-stretch', i.e. normalization.
*
* @param[in] image Reference to the image, modified in place.
* @param[in] update_state Update lo/hi percentiles if true.
*/
void operator()(Eigen::Ref<img_t<double>> image, bool update_state = true);
};
/**
* Corrects beam uniformity by minimizing median difference between rows,
* thereby correcting subtle horizontal line artifacts in images, especially the
* ambient image.
*/
class BeamUniformityCorrector {
private:
int counter = 0;
Eigen::ArrayXd dark_count;
template <typename T>
void update(Eigen::Ref<img_t<T>> image, bool update_state);
public:
/**
* Applies dark count correction to an image, modifying it in-place to have
* reduced horizontal line artifacts.
*
* @param[in] image Reference to the image, modified in-place.
* @param[in] update_state Update dark counts if true.
*/
void operator()(Eigen::Ref<img_t<float>> image, bool update_state = true);
/**
* Applies dark count correction to an image, modifying it in-place to have
* reduced horizontal line artifacts.
*
* @param[in] image Reference to the image, modified in-place.
* @param[in] update_state Update dark counts if true.
*/
void operator()(Eigen::Ref<img_t<double>> image, bool update_state = true);
};
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_viz/src/camera.h | <filename>ouster_viz/src/camera.h
/**
* Copyright (c) 2021, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#include <Eigen/Core>
#include "ouster/point_viz.h"
namespace ouster {
namespace viz {
namespace impl {
inline double window_aspect(const WindowCtx& ctx) {
return ctx.viewport_width / static_cast<double>(ctx.viewport_height);
}
struct CameraData {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Eigen::Matrix4d proj;
Eigen::Matrix4d view;
Eigen::Matrix4d target;
};
} // namespace impl
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | examples/helpers.h | <gh_stars>0
/**
* Copyright (c) 2022, Ouster, Inc.
* All rights reserved.
*/
#include "ouster/lidar_scan.h"
#include "ouster/os_pcap.h"
#include "ouster/types.h"
// Fill scan with data from the 2nd scan in the pcap
// If there is no 2nd scan, scan will remain unchanged
void get_complete_scan(
std::shared_ptr<ouster::sensor_utils::playback_handle> handle,
ouster::LidarScan& scan, ouster::sensor::sensor_info& info);
|
UTS-CAS/ouster_example | ouster_viz/src/cloud.h | <filename>ouster_viz/src/cloud.h
/**
* Copyright (c) 2021, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#include <Eigen/Core>
#include "camera.h"
#include "glfw.h"
#include "ouster/point_viz.h"
namespace ouster {
namespace viz {
namespace impl {
/*
* Contains handles to variables in GLSL shader program compiled from
* point_vertex_shader_code and point_fragment_shader_code
*/
struct CloudIds;
/*
* Manages opengl state for drawing a point cloud
*/
class GLCloud {
// global gl state
static bool initialized;
static GLfloat program_id;
static CloudIds cloud_ids;
private:
// per-object gl state
GLuint xyz_buffer;
GLuint off_buffer;
GLuint range_buffer;
GLuint key_buffer;
GLuint mask_buffer;
GLuint trans_index_buffer;
GLuint transform_texture;
GLuint palette_texture;
GLfloat point_size;
Eigen::Matrix4d map_pose;
Eigen::Matrix4f extrinsic;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/*
* Set up the Cloud. Most of these arguments should correspond to CloudSetup
*/
GLCloud(const Cloud& cloud);
~GLCloud();
/*
* Render the point cloud with the point of view of the Camera
*/
void draw(const WindowCtx& ctx, const CameraData& camera, Cloud& cloud);
static void initialize();
static void uninitialize();
static void beginDraw();
static void endDraw();
};
} // namespace impl
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_viz/src/colormaps.h | /**
* Copyright (c) 2018, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#include <cstddef>
namespace ouster {
namespace viz {
inline float** genPalette(const int n, const float from[3], const float to[3]) {
float** palette = new float*[n];
for (int i = 0; i < n; i++) {
palette[i] = new float[3];
for (int j = 0; j < 3; j++) {
palette[i][j] = (to[j] * i + from[j] * (n - 1 - i)) / (n - 1);
}
}
return palette;
}
// generated from:
// https://daniel.lawrence.lu/public/colortransform/#0_2423_964_352_6_2624_1000_513_11_3248_1000_617_15_415_1000_774
const size_t spezia_n = 256;
const float spezia_palette[spezia_n][3] = {
{0.04890922165917825, 0.34265700288230266, 0.5139042200196196},
{0.04895672077739804, 0.34399228711079705, 0.5173325088859984},
{0.04899969158023907, 0.34532432182766976, 0.5207851330769154},
{0.049038068929181285, 0.34665300013643424, 0.5242624999557384},
{0.0490717860366443, 0.3479782119131098, 0.5277650273921529},
{0.04910077440233592, 0.34929984367863964, 0.5312931441090918},
{0.04912496374647964, 0.35061777846523556, 0.5348472900437968},
{0.049144281939685876, 0.35193189567631167, 0.5384279167237124},
{0.04915865492929047, 0.3532420709396423, 0.5420354876579142},
{0.04916800666192803, 0.3545481759533582, 0.5456704787448663},
{0.04917225900211732, 0.3558500783243678, 0.5493333786972924},
{0.04917133164659893, 0.35714764139876426, 0.553024689485032},
{0.0491651420341628, 0.35844072408375016, 0.5567449267967906},
{0.049153605250673076, 0.35972918066057785, 0.5604946205217287},
{0.04913663392897654, 0.36101286058797066, 0.5642743152519267},
{0.04911413814335756, 0.36229160829545354, 0.5680845708067875},
{0.04908602529819959, 0.36356526296598163, 0.5719259627805287},
{0.04905220001042406, 0.36483365830721187, 0.5757990831139734},
{0.04901256398533129, 0.36609662231071893, 0.5797045406919258},
{0.04896701588534969, 0.36735397699840217, 0.5836429619674972},
{0.04891545119124254, 0.36860553815528246, 0.5876149916148347},
{0.04885776205520153, 0.36985111504782353, 0.5916212932117864},
{0.048793837145294165, 0.371090510126853, 0.5956625499541581},
{0.048723561480604215, 0.37232351871408936, 0.5997394654032839},
{0.04864681625641982, 0.37354992867120285, 0.6038527642687842},
{0.0485634786587359, 0.37476952005026626, 0.6080031932284756},
{0.04847342166723854, 0.3759820647243526, 0.6121915217875443},
{0.04837651384597603, 0.37718732599695254, 0.6164185431792271},
{0.04827261912068898, 0.3783850581887729, 0.6206850753093874},
{0.04816159654185025, 0.37957500620037093, 0.6249919617475522},
{0.04804330003224206, 0.38075690504895116, 0.6293400727671268},
{0.047917578117875524, 0.3819304793775204, 0.633730306437712},
{0.04778427364089425, 0.38309544293445374, 0.6381635897726399},
{0.04764322345301101, 0.38425149802135766, 0.6426408799350484},
{0.04749425808786458, 0.385398334906948, 0.6471631655060938},
{0.04733720141054259, 0.3865356312044689, 0.6517314678190856},
{0.04717187024231324, 0.3876630512099673, 0.6563468423636755},
{0.046998073958454976, 0.38878024519851034, 0.6610103802644818},
{0.046815614056824016, 0.3898868486751851, 0.6657232098388559},
{0.04662428369457814, 0.3909824815774357, 0.6704864982388766},
{0.04642386719018477, 0.39206674742499825, 0.6753014531830023},
{0.04621413948754389, 0.39313923241335524, 0.6801693247832367},
{0.045994865578738504, 0.3941995044462622, 0.6850914074741193},
{0.04576579988147745, 0.39524711210249736, 0.6900690420503143},
{0.04552668556693947, 0.3962815835315315, 0.6951036178201221},
{0.04527725383318241, 0.39730242527232407, 0.7001965748827989},
{0.04501722311872807, 0.39830912098889804, 0.7053494065382041},
{0.04474629825033485, 0.39930113011574186, 0.7105636618379779},
{0.044464169518219306, 0.4002778864054065, 0.7158409482881979},
{0.044170511671191286, 0.4012387963699213, 0.7211829347142875},
{0.04386498282321687, 0.4021832376068135, 0.7265913542998228},
{0.04354722326188234, 0.4031105569995846, 0.7320680078119023},
{0.04321685414797862, 0.40402006878146585, 0.7376147670267773},
{0.0428734760940282, 0.40491105245010933, 0.743233578370643},
{0.042516667607970175, 0.40578275051957646, 0.748926466791789},
{0.04214598338630927, 0.4066343660945334, 0.7546955398817109},
{0.04176095243886018, 0.40746506024993384, 0.7605429922643745},
{0.04136107602475044, 0.40827394919762916, 0.766471110274553},
{0.04094582537627162, 0.4090601012192915, 0.7724822769480404},
{0.04051463918382638, 0.40982253334270374, 0.7785789773486957},
{0.040061502782456945, 0.4105602077358398, 0.7847638042595603},
{0.03959294089889664, 0.41127202779018696, 0.7910394642679004},
{0.039109793546916495, 0.4119568338613871, 0.7974087842769024},
{0.03861172210191932, 0.41261339863144436, 0.803874718479878},
{0.0380983735795864, 0.4132404220523802, 0.8104403558364525},
{0.03756937968562651, 0.4138365258262561, 0.8171089280940507},
{0.03702435578736771, 0.4144002473707861, 0.8238838184024792},
{0.0364628997996382, 0.4149300332132621, 0.8307685705742502},
{0.03588459097638143, 0.4154242317480496, 0.8377668990487521},
{0.035288988598694025, 0.4158810852842974, 0.844882699624589},
{0.03467563054866628, 0.4162987213006144, 0.8521200610312002},
{0.03404403175731731, 0.41667514281199364, 0.8594832774186676},
{0.033393682513460185, 0.41700821774098445, 0.8669768618532854},
{0.03272404661867004, 0.41729566716967786, 0.8746055609162682},
{0.032034559371859575, 0.4175350523310705, 0.8823743705140761},
{0.03132462536474723, 0.41772376017735885, 0.8902885530212784},
{0.03059361606719027, 0.417858987338036, 0.8983536558911435},
{0.029840867178669222, 0.41793772225168413, 0.9065755318852089},
{0.02906567571902483, 0.4179567252211435, 0.9149603610913213},
{0.028267296828018075, 0.41791250610119823, 0.9235146749206897},
{0.027444940239127507, 0.41780129927982523, 0.9322453822980893},
{0.026597766388240202, 0.4176190355565933, 0.9411597982868389},
{0.02572488211232861, 0.41736131045306674, 0.9502656754213602},
{0.02482533588680886, 0.41702334840740857, 0.9595712380560552},
{0.023898112542860842, 0.416599962205498, 0.9690852200808441},
{0.02294212739712791, 0.41608550687982504, 0.9788169064013666},
{0.02195621971619119, 0.4154738271597193, 0.9887761786374855},
{0.03533572637548167, 0.4150344767837667, 0.9966419438918287},
{0.08206748636661013, 0.4154760610454022, 0.996875442497312},
{0.1131664468320158, 0.4159292422424467, 0.9971067037505105},
{0.1377759789309851, 0.4163940123475041, 0.9973357493609963},
{0.1586260932452447, 0.4168703621191211, 0.9975626007042689},
{0.17695881259992585, 0.41735828111703227, 0.997787278826484},
{0.19346029551091778, 0.4178577577177723, 0.9980098044491156},
{0.2085556849234767, 0.4183687791306285, 0.9982301979735458},
{0.22252938052310162, 0.41889133141394447, 0.9984484794855942},
{0.2355824089832244, 0.4194253994917421, 0.9986646687599702},
{0.24786290560296725, 0.4199709671706614, 0.9988787852646682},
{0.25948364869956886, 0.42052801715720073, 0.9990908481652964},
{0.2705327829044692, 0.42109653107524325, 0.9993008763293371},
{0.2810807045979947, 0.4216764894838623, 0.9995088883303488},
{0.2911846624744039, 0.4222678718953844, 0.9997149024521047},
{0.30089193496804306, 0.4228706567937021, 0.9999189366926701},
{0.3199598560384707, 0.4211529467871777, 1.0000000000000044},
{0.3436114893370144, 0.4178742172053897, 1.0000000000000047},
{0.36539676089694495, 0.41458308629177515, 1.0000000000000044},
{0.3856661632570949, 0.41127775518053283, 1.0000000000000042},
{0.404675301565696, 0.407956362084171, 1.0000000000000044},
{0.4226172861700883, 0.4046169767859018, 1.0000000000000047},
{0.43964219386021874, 0.40125759469274436, 1.0000000000000047},
{0.45586938841351193, 0.3978761303980185, 1.0000000000000047},
{0.47139565849043324, 0.39447041069519134, 1.0000000000000047},
{0.4863007849418988, 0.3910381669772773, 1.0000000000000047},
{0.5006514638539757, 0.3875770269469873, 1.0000000000000044},
{0.5145041416968924, 0.3840845055522841, 1.0000000000000047},
{0.5279071095300848, 0.3805579950497078, 1.0000000000000047},
{0.5409020797263486, 0.3769947540834305, 1.0000000000000044},
{0.5535253932438766, 0.3733918956509583, 1.0000000000000044},
{0.5658089579546876, 0.3697463738064324, 1.0000000000000042},
{0.577780987780821, 0.366054968928604, 1.0000000000000049},
{0.589466591997403, 0.3623142713523205, 1.0000000000000047},
{0.6008882502481963, 0.35852066312849035, 1.0000000000000044},
{0.6120661992793963, 0.3546702976368881, 1.0000000000000047},
{0.6230187506929341, 0.35075907672718176, 1.0000000000000047},
{0.6337625542333337, 0.34678262500419443, 1.0000000000000047},
{0.6443128176539651, 0.3427362608011279, 1.0000000000000044},
{0.6546834916623888, 0.33861496329592544, 1.0000000000000047},
{0.664887426552217, 0.3344133351169368, 1.0000000000000044},
{0.6749365057066918, 0.3301255596489445, 1.0000000000000047},
{0.6848417600790246, 0.32574535208217403, 1.0000000000000047},
{0.6946134669261637, 0.32126590303548275, 1.0000000000000049},
{0.7042612354316643, 0.31667981331755896, 1.0000000000000047},
{0.7137940813531695, 0.3119790180493533, 1.0000000000000049},
{0.7232204924365964, 0.3071546979334297, 1.0000000000000049},
{0.7325484860275505, 0.30219717488892517, 1.0000000000000047},
{0.7417856600618409, 0.2970957885292609, 1.000000000000005},
{0.7509392384175178, 0.2918387489798506, 1.0000000000000047},
{0.760016111449703, 0.28641296022435003, 1.0000000000000047},
{0.7690228723986646, 0.2808038063993306, 1.0000000000000049},
{0.7779658502549104, 0.27499489103633235, 1.0000000000000049},
{0.7868511395774846, 0.2689677158905533, 1.0000000000000047},
{0.7956846276897148, 0.26270128126132847, 1.0000000000000047},
{0.804472019617065, 0.2561715829275765, 1.0000000000000047},
{0.8132188610824966, 0.2493509709254887, 1.0000000000000047},
{0.8219305598337341, 0.24220732066040862, 1.0000000000000049},
{0.8306124055427538, 0.23470294440057987, 1.0000000000000049},
{0.8392695884894237, 0.2267931361345682, 1.0000000000000047},
{0.847907217217596, 0.21842418639150069, 1.0000000000000047},
{0.8565303353323375, 0.20953060994411976, 1.0000000000000049},
{0.8651439375907393, 0.20003116767718654, 1.0000000000000049},
{0.8737529854254381, 0.18982297245453064, 1.0000000000000049},
{0.8823624220291222, 0.17877241522237444, 1.0000000000000047},
{0.8909771871196978, 0.1667005280966983, 1.0000000000000047},
{0.8996022314990386, 0.15335795616479617, 1.000000000000005},
{0.9082425315133318, 0.13837882372526109, 1.0000000000000049},
{0.9169031035195819, 0.12118667725012405, 1.0000000000000049},
{0.9255890184609986, 0.10077304980525353, 1.0000000000000047},
{0.9343054166534386, 0.07504334998300113, 1.0000000000000049},
{0.9430575228859241, 0.03781952178921804, 1.000000000000005},
{0.9509350420238839, 1.4218570765223148e-13, 0.9989984483716071},
{0.9554497353124459, 1.4191675612451605e-13, 0.9943640499109371},
{0.9599176427714787, 1.4433731987395504e-13, 0.9897799632511853},
{0.9643412154073002, 1.4245465917994694e-13, 0.9852425190239346},
{0.9687227616942858, 1.4191675612451605e-13, 0.9807481714229297},
{0.9730644583865243, 1.411995520506082e-13, 0.9762934885028384},
{0.9773683603724937, 1.3931689135660008e-13, 0.9718751430792824},
{0.9816364096714153, 1.3886863881040766e-13, 0.9674899041721569},
{0.9858704436584534, 1.4039269746746187e-13, 0.9631346289394122},
{0.9900722025959202, 1.4397871783700112e-13, 0.9588062550529955},
{0.9942433365389557, 1.4155815408756212e-13, 0.954501793472642},
{0.9983854116765075, 1.3752388117183045e-13, 0.9502183215767478},
{0.9999999999999819, 0.02804423714351181, 0.9437140548413381},
{0.9999999999999823, 0.0675265531658979, 0.9359017685954015},
{0.9999999999999826, 0.09447578037166751, 0.9282451825736049},
{0.9999999999999823, 0.11567880450339993, 0.920737795368809},
{0.9999999999999826, 0.13352190503381375, 0.9133734552831144},
{0.9999999999999823, 0.1491028314594674, 0.906146335428585},
{0.9999999999999826, 0.16303259275115084, 0.8990509109121838},
{0.9999999999999826, 0.17569199214531872, 0.8920819378992011},
{0.9999999999999826, 0.18733702217610845, 0.8852344343724449},
{0.9999999999999826, 0.19814940356609517, 0.8785036624245576},
{0.9999999999999823, 0.20826355122506324, 0.8718851119384158},
{0.9999999999999823, 0.21778214249596284, 0.8653744855260821},
{0.9999999999999826, 0.22678566871532468, 0.8589676846103573},
{0.9999999999999823, 0.2353385863611125, 0.8526607965450058},
{0.9999999999999828, 0.24349343831907827, 0.8464500826803465},
{0.9999999999999826, 0.2512937077092952, 0.840331967290248},
{0.9999999999999826, 0.2587758499993201, 0.8343030272849384},
{0.999999999999983, 0.26739099502162367, 0.8275538904243963},
{0.999999999999983, 0.2793555475103376, 0.8187524096848618},
{0.9999999999999828, 0.29067538241472596, 0.810154074771914},
{0.999999999999983, 0.3014349177286362, 0.8017491111724352},
{0.9999999999999826, 0.31170258039783083, 0.7935283442712853},
{0.9999999999999826, 0.3215347049761315, 0.7854831467895685},
{0.9999999999999826, 0.3309782925632311, 0.7776053911816436},
{0.9999999999999826, 0.3400730122474594, 0.7698874064041857},
{0.9999999999999826, 0.34885268450644075, 0.7623219385454285},
{0.999999999999983, 0.35734640143399626, 0.7549021148665397},
{0.9999999999999826, 0.3655793867737775, 0.7476214108616114},
{0.9999999999999826, 0.3735736659274856, 0.7404736199894286},
{0.9999999999999828, 0.381348594792351, 0.7334528257702123},
{0.9999999999999826, 0.38892128210540905, 0.7265533759748873},
{0.9999999999999823, 0.3963069303390571, 0.7197698586639263},
{0.9999999999999823, 0.4035191135203492, 0.7130970798581467},
{0.9999999999999823, 0.410570005644612, 0.7065300426455539},
{0.9999999999999821, 0.4174705699878856, 0.700063927546916},
{0.9999999999999819, 0.4242307171780247, 0.6936940739785828},
{0.9999999999999821, 0.4308594380852102, 0.6874159626644994},
{0.9999999999999821, 0.4373649162525338, 0.6812251988606219},
{0.9999999999999819, 0.44375462357781925, 0.6751174962642902},
{0.9999999999999819, 0.4500354021895003, 0.6690886614886871},
{0.9999999999999821, 0.45621353486890187, 0.6631345789884755},
{0.9999999999999817, 0.4622948059133914, 0.657251196327135},
{0.9999999999999817, 0.4682845539768576, 0.6514345096795133},
{0.9999999999999817, 0.474187718141824, 0.645680549464667},
{0.9999999999999817, 0.4800088782535285, 0.6399853660042518},
{0.9999999999999815, 0.4857522903672667, 0.6343450151004509},
{0.9999999999999815, 0.4914219180162633, 0.6287555434246979},
{0.9999999999999815, 0.497021459890778, 0.6232129736041581},
{0.9999999999999815, 0.5025543744242497, 0.6177132888869281},
{0.9999999999999815, 0.5080239017046412, 0.6122524172590773},
{0.999999999999981, 0.5134330830652836, 0.606826214876734},
{0.9999999999999808, 0.518784778656747, 0.6014304486641499},
{0.9999999999999808, 0.5240816832574693, 0.5960607779137368},
{0.9999999999999806, 0.5293263405443853, 0.5907127347060119},
{0.9999999999999806, 0.5345211560142691, 0.5853817029456958},
{0.9999999999999808, 0.5396684087209026, 0.580062895784249},
{0.9999999999999808, 0.5447702619716198, 0.5747513311680923},
{0.9999999999999806, 0.5498287731085955, 0.5694418052146554},
{0.9999999999999803, 0.5548459024848833, 0.5641288630740176},
{0.9999999999999801, 0.5598235217321937, 0.5588067668806895},
{0.9999999999999799, 0.5647634214064047, 0.5534694603362047},
{0.9999999999999799, 0.569667318087479, 0.5481105293861371},
{0.9999999999999801, 0.5745368610026079, 0.5427231583620321},
{0.9999999999999797, 0.5793736382348097, 0.5373000808456486},
{0.9999999999999797, 0.5841791825736894, 0.5318335243749407},
{0.9999999999999797, 0.58895497706055, 0.5263151479421893},
{0.9999999999999795, 0.5937024602763533, 0.5207359710263567},
{0.9999999999999795, 0.5984230314181602, 0.5150862926436902},
{0.9999999999999792, 0.6031180552074987, 0.5093555985787912},
{0.9999999999999792, 0.607788866672662, 0.5035324545546109},
{0.999999999999979, 0.6124367758461117, 0.4976043825895365},
{0.999999999999979, 0.6170630724180334, 0.4915577171399405},
{0.9999999999999788, 0.6216690303876014, 0.48537743679248463},
{0.9999999999999788, 0.6262559127547657, 0.4790469661903673},
{0.9999999999999784, 0.6308249762973255, 0.4725479414659382},
{0.9999999999999786, 0.6353774764808859, 0.46585993058805514},
{0.9999999999999784, 0.6399146725529954, 0.45896009754439654},
{0.9999999999999784, 0.644437832877538, 0.45182279591800384},
{0.9999999999999781, 0.6489482405714118, 0.4444190728188997},
{0.9999999999999779, 0.6534471995128909, 0.4367160577509657},
{0.9999999999999779, 0.6579360408000906, 0.4286762020035964},
{0.9999999999999779, 0.6624161297489367, 0.42025632127341656},
{0.9999999999999777, 0.6668888735333959, 0.41140637540952824},
{0.9999999999999777, 0.6713557295869282, 0.40206789113388525},
{0.9999999999999775, 0.6758182149038043, 0.3921718908087272}};
const size_t calref_n = 256;
const float calref_palette[calref_n][3] = {
{0.1, 0.1, 0.1},
{0.36862745098039246, 0.30980392156862746, 0.6352941176470588},
{0.3618608227604765, 0.31856978085351784, 0.6394463667820068},
{0.3550941945405613, 0.3273356401384083, 0.643598615916955},
{0.3483275663206459, 0.3361014994232987, 0.647750865051903},
{0.3415609381007305, 0.3448673587081891, 0.6519031141868512},
{0.33479430988081516, 0.35363321799307956, 0.6560553633217993},
{0.3280276816608997, 0.36239907727796994, 0.6602076124567474},
{0.3212610534409842, 0.3711649365628603, 0.6643598615916955},
{0.31449442522106885, 0.3799307958477509, 0.6685121107266436},
{0.3077277970011534, 0.38869665513264134, 0.6726643598615917},
{0.300961168781238, 0.3974625144175317, 0.6768166089965398},
{0.29419454056132255, 0.4062283737024219, 0.6809688581314879},
{0.2874279123414072, 0.4149942329873126, 0.685121107266436},
{0.2806612841214917, 0.4237600922722031, 0.6892733564013841},
{0.27389465590157624, 0.4325259515570933, 0.6934256055363321},
{0.2671280276816609, 0.4412918108419839, 0.6975778546712803},
{0.2603613994617455, 0.45005767012687425, 0.7017301038062282},
{0.25359477124183005, 0.4588235294117643, 0.7058823529411765},
{0.24682814302191458, 0.46758938869665506, 0.7100346020761246},
{0.24006151480199922, 0.4763552479815456, 0.7141868512110727},
{0.23329488658208386, 0.485121107266436, 0.7183391003460207},
{0.2265282583621684, 0.49388696655132636, 0.7224913494809689},
{0.21976163014225292, 0.5026528258362168, 0.726643598615917},
{0.21299500192233756, 0.5114186851211073, 0.7307958477508651},
{0.20622837370242209, 0.5201845444059976, 0.7349480968858132},
{0.19946174548250672, 0.5289504036908883, 0.7391003460207612},
{0.20007689350249913, 0.5377931564782777, 0.7393310265282583},
{0.2080738177623992, 0.5467128027681663, 0.7356401384083046},
{0.21607074202229903, 0.5556324490580544, 0.7319492502883508},
{0.2240676662821992, 0.5645520953479432, 0.7282583621683968},
{0.23206459054209927, 0.5734717416378313, 0.7245674740484429},
{0.24006151480199933, 0.58239138792772, 0.720876585928489},
{0.2480584390618994, 0.5913110342176088, 0.7171856978085351},
{0.25605536332179935, 0.6002306805074966, 0.7134948096885814},
{0.2640522875816994, 0.6091503267973857, 0.7098039215686275},
{0.27204921184159947, 0.6180699730872741, 0.7061130334486736},
{0.28004613610149953, 0.6269896193771626, 0.7024221453287197},
{0.2880430603613995, 0.6359092656670511, 0.6987312572087658},
{0.29603998462129966, 0.6448289119569397, 0.695040369088812},
{0.3040369088811996, 0.6537485582468282, 0.6913494809688581},
{0.3120338331410998, 0.6626682045367166, 0.6876585928489042},
{0.32003075740099973, 0.671587850826605, 0.6839677047289503},
{0.3280276816608998, 0.6805074971164937, 0.6802768166089965},
{0.33602460592079986, 0.6894271434063821, 0.6765859284890426},
{0.3440215301806999, 0.6983467896962707, 0.6728950403690888},
{0.35201845444059976, 0.7072664359861591, 0.6692041522491351},
{0.36001537870050004, 0.7161860822760477, 0.6655132641291811},
{0.3680123029604, 0.7251057285659362, 0.6618223760092272},
{0.37600922722029995, 0.7340253748558248, 0.6581314878892734},
{0.3840061514802, 0.7429450211457131, 0.6544405997693193},
{0.39200307574010007, 0.7518646674356018, 0.6507497116493657},
{0.40000000000000036, 0.7607843137254902, 0.6470588235294117},
{0.4106113033448675, 0.7649365628604383, 0.6469050365244137},
{0.42122260668973477, 0.7690888119953864, 0.6467512495194156},
{0.43183391003460214, 0.7732410611303345, 0.6465974625144175},
{0.4424452133794696, 0.7773933102652826, 0.6464436755094196},
{0.4530565167243371, 0.7815455594002306, 0.6462898885044215},
{0.46366782006920415, 0.7856978085351789, 0.6461361014994234},
{0.4742791234140715, 0.7898500576701271, 0.6459823144944252},
{0.4848904267589389, 0.794002306805075, 0.6458285274894271},
{0.49550173010380627, 0.7981545559400232, 0.645674740484429},
{0.5061130334486739, 0.8023068050749711, 0.6455209534794312},
{0.5167243367935411, 0.8064590542099194, 0.645367166474433},
{0.5273356401384084, 0.8106113033448674, 0.6452133794694349},
{0.5379469434832758, 0.8147635524798154, 0.6450595924644369},
{0.548558246828143, 0.8189158016147636, 0.6449058054594388},
{0.5591695501730105, 0.8230680507497117, 0.6447520184544406},
{0.5697808535178779, 0.8272202998846598, 0.6445982314494427},
{0.5803921568627453, 0.831372549019608, 0.6444444444444446},
{0.5910034602076126, 0.8355247981545562, 0.6442906574394465},
{0.60161476355248, 0.8396770472895041, 0.6441368704344483},
{0.6122260668973473, 0.8438292964244521, 0.6439830834294502},
{0.6228373702422147, 0.8479815455594002, 0.6438292964244523},
{0.633448673587082, 0.8521337946943485, 0.6436755094194541},
{0.6440599769319493, 0.8562860438292964, 0.6435217224144562},
{0.6546712802768165, 0.8604382929642447, 0.6433679354094579},
{0.6652825836216838, 0.8645905420991928, 0.6432141484044598},
{0.675124951941561, 0.8685121107266438, 0.6422145328719724},
{0.6841983852364476, 0.8722029988465975, 0.6403690888119954},
{0.6932718185313342, 0.8758938869665513, 0.6385236447520186},
{0.7023452518262208, 0.8795847750865051, 0.6366782006920415},
{0.7114186851211074, 0.8832756632064591, 0.6348327566320646},
{0.7204921184159938, 0.8869665513264131, 0.6329873125720877},
{0.7295655517108806, 0.890657439446367, 0.6311418685121105},
{0.7386389850057672, 0.8943483275663208, 0.6292964244521339},
{0.7477124183006536, 0.8980392156862746, 0.6274509803921569},
{0.7567858515955403, 0.9017301038062284, 0.62560553633218},
{0.7658592848904268, 0.9054209919261822, 0.6237600922722031},
{0.7749327181853134, 0.909111880046136, 0.6219146482122262},
{0.7840061514802001, 0.9128027681660901, 0.6200692041522492},
{0.7930795847750867, 0.916493656286044, 0.618223760092272},
{0.8021530180699734, 0.920184544405998, 0.6163783160322951},
{0.8112264513648599, 0.9238754325259518, 0.6145328719723183},
{0.8202998846597466, 0.9275663206459055, 0.6126874279123413},
{0.8293733179546331, 0.9312572087658594, 0.6108419838523645},
{0.8384467512495197, 0.9349480968858133, 0.6089965397923875},
{0.8475201845444063, 0.9386389850057671, 0.6071510957324106},
{0.8565936178392928, 0.9423298731257211, 0.6053056516724337},
{0.8656670511341793, 0.9460207612456747, 0.6034602076124568},
{0.874740484429066, 0.9497116493656288, 0.6016147635524798},
{0.8838139177239525, 0.9534025374855826, 0.5997693194925027},
{0.8928873510188393, 0.9570934256055367, 0.5979238754325257},
{0.9019607843137256, 0.9607843137254903, 0.5960784313725491},
{0.9058054594386773, 0.962322183775471, 0.6020761245674742},
{0.9096501345636295, 0.9638600538254517, 0.6080738177623993},
{0.9134948096885813, 0.9653979238754326, 0.6140715109573244},
{0.9173394848135333, 0.9669357939254133, 0.6200692041522493},
{0.9211841599384853, 0.9684736639753941, 0.6260668973471741},
{0.9250288350634372, 0.9700115340253751, 0.6320645905420991},
{0.9288735101883892, 0.9715494040753557, 0.6380622837370243},
{0.932718185313341, 0.9730872741253366, 0.6440599769319492},
{0.9365628604382931, 0.9746251441753172, 0.6500576701268744},
{0.9404075355632451, 0.9761630142252982, 0.6560553633217994},
{0.9442522106881969, 0.9777008842752788, 0.6620530565167244},
{0.9480968858131487, 0.9792387543252595, 0.6680507497116493},
{0.9519415609381008, 0.9807766243752404, 0.6740484429065746},
{0.9557862360630527, 0.9823144944252212, 0.6800461361014994},
{0.9596309111880046, 0.9838523644752019, 0.6860438292964245},
{0.9634755863129567, 0.9853902345251826, 0.6920415224913494},
{0.9673202614379086, 0.9869281045751634, 0.6980392156862747},
{0.9711649365628605, 0.9884659746251442, 0.7040369088811996},
{0.9750096116878124, 0.9900038446751249, 0.7100346020761246},
{0.9788542868127644, 0.9915417147251058, 0.7160322952710494},
{0.9826989619377164, 0.9930795847750866, 0.7220299884659747},
{0.9865436370626683, 0.9946174548250674, 0.7280276816608996},
{0.9903883121876201, 0.9961553248750481, 0.7340253748558248},
{0.9942329873125721, 0.9976931949250287, 0.7400230680507498},
{0.9980776624375239, 0.9992310649750095, 0.746020761245675},
{0.9999231064975008, 0.9976163014225297, 0.7450211457131873},
{0.9997693194925027, 0.9928489042675892, 0.7370242214532873},
{0.9996155324875048, 0.988081507112649, 0.729027297193387},
{0.9994617454825068, 0.9833141099577085, 0.7210303729334873},
{0.9993079584775085, 0.9785467128027682, 0.7130334486735873},
{0.9991541714725107, 0.9737793156478278, 0.7050365244136869},
{0.9990003844675125, 0.9690119184928874, 0.697039600153787},
{0.9988465974625144, 0.9642445213379468, 0.6890426758938869},
{0.9986928104575163, 0.9594771241830067, 0.681045751633987},
{0.9985390234525182, 0.9547097270280661, 0.6730488273740869},
{0.9983852364475202, 0.9499423298731258, 0.6650519031141869},
{0.9982314494425222, 0.9451749327181854, 0.6570549788542868},
{0.998077662437524, 0.9404075355632449, 0.6490580545943867},
{0.9979238754325258, 0.9356401384083044, 0.6410611303344868},
{0.9977700884275279, 0.930872741253364, 0.6330642060745867},
{0.9976163014225298, 0.9261053440984237, 0.6250672818146866},
{0.9974625144175316, 0.9213379469434833, 0.6170703575547868},
{0.9973087274125335, 0.9165705497885427, 0.6090734332948867},
{0.9971549404075356, 0.9118031526336023, 0.6010765090349864},
{0.9970011534025374, 0.907035755478662, 0.5930795847750865},
{0.9968473663975395, 0.9022683583237218, 0.5850826605151866},
{0.9966935793925413, 0.8975009611687812, 0.5770857362552864},
{0.9965397923875433, 0.892733564013841, 0.5690888119953864},
{0.9963860053825454, 0.8879661668589005, 0.5610918877354861},
{0.9962322183775473, 0.88319876970396, 0.5530949634755861},
{0.996078431372549, 0.8784313725490196, 0.5450980392156861},
{0.9959246443675508, 0.8707420222991156, 0.538638985005767},
{0.9957708573625528, 0.8630526720492118, 0.5321799307958477},
{0.9956170703575548, 0.855363321799308, 0.5257208765859284},
{0.9954632833525567, 0.847673971549404, 0.519261822376009},
{0.9953094963475586, 0.8399846212995001, 0.5128027681660898},
{0.9951557093425605, 0.8322952710495963, 0.5063437139561706},
{0.9950019223375625, 0.8246059207996924, 0.4998846597462513},
{0.9948481353325646, 0.8169165705497885, 0.4934256055363321},
{0.9946943483275664, 0.8092272202998847, 0.48696655132641264},
{0.9945405613225683, 0.8015378700499808, 0.48050749711649365},
{0.9943867743175702, 0.7938485198000771, 0.47404844290657466},
{0.9942329873125721, 0.7861591695501731, 0.4675893886966551},
{0.994079200307574, 0.7784698193002692, 0.4611303344867359},
{0.993925413302576, 0.7707804690503652, 0.4546712802768166},
{0.9937716262975778, 0.7630911188004613, 0.4482122260668975},
{0.99361783929258, 0.7554017685505575, 0.44175317185697793},
{0.9934640522875816, 0.7477124183006536, 0.43529411764705894},
{0.9933102652825835, 0.7400230680507496, 0.4288350634371395},
{0.9931564782775857, 0.7323337178008458, 0.4223760092272202},
{0.9930026912725872, 0.724644367550942, 0.4159169550173013},
{0.9928489042675894, 0.716955017301038, 0.40945790080738176},
{0.9926951172625912, 0.7092656670511341, 0.40299884659746266},
{0.9925413302575933, 0.7015763168012303, 0.3965397923875432},
{0.9923875432525952, 0.6938869665513263, 0.390080738177624},
{0.992233756247597, 0.6861976163014225, 0.3836216839677048},
{0.9914648212226067, 0.677354863514033, 0.3780853517877738},
{0.990080738177624, 0.6673587081891583, 0.3734717416378317},
{0.9886966551326414, 0.6573625528642829, 0.36885813148788904},
{0.9873125720876587, 0.647366397539408, 0.36424452133794694},
{0.985928489042676, 0.6373702422145329, 0.3596309111880045},
{0.9845444059976933, 0.6273740868896578, 0.35501730103806217},
{0.9831603229527106, 0.6173779315647828, 0.35040369088811985},
{0.981776239907728, 0.6073817762399077, 0.3457900807381774},
{0.9803921568627451, 0.5973856209150328, 0.3411764705882355},
{0.9790080738177624, 0.5873894655901575, 0.33656286043829287},
{0.9776239907727798, 0.5773933102652827, 0.33194925028835065},
{0.976239907727797, 0.5673971549404075, 0.3273356401384082},
{0.9748558246828143, 0.5574009996155325, 0.3227220299884661},
{0.9734717416378316, 0.5474048442906574, 0.3181084198385238},
{0.9720876585928488, 0.5374086889657824, 0.31349480968858146},
{0.9707035755478661, 0.5274125336409075, 0.30888119953863913},
{0.9693194925028835, 0.5174163783160323, 0.3042675893886967},
{0.9679354094579009, 0.5074202229911575, 0.2996539792387545},
{0.9665513264129182, 0.4974240676662822, 0.2950403690888119},
{0.9651672433679354, 0.4874279123414072, 0.2904267589388697},
{0.9637831603229527, 0.47743175701653207, 0.2858131487889273},
{0.9623990772779699, 0.4674356016916571, 0.28119953863898506},
{0.9610149942329872, 0.4574394463667821, 0.27658592848904273},
{0.9596309111880046, 0.447443291041907, 0.2719723183391005},
{0.958246828143022, 0.43744713571703187, 0.2673587081891581},
{0.9568627450980394, 0.42745098039215673, 0.26274509803921564},
{0.9520953479430986, 0.42022299115724726, 0.26459054209919286},
{0.9473279507881583, 0.4129950019223377, 0.26643598615916975},
{0.9425605536332179, 0.40576701268742793, 0.26828143021914663},
{0.9377931564782777, 0.39853902345251835, 0.2701268742791235},
{0.9330257593233372, 0.3913110342176086, 0.2719723183391004},
{0.928258362168397, 0.38408304498269874, 0.27381776239907707},
{0.9234909650134564, 0.3768550557477892, 0.2756632064590543},
{0.9187235678585162, 0.36962706651287985, 0.2775086505190312},
{0.9139561707035755, 0.36239907727797027, 0.2793540945790083},
{0.9091887735486351, 0.3551710880430604, 0.28119953863898506},
{0.9044213763936948, 0.34794309880815055, 0.28304498269896183},
{0.8996539792387543, 0.340715109573241, 0.28489042675893894},
{0.8948865820838141, 0.3334871203383314, 0.28673587081891583},
{0.8901191849288733, 0.326259131103422, 0.28858131487889305},
{0.8853517877739333, 0.319031141868512, 0.2904267589388695},
{0.8805843906189926, 0.3118031526336025, 0.2922722029988466},
{0.8758169934640523, 0.30457516339869284, 0.2941176470588236},
{0.871049596309112, 0.2973471741637831, 0.2959630911188005},
{0.8662821991541714, 0.29011918492887356, 0.2978085351787776},
{0.8615148019992313, 0.2828911956939638, 0.2996539792387542},
{0.8567474048442908, 0.2756632064590542, 0.30149942329873114},
{0.8519800076893502, 0.26843521722414465, 0.3033448673587078},
{0.84721261053441, 0.2612072279892348, 0.3051903114186846},
{0.8424452133794698, 0.2539792387543254, 0.3070357554786618},
{0.8376778162245291, 0.24675124951941552, 0.3088811995386387},
{0.8310649750096116, 0.23844675124951953, 0.30880430603613984},
{0.8226066897347173, 0.22906574394463686, 0.3068050749711647},
{0.8141484044598231, 0.21968473663975407, 0.30480584390618953},
{0.8056901191849288, 0.2103037293348713, 0.30280661284121513},
{0.7972318339100345, 0.20092272202998862, 0.30080738177624006},
{0.7887735486351404, 0.19154171472510573, 0.2988081507112643},
{0.7803152633602461, 0.18216070742022294, 0.2968089196462894},
{0.7718569780853518, 0.17277970011534027, 0.2948096885813144},
{0.7633986928104576, 0.1633986928104575, 0.29281045751633983},
{0.7549404075355632, 0.15401768550557482, 0.29081122645136503},
{0.746482122260669, 0.14463667820069204, 0.2888119953863893},
{0.7380238369857748, 0.13525567089580925, 0.2868127643214149},
{0.7295655517108804, 0.12587466359092658, 0.2848135332564399},
{0.7211072664359862, 0.1164936562860438, 0.28281430219146436},
{0.7126489811610921, 0.10711264898116135, 0.2808150711264894},
{0.7041906958861976, 0.09773164167627835, 0.2788158400615146},
{0.6957324106113034, 0.08835063437139556, 0.27681660899653987},
{0.6872741253364091, 0.07896962706651289, 0.2748173779315646},
{0.6788158400615149, 0.06958861976163011, 0.27281814686658995},
{0.6703575547866205, 0.06020761245674744, 0.2708189158016141},
{0.6618992695117263, 0.05082660515186466, 0.26881968473663936},
{0.6534409842368321, 0.041445597846981874, 0.2668204536716644},
{0.6449826989619377, 0.0320645905420992, 0.26482122260668983},
{0.6365244136870435, 0.02268358323721642, 0.2628219915417146},
{0.6280661284121491, 0.013302575932333749, 0.26082276047673913}};
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_viz/include/ouster/point_viz.h | /**
* Copyright (c) 2020, Ouster, Inc.
* All rights reserved.
*
* @file
* @brief Point cloud and image visualizer for Ouster Lidar using OpenGL
*/
#pragma once
#include <array>
#include <cstddef>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace ouster {
namespace viz {
/**
* @todo document me
*/
using mat4d = std::array<double, 16>;
/**
* @todo document me
*/
constexpr mat4d identity4d = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
using vec4f = std::array<float, 4>;
using vec3d = std::array<double, 3>;
// TODO: messes up lidar_scan_viz
namespace impl {
class GLCloud;
class GLImage;
class GLCuboid;
class GLLabel;
class GLRings;
struct CameraData;
} // namespace impl
struct WindowCtx;
class Camera;
class Cloud;
class Image;
class Cuboid;
class Label;
class TargetDisplay;
/**
* @todo document me
*/
constexpr int default_window_width = 800;
/**
* @todo document me
*/
constexpr int default_window_height = 600;
/**
* @brief A basic visualizer for sensor data
*
* Displays a set of point clouds, images, cuboids, and text labels with a few
* options for coloring and handling input.
*
* All operations are thread safe when running rendering (run() or run_once())
* in a separate thread. This is the intended way to use the visualizer library
* when a nontrivial amount of processing needs to run concurrently with
* rendering (e.g. when streaming data from a running sensor).
*/
class PointViz {
public:
struct Impl;
/**
* Creates a window and initializes the rendering context
*
* @param[in] name name of the visualizer, shown in the title bar
* @param[in] fix_aspect @todo document me
* @param[in] window_width @todo document me
* @param[in] window_height @todo document me
*/
PointViz(const std::string& name, bool fix_aspect = false,
int window_width = default_window_width,
int window_height = default_window_height);
/**
* Tears down the rendering context and closes the viz window
*/
~PointViz();
/**
* Main drawing loop, keeps drawing things until running(false)
*
* Should be called from the main thread for macos compatibility
*/
void run();
/**
* Run one iteration of the main loop for rendering and input handling
*
* Should be called from the main thread for macos compatibility
*/
void run_once();
/**
* Check if the run() has been signaled to exit
*
* @return true if the run() loop is currently executing
*/
bool running();
/**
* Set the running flag. Will signal run() to exit
*
* @param[in] state new value of the flag
*/
void running(bool state);
/**
* Show or hide the visualizer window
*
* @param[in] state true to show
*/
void visible(bool state);
/**
* Update visualization state
*
* Send state updates to be rendered on the next frame
*
* @return whether state was successfully sent. If not, will be sent on next
* call to update(). This can happen if update() is called more
* frequently than the frame rate.
*/
bool update();
/**
* Add a callback for handling keyboard input
*
* @param[in] f the callback. The second argument is the ascii value of the
* key pressed. Third argument is a bitmask of the modifier keys
*/
void push_key_handler(std::function<bool(const WindowCtx&, int, int)>&& f);
/**
* Add a callback for handling mouse button input
*
* @param[in] f @todo document me
*/
void push_mouse_button_handler(
std::function<bool(const WindowCtx&, int, int)>&& f);
/**
* Add a callback for handling mouse scrolling input
*
* @param[in] f @todo document me
*/
void push_scroll_handler(
std::function<bool(const WindowCtx&, double, double)>&& f);
/**
* Add a callback for handling mouse movement
*
* @param[in] f @todo document me
*/
void push_mouse_pos_handler(
std::function<bool(const WindowCtx&, double, double)>&& f);
/**
* Remove the last added callback for handling keyboard input
*/
void pop_key_handler();
/**
* @copydoc pop_key_handler()
*/
void pop_mouse_button_handler();
/**
* @copydoc pop_key_handler()
*/
void pop_scroll_handler();
/**
* @copydoc pop_key_handler()
*/
void pop_mouse_pos_handler();
/**
* Get a reference to the camera controls
*
* @return @todo document me
*/
Camera& camera();
/**
* Get a reference to the target display controls
*
* @return @todo document me
*/
TargetDisplay& target_display();
/**
* Add an object to the scene
*
* @param[in] cloud @todo document me
*/
void add(const std::shared_ptr<Cloud>& cloud);
/**
* Add an object to the scene
*
* @param[in] image @todo document me
*/
void add(const std::shared_ptr<Image>& image);
/**
* Add an object to the scene
*
* @param[in] cuboid @todo document me
*/
void add(const std::shared_ptr<Cuboid>& cuboid);
/**
* Add an object to the scene
*
* @param[in] label @todo document me
*/
void add(const std::shared_ptr<Label>& label);
/**
* Remove an object from the scene
*
* @param[in] cloud @todo document me
*/
bool remove(const std::shared_ptr<Cloud>& cloud);
/**
* Remove an object from the scene
*
* @param[in] image @todo document me
*/
bool remove(const std::shared_ptr<Image>& image);
/**
* Remove an object from the scene
*
* @param[in] cuboid @todo document me
*/
bool remove(const std::shared_ptr<Cuboid>& cuboid);
/**
* Remove an object from the scene
*
* @param[in] label @todo document me
*/
bool remove(const std::shared_ptr<Label>& label);
private:
std::unique_ptr<Impl> pimpl;
void draw();
};
/**
* Add default keyboard and mouse bindings to a visualizer instance
*
* Controls will modify the camera from the thread that calls run() or
* run_once(), which will require synchronization when using multiple threads.
*
* @param[in] viz the visualizer instance
* @param[in] mx mutex to lock while modifying camera
*/
void add_default_controls(viz::PointViz& viz, std::mutex* mx = nullptr);
/**
* @brief Context for input callbacks.
*/
struct WindowCtx {
bool lbutton_down{false}; ///< True if the left mouse button is held
bool mbutton_down{false}; ///< True if the middle mouse button is held
double mouse_x{0}; ///< Current mouse x position
double mouse_y{0}; ///< Current mouse y position
int viewport_width{0}; ///< Current viewport width in pixels
int viewport_height{0}; ///< Current viewport height in pixels
};
/**
* @brief Controls the camera view and projection.
*/
class Camera {
/* view parameters */
mat4d target_;
vec3d view_offset_;
int yaw_; // decidegrees
int pitch_;
int log_distance_; // 0 means 50m
/* projection parameters */
bool orthographic_;
int fov_;
double proj_offset_x_, proj_offset_y_;
double view_distance() const;
public:
/**
* @todo document me
*/
Camera();
/**
* Calculate camera matrices.
*
* @param[in] aspect aspect ratio of the viewport
*
* @return projection, view matrices and target location.
*/
impl::CameraData matrices(double aspect) const;
/**
* Reset the camera view and fov.
*/
void reset();
/**
* Orbit the camera left or right about the camera target.
*
* @param[in] degrees offset to the current yaw angle
*/
void yaw(float degrees);
/**
* Pitch the camera up or down.
*
* @param[in] degrees offset to the current pitch angle
*/
void pitch(float degrees);
/**
* Move the camera towards or away from the target.
*
* @param[in] amount offset to the current camera distance from the target
*/
void dolly(int amount);
/**
* Move the camera in the XY plane of the camera view.
*
* Coordinates are normalized so that 1 is the length of the diagonal of the
* view plane at the target. This is useful for implementing controls that
* work intuitively regardless of the camera distance.
*
* @param[in] x horizontal offset
* @param[in] y vertical offset
*/
void dolly_xy(double x, double y);
/**
* Set the diagonal field of view.
*
* @param[in] degrees the diagonal field of view, in degrees
*/
void set_fov(float degrees);
/**
* Use an orthographic or perspective projection.
*
* @param[in] state true for orthographic, false for perspective
*/
void set_orthographic(bool state);
/**
* Set the 2d position of camera target in the viewport.
*
* @param[in] x horizontal position in in normalized coordinates [-1, 1]
* @param[in] y vertical position in in normalized coordinates [-1, 1]
*/
void set_proj_offset(float x, float y);
};
/**
* @brief Manages the state of the camera target display.
*/
class TargetDisplay {
int ring_size_{1};
bool rings_enabled_{false};
public:
/**
* Enable or disable distance ring display.
*
* @param[in] state true to display rings
*/
void enable_rings(bool state);
/**
* Set the distance between rings.
*
* @param[in] n space between rings will be 10^n meters
*/
void set_ring_size(int n);
friend class impl::GLRings;
};
/**
* @brief Manages the state of a point cloud.
*
* Each point cloud consists of n points with w poses. The ith point will be
* transformed by the (i % w)th pose. For example for 2048 x 64 Ouster lidar
* point cloud, we may have w = 2048 poses and n = 2048 * 64 = 131072 points.
*
* We also keep track of a per-cloud pose to efficiently transform the
* whole point cloud without having to update all ~2048 poses.
*/
class Cloud {
size_t n_{0};
size_t w_{0};
mat4d extrinsic_{};
bool range_changed_{false};
bool key_changed_{false};
bool mask_changed_{false};
bool xyz_changed_{false};
bool offset_changed_{false};
bool transform_changed_{false};
bool palette_changed_{false};
bool pose_changed_{false};
bool point_size_changed_{false};
std::vector<float> range_data_{};
std::vector<float> key_data_{};
std::vector<float> mask_data_{};
std::vector<float> xyz_data_{};
std::vector<float> off_data_{};
std::vector<float> transform_data_{};
std::vector<float> palette_data_{};
mat4d pose_{};
float point_size_{2};
Cloud(size_t w, size_t h, const mat4d& extrinsic);
public:
/**
* Unstructured point cloud for visualization.
*
* Call set_xyz() to update
*
* @param[in] n number of points
* @param[in] extrinsic sensor extrinsic calibration. 4x4 column-major
* homogeneous transformation matrix
*/
Cloud(size_t n, const mat4d& extrinsic = identity4d);
/**
* Structured point cloud for visualization.
*
* Call set_range() to update
*
* @param[in] w number of columns
* @param[in] h number of pixels per column
* @param[in] dir unit vectors for projection
* @param[in] off offsets for xyz projection
* @param[in] extrinsic sensor extrinsic calibration. 4x4 column-major
* homogeneous transformation matrix
*/
Cloud(size_t w, size_t h, const float* dir, const float* off,
const mat4d& extrinsic = identity4d);
/**
* Clear dirty flags.
*
* Resets any changes since the last call to PointViz::update()
*/
void clear();
/**
* Get the size of the point cloud.
*
* @return @todo document me
*/
size_t get_size() { return n_; }
/**
* Set the range values.
*
* @param[in] range pointer to array of at least as many elements as there
* are points, representing the range of the points
*/
void set_range(const uint32_t* range);
/**
* Set the key values, used for colouring.
*
* @param[in] key pointer to array of at least as many elements as there are
* points, preferably normalized between 0 and 1
*/
void set_key(const float* key);
/**
* Set the RGBA mask values, used as an overlay on top of the key.
*
* @param[in] mask pointer to array of at least 4x as many elements as there
* are points, preferably normalized between 0 and 1
*/
void set_mask(const float* mask);
/**
* Set the XYZ values.
*
* @param[in] xyz pointer to array of exactly 3n where n is number of
* points, so that the xyz position of the ith point is i, i + n, i + 2n
*/
void set_xyz(const float* xyz);
/**
* Set the offset values.
*
* TODO: no real reason to have this. Set in constructor, if at all
*
* @param[in] offset pointer to array of exactly 3n where n is number of
* points, so that the xyz position of the ith point is i, i + n, i + 2n
*/
void set_offset(const float* offset);
/**
* Set the ith point cloud pose.
*
* @param[in] pose 4x4 column-major homogeneous transformation matrix
*/
void set_pose(const mat4d& pose);
/**
* Set point size.
*
* @param[in] size point size
*/
void set_point_size(float size);
/**
* Set the per-column poses, so that the point corresponding to the
* pixel at row u, column v in the staggered lidar scan is transformed
* by the vth pose, given as a homogeneous transformation matrix.
*
* @param[in] rotation array of rotation matrices, total size 9 * w, where
* the vth rotation matrix is: r[v], r[w + v], r[2 * w + v], r[3 * w + v],
* r[4 * w + v], r[5 * w + v], r[6 * w + v], r[7 * w + v], r[8 * w + v]
* @param[in] translation translation vector array, column major, where each
* row is a translation vector. That is, the vth translation is t[v], t[w +
* v], t[2 * w + v]
*/
void set_column_poses(const float* rotation, const float* translation);
/**
* Set the point cloud color palette.
*
* @param[in] palette the new palette to use, must have size 3*palette_size
* @param[in] palette_size the number of colors in the new palette
*/
void set_palette(const float* palette, size_t palette_size);
friend class impl::GLCloud;
};
/**
* @brief Manages the state of an image.
*/
class Image {
bool position_changed_{false};
bool image_changed_{false};
bool mask_changed_{false};
vec4f position_{};
size_t image_width_{0};
size_t image_height_{0};
std::vector<float> image_data_{};
size_t mask_width_{0};
size_t mask_height_{0};
std::vector<float> mask_data_{};
float hshift_{0}; // in normalized screen coordinates [-1. 1]
public:
/**
* @todo document me
*/
Image();
/**
* Clear dirty flags.
*
* Resets any changes since the last call to PointViz::update()
*/
void clear();
/**
* Set the image data.
*
* @param[in] width width of the image data in pixels
* @param[in] height height of the image data in pixels
* @param[in] image_data pointer to an array of width * height elements
* interpreted as a row-major monochrome image
*/
void set_image(size_t width, size_t height, const float* image_data);
/**
* Set the RGBA mask.
*
* Not required to be the same resolution as the image data
*
* @param[in] width width of the image data in pixels
* @param[in] height height of the image data in pixels
* @param[in] mask_data pointer to array of 4 * width * height elements
* interpreted as a row-major rgba image
*/
void set_mask(size_t width, size_t height, const float* mask_data);
/**
* Set the display position of the image.
*
* TODO: this is super weird. Coordinates are {x_min, x_max, y_max, y_min}
* in sort-of normalized screen coordinates: y is in [-1, 1], and x uses the
* same scale (i.e. window width is ignored). This is currently just the
* same method the previous hard-coded 'image_frac' logic was using; I
* believe it was done this way to allow scaling with the window while
* maintaining the aspect ratio.
*
* @param[in] x_min
* @param[in] x_max
* @param[in] y_min
* @param[in] y_max
*/
void set_position(float x_min, float x_max, float y_min, float y_max);
/**
* Set horizontal shift in normalized viewport screen width coordinate.
*
* This may be used to "snap" images to the left/right screen edges.
*
* Some example values:
* 0 - default, image is centered horizontally on the screen
* -0.5 - image moved to the left for the 1/4 of a horizontal viewport
* -1 - image moved to the left for the 1/2 of a horizontal viewport
* +1 - image moved to the right for the 1/2 of a horizontal viewport
* +0.5 - image moved to the right for the 1/4 of a horizontal viewport
*
* @param[in] hshift shift in normalized by width coordinates from 0 at
* the center [-1.0..1.0]
*
*/
void set_hshift(float hshift);
friend class impl::GLImage;
};
/**
* @brief Manages the state of a single cuboid.
*/
class Cuboid {
bool transform_changed_{false};
bool rgba_changed_{false};
mat4d transform_{};
vec4f rgba_{};
public:
/**
* @todo document me
*/
Cuboid(const mat4d& transform, const vec4f& rgba);
/**
* Clear dirty flags.
*
* Resets any changes since the last call to PointViz::update()
*/
void clear();
/**
* Set the transform defining the cuboid.
*
* Applied to a unit cube centered at the origin.
*
* @param[in] pose @todo document me
*/
void set_transform(const mat4d& pose);
/**
* Set the color of the cuboid.
*
* @param rgba @todo document me
*/
void set_rgba(const vec4f& rgba);
friend class impl::GLCuboid;
};
/**
* @brief Manages the state of a text label.
*/
class Label {
bool pos_changed_{false};
bool scale_changed_{true};
bool text_changed_{false};
bool is_3d_{false};
bool align_right_{false};
bool align_top_{false};
bool rgba_changed_{true};
vec3d position_{};
float scale_{1.0};
std::string text_{};
vec4f rgba_{1.0, 1.0, 1.0, 1.0};
public:
/**
* @todo document me
*/
Label(const std::string& text, const vec3d& position);
/**
* @todo document me
*/
Label(const std::string& text, float x, float y, bool align_right = false,
bool align_top = false);
/**
* Clear dirty flags.
*
* Resets any changes since the last call to PointViz::update()
*/
void clear();
/**
* Update label text.
*
* @param[in] text new text to display
*/
void set_text(const std::string& text);
/**
* Set label position.
*
* @param[in] position 3d position of the label
*/
void set_position(const vec3d& position);
/**
* Set position of the 2D label.
*
* @param[in] x horizontal position [0, 1]
* @param[in] y vertical position [0, 1]
* @param[in] align_right interpret position as right of the label
* @param[in] align_top interpret position as top of the label
*/
void set_position(float x, float y, bool align_right = false,
bool align_top = false);
/**
* Set scaling factor of the label.
*
* @param[in] scale text scaling factor
*/
void set_scale(float scale);
/**
* Set the color of the label.
*
* @param[in] rgba color in RGBA format
*/
void set_rgba(const vec4f& rgba);
friend class impl::GLLabel;
};
/**
* @todo document me
*/
extern const size_t spezia_n;
/**
* @todo document me
*/
extern const float spezia_palette[][3];
/**
* @todo document me
*/
extern const size_t calref_n;
/**
* @todo document me
*/
extern const float calref_palette[][3];
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_viz/src/common.h | /**
* Copyright (c) 2021, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#include <atomic>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "glfw.h"
namespace ouster {
namespace viz {
namespace impl {
/**
* load and compile GLSL shaders
*
* @param vertex_shader_code code of vertex shader
* @param fragment_shader_code code of fragment shader
* @return handle to program_id
*/
inline GLuint load_shaders(const std::string& vertex_shader_code,
const std::string& fragment_shader_code) {
// Adapted from WTFPL-licensed code:
// https://github.com/opengl-tutorials/ogl/blob/2.1_branch/common/shader.cpp
// Create the shaders
GLuint vertex_shader_id = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER);
GLint result = GL_FALSE;
int info_log_length;
// Compile Vertex Shader
char const* vertex_source_pointer = vertex_shader_code.c_str();
glShaderSource(vertex_shader_id, 1, &vertex_source_pointer, NULL);
glCompileShader(vertex_shader_id);
// Check Vertex Shader
glGetShaderiv(vertex_shader_id, GL_COMPILE_STATUS, &result);
glGetShaderiv(vertex_shader_id, GL_INFO_LOG_LENGTH, &info_log_length);
if (info_log_length > 0) {
std::vector<char> vertex_shader_error_message(info_log_length + 1);
glGetShaderInfoLog(vertex_shader_id, info_log_length, NULL,
&vertex_shader_error_message[0]);
printf("%s\n", &vertex_shader_error_message[0]);
}
// Compile Fragment Shader
char const* fragment_source_pointer = fragment_shader_code.c_str();
glShaderSource(fragment_shader_id, 1, &fragment_source_pointer, NULL);
glCompileShader(fragment_shader_id);
// Check Fragment Shader
glGetShaderiv(fragment_shader_id, GL_COMPILE_STATUS, &result);
glGetShaderiv(fragment_shader_id, GL_INFO_LOG_LENGTH, &info_log_length);
if (info_log_length > 0) {
std::vector<char> fragment_shader_error_message(info_log_length + 1);
glGetShaderInfoLog(fragment_shader_id, info_log_length, NULL,
&fragment_shader_error_message[0]);
printf("%s\n", &fragment_shader_error_message[0]);
}
// Link the program
GLuint program_id = glCreateProgram();
glAttachShader(program_id, vertex_shader_id);
glAttachShader(program_id, fragment_shader_id);
glLinkProgram(program_id);
// Check the program
glGetProgramiv(program_id, GL_LINK_STATUS, &result);
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_log_length);
if (info_log_length > 0) {
std::vector<char> program_error_message(info_log_length + 1);
glGetProgramInfoLog(program_id, info_log_length, NULL,
&program_error_message[0]);
printf("%s\n", &program_error_message[0]);
}
glDetachShader(program_id, vertex_shader_id);
glDetachShader(program_id, fragment_shader_id);
glDeleteShader(vertex_shader_id);
glDeleteShader(fragment_shader_id);
return program_id;
}
/**
* load a texture from an array of GLfloat or equivalent
* such as float[n][3]
*
* @param texture array of at least size width * height * elements_per_texel
* where elements per texel is 3 for GL_RGB and 1 for GL_RED
* @param width width of texture in texels
* @param height height of texture in texels
* @param texture_id handle generated by glGenTextures
* @param internal_format internal format, e.g. GL_RGB or GL_RGB32F
* @param format format, e.g. GL_RGB or GL_RED
*/
template <class F>
void load_texture(const F& texture, const size_t width, const size_t height,
const GLuint texture_id,
const GLenum internal_format = GL_RGB,
const GLenum format = GL_RGB) {
glBindTexture(GL_TEXTURE_2D, texture_id);
// we have only 1 level, so we override base/max levels
// https://www.khronos.org/opengl/wiki/Common_Mistakes#Creating_a_complete_texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format,
GL_FLOAT, texture);
}
/**
* The point vertex shader supports transforming the point cloud by an array of
* transformations.
*
* @param xyz XYZ point before it was multiplied by range.
* Corresponds to the "xyzlut" used by LidarScan.
*
* @param range Range of each point.
*
* @param key Key for colouring each point for aesthetic reasons.
*
* @param trans_index Index of which of the transformations to use for this
* point. Normalized between 0 and 1. (0 being the first
* 1 being the last).
*
* @param model Extrinsic calibration of the lidar.
*
* @param transformation The w transformations are stored as a w x 4 texture.
* Each column of the texture corresponds one 4 x 4
* transformation matrix, where the four pixels' rgb
* values correspond to four columns (3 rotation 1
* translation)
*
* @param proj_view Camera view matrix controlled by the visualizer.
*/
static const std::string point_vertex_shader_code =
R"SHADER(
#version 330 core
in vec3 xyz;
in vec3 offset;
in float range;
in float key;
in vec4 mask;
in float trans_index;
uniform sampler2D transformation;
uniform mat4 model;
uniform mat4 proj_view;
out float vcolor;
out vec4 overlay_rgba;
void main(){
vec4 local_point = range > 0
? model * vec4(xyz * range + offset, 1.0)
: vec4(0, 0, 0, 1.0);
// Here, we get the four columns of the transformation.
// Since this version of GLSL doesn't have texel fetch,
// we use texture2D instead. Numbers are chosen to index
// the middle of each pixel.
// | r0 | r1 | r2 | t |
// 0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
vec4 r0 = texture(transformation, vec2(trans_index, 0.125));
vec4 r1 = texture(transformation, vec2(trans_index, 0.375));
vec4 r2 = texture(transformation, vec2(trans_index, 0.625));
vec4 t = texture(transformation, vec2(trans_index, 0.875));
mat4 car_pose = mat4(
r0.x, r0.y, r0.z, 0,
r1.x, r1.y, r1.z, 0,
r2.x, r2.y, r2.z, 0,
t.x, t.y, t.z, 1
);
gl_Position = proj_view * car_pose * local_point;
vcolor = sqrt(key);
overlay_rgba = mask;
})SHADER";
static const std::string point_fragment_shader_code =
R"SHADER(
#version 330 core
in float vcolor;
in vec4 overlay_rgba;
uniform sampler2D palette;
out vec4 color;
void main() {
color = vec4(texture(palette, vec2(vcolor, 1)).xyz * (1.0 - overlay_rgba.w)
+ overlay_rgba.xyz * overlay_rgba.w, 1);
})SHADER";
static const std::string ring_vertex_shader_code =
R"SHADER(
#version 330 core
in vec3 ring_xyz;
uniform float ring_range;
uniform mat4 proj_view;
void main(){
gl_Position = proj_view * vec4(ring_xyz * ring_range, 1.0);
gl_Position.z = gl_Position.w;
})SHADER";
static const std::string ring_fragment_shader_code =
R"SHADER(
#version 330 core
out vec4 color;
void main() {
color = vec4(0.15, 0.15, 0.15, 1);
})SHADER";
static const std::string cuboid_vertex_shader_code =
R"SHADER(
#version 330 core
in vec3 cuboid_xyz;
uniform vec4 cuboid_rgba;
uniform mat4 proj_view;
out vec4 rgba;
void main(){
gl_Position = proj_view * vec4(cuboid_xyz, 1.0);
rgba = cuboid_rgba;
})SHADER";
static const std::string cuboid_fragment_shader_code =
R"SHADER(
#version 330 core
in vec4 rgba;
out vec4 color;
void main() {
color = rgba;
})SHADER";
static const std::string image_vertex_shader_code =
R"SHADER(
#version 330 core
in vec2 vertex;
in vec2 vertex_uv;
out vec2 uv;
void main() {
gl_Position = vec4(vertex, 0, 1);
uv = vertex_uv;
})SHADER";
static const std::string image_fragment_shader_code =
R"SHADER(
#version 330 core
in vec2 uv;
uniform sampler2D image;
uniform sampler2D mask;
out vec4 color;
void main() {
vec4 m = texture(mask, uv);
float a = m.a;
float r = sqrt(texture(image, uv).r) * (1.0 - a);
color = vec4(vec3(r, r, r) + m.rgb * a, 1.0);
})SHADER";
} // namespace impl
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_client/include/ouster/impl/lidar_scan_impl.h | <reponame>UTS-CAS/ouster_example<gh_stars>0
/**
* Copyright (c) 2021, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#include <Eigen/Core>
#include <cstdint>
#include <stdexcept>
#include "ouster/lidar_scan.h"
#include "ouster/types.h"
namespace ouster {
namespace impl {
using sensor::ChanFieldType;
template <typename T>
struct FieldTag;
template <>
struct FieldTag<uint8_t> {
static constexpr ChanFieldType tag = ChanFieldType::UINT8;
};
template <>
struct FieldTag<uint16_t> {
static constexpr ChanFieldType tag = ChanFieldType::UINT16;
};
template <>
struct FieldTag<uint32_t> {
static constexpr ChanFieldType tag = ChanFieldType::UINT32;
};
template <>
struct FieldTag<uint64_t> {
static constexpr ChanFieldType tag = ChanFieldType::UINT64;
};
/*
* Tagged union for LidarScan fields
*/
struct FieldSlot {
ChanFieldType tag;
union {
img_t<uint8_t> f8;
img_t<uint16_t> f16;
img_t<uint32_t> f32;
img_t<uint64_t> f64;
};
FieldSlot(ChanFieldType t, size_t w, size_t h) : tag{t} {
switch (t) {
case ChanFieldType::VOID:
break;
case ChanFieldType::UINT8:
new (&f8) img_t<uint8_t>{h, w};
f8.setZero();
break;
case ChanFieldType::UINT16:
new (&f16) img_t<uint16_t>{h, w};
f16.setZero();
break;
case ChanFieldType::UINT32:
new (&f32) img_t<uint32_t>{h, w};
f32.setZero();
break;
case ChanFieldType::UINT64:
new (&f64) img_t<uint64_t>{h, w};
f64.setZero();
break;
}
}
FieldSlot() : FieldSlot{ChanFieldType::VOID, 0, 0} {};
~FieldSlot() { clear(); }
FieldSlot(const FieldSlot& other) {
switch (other.tag) {
case ChanFieldType::VOID:
break;
case ChanFieldType::UINT8:
new (&f8) img_t<uint8_t>{other.f8};
break;
case ChanFieldType::UINT16:
new (&f16) img_t<uint16_t>{other.f16};
break;
case ChanFieldType::UINT32:
new (&f32) img_t<uint32_t>{other.f32};
break;
case ChanFieldType::UINT64:
new (&f64) img_t<uint64_t>{other.f64};
break;
}
tag = other.tag;
}
FieldSlot(FieldSlot&& other) { set_from(other); }
FieldSlot& operator=(FieldSlot other) {
clear();
set_from(other);
return *this;
}
template <typename T>
Eigen::Ref<img_t<T>> get() {
if (tag == FieldTag<T>::tag)
return get_unsafe<T>();
else
throw std::invalid_argument("Accessed field at wrong type");
}
template <typename T>
Eigen::Ref<const img_t<T>> get() const {
if (tag == FieldTag<T>::tag)
return get_unsafe<T>();
else
throw std::invalid_argument("Accessed field at wrong type");
}
friend bool operator==(const FieldSlot& l, const FieldSlot& r) {
if (l.tag != r.tag) return false;
switch (l.tag) {
case ChanFieldType::VOID:
return true;
case ChanFieldType::UINT8:
return (l.f8 == r.f8).all();
case ChanFieldType::UINT16:
return (l.f16 == r.f16).all();
case ChanFieldType::UINT32:
return (l.f32 == r.f32).all();
case ChanFieldType::UINT64:
return (l.f64 == r.f64).all();
default:
assert(false);
}
// unreachable, appease older gcc
return false;
}
private:
void set_from(FieldSlot& other) {
switch (other.tag) {
case ChanFieldType::VOID:
break;
case ChanFieldType::UINT8:
new (&f8) img_t<uint8_t>{std::move(other.f8)};
break;
case ChanFieldType::UINT16:
new (&f16) img_t<uint16_t>{std::move(other.f16)};
break;
case ChanFieldType::UINT32:
new (&f32) img_t<uint32_t>{std::move(other.f32)};
break;
case ChanFieldType::UINT64:
new (&f64) img_t<uint64_t>{std::move(other.f64)};
break;
}
tag = other.tag;
other.clear();
}
void clear() {
switch (tag) {
case ChanFieldType::VOID:
break;
case ChanFieldType::UINT8:
f8.~img_t<uint8_t>();
break;
case ChanFieldType::UINT16:
f16.~img_t<uint16_t>();
break;
case ChanFieldType::UINT32:
f32.~img_t<uint32_t>();
break;
case ChanFieldType::UINT64:
f64.~img_t<uint64_t>();
break;
}
tag = ChanFieldType::VOID;
}
template <typename T>
Eigen::Ref<img_t<T>> get_unsafe();
template <typename T>
Eigen::Ref<const img_t<T>> get_unsafe() const;
};
template <>
inline Eigen::Ref<img_t<uint8_t>> FieldSlot::get_unsafe() {
return f8;
}
template <>
inline Eigen::Ref<img_t<uint16_t>> FieldSlot::get_unsafe() {
return f16;
}
template <>
inline Eigen::Ref<img_t<uint32_t>> FieldSlot::get_unsafe() {
return f32;
}
template <>
inline Eigen::Ref<img_t<uint64_t>> FieldSlot::get_unsafe() {
return f64;
}
template <>
inline Eigen::Ref<const img_t<uint8_t>> FieldSlot::get_unsafe() const {
return f8;
}
template <>
inline Eigen::Ref<const img_t<uint16_t>> FieldSlot::get_unsafe() const {
return f16;
}
template <>
inline Eigen::Ref<const img_t<uint32_t>> FieldSlot::get_unsafe() const {
return f32;
}
template <>
inline Eigen::Ref<const img_t<uint64_t>> FieldSlot::get_unsafe() const {
return f64;
}
/*
* Call a generic operation op<T>(f, Args..) with the type parameter T having
* the correct (dynamic) field type for the LidarScan channel field f
* Example code for the operation<T>:
* \code
* struct print_field_size {
* template <typename T>
* void operator()(Eigen::Ref<img_t<T>> field) {
* std::cout << "Rows: " + field.rows() << std::endl;
* std::cout << "Cols: " + field.cols() << std::endl;
* }
* };
* \endcode
*/
template <typename SCAN, typename OP, typename... Args>
void visit_field(SCAN&& ls, sensor::ChanField f, OP&& op, Args&&... args) {
switch (ls.field_type(f)) {
case sensor::ChanFieldType::UINT8:
op.template operator()(ls.template field<uint8_t>(f),
std::forward<Args>(args)...);
break;
case sensor::ChanFieldType::UINT16:
op.template operator()(ls.template field<uint16_t>(f),
std::forward<Args>(args)...);
break;
case sensor::ChanFieldType::UINT32:
op.template operator()(ls.template field<uint32_t>(f),
std::forward<Args>(args)...);
break;
case sensor::ChanFieldType::UINT64:
op.template operator()(ls.template field<uint64_t>(f),
std::forward<Args>(args)...);
break;
default:
throw std::invalid_argument("Invalid field for LidarScan");
}
}
/*
* Call a generic operation op<T>(f, Args...) for each field of the lidar scan
* with type parameter T having the correct field type
*/
template <typename SCAN, typename OP, typename... Args>
void foreach_field(SCAN&& ls, OP&& op, Args&&... args) {
for (const auto& ft : ls)
visit_field(std::forward<SCAN>(ls), ft.first, std::forward<OP>(op),
ft.first, std::forward<Args>(args)...);
}
} // namespace impl
template <typename T>
inline img_t<T> destagger(const Eigen::Ref<const img_t<T>>& img,
const std::vector<int>& pixel_shift_by_row,
bool inverse) {
const size_t h = img.rows();
const size_t w = img.cols();
if (pixel_shift_by_row.size() != h)
throw std::invalid_argument{"image height does not match shifts size"};
img_t<T> destaggered{h, w};
for (size_t u = 0; u < h; u++) {
const std::ptrdiff_t offset =
((inverse ? -1 : 1) * pixel_shift_by_row[u] + w) % w;
destaggered.row(u).segment(offset, w - offset) =
img.row(u).segment(0, w - offset);
destaggered.row(u).segment(0, offset) =
img.row(u).segment(w - offset, offset);
}
return destaggered;
}
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_client/include/ouster/version.h | /**
* Copyright (c) 2018, Ouster, Inc.
* All rights reserved.
*
* @file
* @brief Simple version struct
*/
#include <cstdint>
#include <string>
#pragma once
namespace ouster {
namespace util {
struct version {
uint16_t major; ///< Major version number
uint16_t minor; ///< Minor version number
uint16_t patch; ///< Patch(or revision) version number
};
const version invalid_version = {0, 0, 0};
/** \defgroup ouster_client_version_operators Ouster Client version.h Operators
* @{
*/
/**
* Equality operation for version structs.
*
* @param[in] u The first version to compare.
* @param[in] v The second version to compare.
*
* @return If the versions are the same.
*/
inline bool operator==(const version& u, const version& v) {
return u.major == v.major && u.minor == v.minor && u.patch == v.patch;
}
/**
* Less than operation for version structs.
*
* @param[in] u The first version to compare.
* @param[in] v The second version to compare.
*
* @return If the first version is less than the second version.
*/
inline bool operator<(const version& u, const version& v) {
return (u.major < v.major) || (u.major == v.major && u.minor < v.minor) ||
(u.major == v.major && u.minor == v.minor && u.patch < v.patch);
}
/**
* Less than or equal to operation for version structs.
*
* @param[in] u The first version to compare.
* @param[in] v The second version to compare.
*
* @return If the first version is less than or equal to the second version.
*/
inline bool operator<=(const version& u, const version& v) {
return u < v || u == v;
}
/**
* In-equality operation for version structs.
*
* @param[in] u The first version to compare.
* @param[in] v The second version to compare.
*
* @return If the versions are not the same.
*/
inline bool operator!=(const version& u, const version& v) { return !(u == v); }
/**
* Greater than or equal to operation for version structs.
*
* @param[in] u The first version to compare.
* @param[in] v The second version to compare.
*
* @return If the first version is greater than or equal to the second version.
*/
inline bool operator>=(const version& u, const version& v) { return !(u < v); }
/**
* Greater than operation for version structs.
*
* @param[in] u The first version to compare.
* @param[in] v The second version to compare.
*
* @return If the first version is greater than the second version.
*/
inline bool operator>(const version& u, const version& v) { return !(u <= v); }
/** @}*/
/**
* Get string representation of a version.
*
* @param[in] v version.
*
* @return string representation of the version.
*/
std::string to_string(const version& v);
/**
* Get version from string.
*
* @param[in] s string.
*
* @return version corresponding to the string, or invalid_version on error.
*/
version version_of_string(const std::string& s);
} // namespace util
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_viz/src/image.h | /**
* Copyright (c) 2021, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#include <array>
#include "camera.h"
#include "glfw.h"
#include "ouster/point_viz.h"
namespace ouster {
namespace viz {
namespace impl {
/*
* Manages opengl state for drawing a point cloud
*
* The image is auto-scaled to be positioned either at the top (for wide images)
* or the left (for tall images)
*/
class GLImage {
constexpr static int size_fraction_max = 20;
// global gl state
static bool initialized;
static GLuint program_id;
static GLuint vertex_id;
static GLuint uv_id;
static GLuint image_id;
static GLuint mask_id;
// per-image gl state
std::array<GLuint, 2> vertexbuffers;
GLuint image_texture_id{0};
GLuint mask_texture_id{0};
GLuint image_index_id{0};
float x0{-1}, x1{0}, y0{0}, y1{-1}, hshift{0};
public:
GLImage();
GLImage(const Image& image);
~GLImage();
/*
* Render the monochrome image.
*
* Modifies the camera to offset it so that it is centered on the region not
* covered by image.
*/
void draw(const WindowCtx& ctx, const CameraData& camera, Image& image);
static void initialize();
static void uninitialize();
static void beginDraw();
static void endDraw();
};
} // namespace impl
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_viz/src/glfw.h | /**
* Copyright (c) 2022, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#ifdef OUSTER_VIZ_GLEW
#include <GL/glew.h>
#else
#include <glad/glad.h>
#endif
#include <GLFW/glfw3.h>
#include <functional>
#include <string>
#include "ouster/point_viz.h"
namespace ouster {
namespace viz {
struct GLFWContext {
explicit GLFWContext(const std::string& name, bool fix_aspect,
int window_width, int window_height);
// manages glfw window pointer lifetime
GLFWContext(const GLFWContext&) = delete;
GLFWContext& operator=(const GLFWContext&) = delete;
// pointer used for glfw callback context; can't move
GLFWContext(GLFWContext&&) = delete;
GLFWContext& operator=(GLFWContext&&) = delete;
~GLFWContext();
// tear down global glfw context
static void terminate();
// manipulate glfwWindowShouldClose flag
bool running();
void running(bool);
void visible(bool);
GLFWwindow* window;
// state set by GLFW callbacks
WindowCtx window_context;
std::function<void(const WindowCtx&, int, int)> key_handler;
std::function<void(const WindowCtx&, int, int)> mouse_button_handler;
std::function<void(const WindowCtx&, double, double)> scroll_handler;
std::function<void(const WindowCtx&, double, double)> mouse_pos_handler;
std::function<void()> resize_handler;
};
} // namespace viz
} // namespace ouster
|
UTS-CAS/ouster_example | ouster_viz/src/gltext.h | // Repository: https://github.com/vallentin/glText
// License: https://github.com/vallentin/glText/blob/master/LICENSE.md
//
// Date Created: September 24, 2013
// Last Modified: December, 2022
//
// Modified from the original for use in ouster_viz:
// - inline api functions to avoid unused warnings
// - hacked to always initialize on gltInit
// In one C or C++ file, define GLT_IMPLEMENTATION prior to inclusion to create
// the implementation.
// #define GLT_IMPLEMENTATION
// #include "gltext.h"
// Copyright (c) 2013-2018 <NAME>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
// Refrain from using any exposed macros, functions
// or structs prefixed with an underscore. As these
// are only intended for internal purposes. Which
// additionally means they can be removed, renamed
// or changed between minor updates without notice.
#ifndef GL_TEXT_H
#define GL_TEXT_H
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(__gl_h_) && !defined(__glcorearb_h_)
#error OpenGL header must be included prior to including glText header
#endif
#include <stdint.h> /* uint8_t, uint16_t, uint32_t, uint64_t */
#include <stdlib.h> /* malloc(), calloc(), free() */
#include <string.h> /* memset(), memcpy(), strlen() */
#if (defined(_DEBUG) || defined(DEBUG)) && !defined(GLT_DEBUG)
#define GLT_DEBUG 1
#endif
#ifdef GLT_DEBUG
#include <assert.h> /* assert() */
#define _GLT_ASSERT(expression) assert(expression)
#else
#define _GLT_ASSERT(expression)
#endif
#ifdef GLT_DEBUG_PRINT
#include <stdio.h> /* printf */
#endif
#define _GLT_STRINGIFY(str) #str
#define _GLT_STRINGIFY_TOKEN(str) _GLT_STRINGIFY(str)
#define GLT_STRINGIFY_VERSION(major, minor, patch) \
_GLT_STRINGIFY(major) "." _GLT_STRINGIFY(minor) "." _GLT_STRINGIFY(patch)
#define GLT_NAME "glText"
#define GLT_VERSION_MAJOR 1
#define GLT_VERSION_MINOR 1
#define GLT_VERSION_PATCH 6
#define GLT_VERSION \
GLT_STRINGIFY_VERSION(GLT_VERSION_MAJOR, GLT_VERSION_MINOR, \
GLT_VERSION_PATCH)
#define GLT_NAME_VERSION GLT_NAME " " GLT_VERSION
#define GLT_NULL 0
#define GLT_NULL_HANDLE 0
#ifdef GLT_IMPORTS
#define GLT_API extern
#else
#ifndef GLT_STATIC
#define GLT_STATIC
#endif
#define GLT_API
#endif
#define GLT_LEFT 0
#define GLT_TOP 0
#define GLT_CENTER 1
#define GLT_RIGHT 2
#define GLT_BOTTOM 2
typedef struct GLTtext GLTtext;
GLT_API GLboolean gltInit(void);
GLT_API void gltTerminate(void);
GLT_API GLTtext* gltCreateText(void);
GLT_API void gltDeleteText(GLTtext* text);
#define gltDestroyText gltDeleteText
GLT_API GLboolean gltSetText(GLTtext* text, const char* string);
GLT_API const char* gltGetText(GLTtext* text);
GLT_API void gltViewport(GLsizei width, GLsizei height);
GLT_API void gltBeginDraw();
GLT_API void gltEndDraw();
GLT_API void gltDrawText(GLTtext* text, const GLfloat mvp[16]);
GLT_API void gltDrawText2D(GLTtext* text, GLfloat x, GLfloat y, GLfloat scale);
GLT_API void gltDrawText2DAligned(GLTtext* text, GLfloat x, GLfloat y,
GLfloat scale, int horizontalAlignment,
int verticalAlignment);
GLT_API void gltDrawText3D(GLTtext* text, GLfloat x, GLfloat y, GLfloat z,
GLfloat scale, GLfloat view[16],
GLfloat projection[16]);
GLT_API void gltColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
GLT_API void gltGetColor(GLfloat* r, GLfloat* g, GLfloat* b, GLfloat* a);
GLT_API GLfloat gltGetLineHeight(GLfloat scale);
GLT_API GLfloat gltGetTextWidth(const GLTtext* text, GLfloat scale);
GLT_API GLfloat gltGetTextHeight(const GLTtext* text, GLfloat scale);
GLT_API GLboolean gltIsCharacterSupported(const char c);
GLT_API GLint gltCountSupportedCharacters(const char* str);
GLT_API GLboolean gltIsCharacterDrawable(const char c);
GLT_API GLint gltCountDrawableCharacters(const char* str);
GLT_API GLint gltCountNewLines(const char* str);
// After this point everything you'll see is the
// implementation and all the internal stuff.
// Use it at your own discretion, but be warned
// that everything can have changed in the next
// commit, so be careful relying on any of it.
#ifdef GLT_IMPLEMENTATION
static GLboolean gltInitialized = GL_FALSE;
#define _GLT_TEXT2D_POSITION_LOCATION 0
#define _GLT_TEXT2D_TEXCOORD_LOCATION 1
#define _GLT_TEXT2D_POSITION_SIZE 2
#define _GLT_TEXT2D_TEXCOORD_SIZE 2
#define _GLT_TEXT2D_VERTEX_SIZE \
(_GLT_TEXT2D_POSITION_SIZE + _GLT_TEXT2D_TEXCOORD_SIZE)
#define _GLT_TEXT2D_POSITION_OFFSET 0
#define _GLT_TEXT2D_TEXCOORD_OFFSET _GLT_TEXT2D_POSITION_SIZE
#define _GLT_MAT4_INDEX(row, column) ((row) + (column)*4)
static const char* _gltFontGlyphCharacters =
" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/"
"():;%&`*#=[]\"";
#define _gltFontGlyphCount 83
#define _gltFontGlyphMinChar ' '
#define _gltFontGlyphMaxChar 'z'
static const int _gltFontGlyphHeight = 17; // Line height
typedef struct _GLTglyph {
char c;
GLint x, y;
GLint w, h;
GLfloat u1, v1;
GLfloat u2, v2;
GLboolean drawable;
} _GLTglyph;
typedef struct _GLTglyphdata {
uint32_t x, y;
uint32_t w, h;
uint32_t marginLeft, marginTop;
uint32_t marginRight, marginBottom;
uint16_t dataWidth, dataHeight;
} _GLTglyphdata;
static _GLTglyph _gltFontGlyphs[_gltFontGlyphCount];
#define _gltFontGlyphLength (_gltFontGlyphMaxChar - _gltFontGlyphMinChar + 1)
static _GLTglyph _gltFontGlyphs2[_gltFontGlyphLength];
static GLuint _gltText2DShader = GLT_NULL_HANDLE;
static GLuint _gltText2DFontTexture = GLT_NULL_HANDLE;
static GLint _gltText2DShaderMVPUniformLocation = -1;
static GLint _gltText2DShaderColorUniformLocation = -1;
static GLfloat _gltText2DProjectionMatrix[16];
struct GLTtext {
char* _text;
GLsizei _textLength;
GLboolean _dirty;
GLsizei vertexCount;
GLfloat* _vertices;
GLuint _vao;
GLuint _vbo;
};
GLT_API void _gltGetViewportSize(GLint* width, GLint* height);
GLT_API void _gltMat4Mult(const GLfloat lhs[16], const GLfloat rhs[16],
GLfloat result[16]);
GLT_API void _gltUpdateBuffers(GLTtext* text);
GLT_API GLboolean _gltCreateText2DShader(void);
GLT_API GLboolean _gltCreateText2DFontTexture(void);
GLT_API GLTtext* gltCreateText(void) {
GLTtext* text = (GLTtext*)calloc(1, sizeof(GLTtext));
_GLT_ASSERT(text);
if (!text) return GLT_NULL;
glGenVertexArrays(1, &text->_vao);
glGenBuffers(1, &text->_vbo);
_GLT_ASSERT(text->_vao);
_GLT_ASSERT(text->_vbo);
if (!text->_vao || !text->_vbo) {
gltDeleteText(text);
return GLT_NULL;
}
glBindVertexArray(text->_vao);
glBindBuffer(GL_ARRAY_BUFFER, text->_vbo);
glEnableVertexAttribArray(_GLT_TEXT2D_POSITION_LOCATION);
glVertexAttribPointer(
_GLT_TEXT2D_POSITION_LOCATION, _GLT_TEXT2D_POSITION_SIZE, GL_FLOAT,
GL_FALSE, (_GLT_TEXT2D_VERTEX_SIZE * sizeof(GLfloat)),
(const void*)(_GLT_TEXT2D_POSITION_OFFSET * sizeof(GLfloat)));
glEnableVertexAttribArray(_GLT_TEXT2D_TEXCOORD_LOCATION);
glVertexAttribPointer(
_GLT_TEXT2D_TEXCOORD_LOCATION, _GLT_TEXT2D_TEXCOORD_SIZE, GL_FLOAT,
GL_FALSE, (_GLT_TEXT2D_VERTEX_SIZE * sizeof(GLfloat)),
(const void*)(_GLT_TEXT2D_TEXCOORD_OFFSET * sizeof(GLfloat)));
glBindVertexArray(0);
return text;
}
GLT_API void gltDeleteText(GLTtext* text) {
if (!text) return;
if (text->_vao) {
glDeleteVertexArrays(1, &text->_vao);
text->_vao = GLT_NULL_HANDLE;
}
if (text->_vbo) {
glDeleteBuffers(1, &text->_vbo);
text->_vbo = GLT_NULL_HANDLE;
}
if (text->_text) free(text->_text);
if (text->_vertices) free(text->_vertices);
free(text);
}
GLT_API GLboolean gltSetText(GLTtext* text, const char* string) {
if (!text) return GL_FALSE;
int strLength = 0;
if (string) strLength = strlen(string);
if (strLength) {
if (text->_text) {
if (strcmp(string, text->_text) == 0) return GL_TRUE;
free(text->_text);
text->_text = GLT_NULL;
}
text->_text = (char*)malloc((strLength + 1) * sizeof(char));
if (text->_text) {
memcpy(text->_text, string, (strLength + 1) * sizeof(char));
text->_textLength = strLength;
text->_dirty = GL_TRUE;
return GL_TRUE;
}
} else {
if (text->_text) {
free(text->_text);
text->_text = GLT_NULL;
} else {
return GL_TRUE;
}
text->_textLength = 0;
text->_dirty = GL_TRUE;
return GL_TRUE;
}
return GL_FALSE;
}
GLT_API const char* gltGetText(GLTtext* text) {
if (text && text->_text) return text->_text;
return "\0";
}
GLT_API void gltViewport(GLsizei width, GLsizei height) {
_GLT_ASSERT(width > 0);
_GLT_ASSERT(height > 0);
const GLfloat left = 0.0f;
const GLfloat right = (GLfloat)width;
const GLfloat bottom = (GLfloat)height;
const GLfloat top = 0.0f;
const GLfloat zNear = -1.0f;
const GLfloat zFar = 1.0f;
const GLfloat projection[16] = {
(2.0f / (right - left)),
0.0f,
0.0f,
0.0f,
0.0f,
(2.0f / (top - bottom)),
0.0f,
0.0f,
0.0f,
0.0f,
(-2.0f / (zFar - zNear)),
0.0f,
-((right + left) / (right - left)),
-((top + bottom) / (top - bottom)),
-((zFar + zNear) / (zFar - zNear)),
1.0f,
};
memcpy(_gltText2DProjectionMatrix, projection, 16 * sizeof(GLfloat));
}
GLT_API void gltBeginDraw() {
glUseProgram(_gltText2DShader);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, _gltText2DFontTexture);
}
GLT_API void gltEndDraw() {}
#define _gltDrawText() \
glUniformMatrix4fv(_gltText2DShaderMVPUniformLocation, 1, GL_FALSE, mvp); \
\
glBindVertexArray(text->_vao); \
glDrawArrays(GL_TRIANGLES, 0, text->vertexCount);
GLT_API void gltDrawText(GLTtext* text, const GLfloat mvp[16]) {
if (!text) return;
if (text->_dirty) _gltUpdateBuffers(text);
if (!text->vertexCount) return;
_gltDrawText();
}
GLT_API void gltDrawText2D(GLTtext* text, GLfloat x, GLfloat y, GLfloat scale) {
if (!text) return;
if (text->_dirty) _gltUpdateBuffers(text);
if (!text->vertexCount) return;
#ifndef GLT_MANUAL_VIEWPORT
GLint viewportWidth, viewportHeight;
_gltGetViewportSize(&viewportWidth, &viewportHeight);
gltViewport(viewportWidth, viewportHeight);
#endif
const GLfloat model[16] = {
scale, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f,
0.0f, 0.0f, scale, 0.0f, x, y, 0.0f, 1.0f,
};
GLfloat mvp[16];
_gltMat4Mult(_gltText2DProjectionMatrix, model, mvp);
_gltDrawText();
}
GLT_API void gltDrawText2DAligned(GLTtext* text, GLfloat x, GLfloat y,
GLfloat scale, int horizontalAlignment,
int verticalAlignment) {
if (!text) return;
if (text->_dirty) _gltUpdateBuffers(text);
if (!text->vertexCount) return;
if (horizontalAlignment == GLT_CENTER)
x -= gltGetTextWidth(text, scale) * 0.5f;
else if (horizontalAlignment == GLT_RIGHT)
x -= gltGetTextWidth(text, scale);
if (verticalAlignment == GLT_CENTER)
y -= gltGetTextHeight(text, scale) * 0.5f;
else if (verticalAlignment == GLT_RIGHT)
y -= gltGetTextHeight(text, scale);
gltDrawText2D(text, x, y, scale);
}
GLT_API void gltDrawText3D(GLTtext* text, GLfloat x, GLfloat y, GLfloat z,
GLfloat scale, GLfloat view[16],
GLfloat projection[16]) {
if (!text) return;
if (text->_dirty) _gltUpdateBuffers(text);
if (!text->vertexCount) return;
const GLfloat model[16] = {
scale, 0.0f,
0.0f, 0.0f,
0.0f, -scale,
0.0f, 0.0f,
0.0f, 0.0f,
scale, 0.0f,
x, y + (GLfloat)_gltFontGlyphHeight * scale,
z, 1.0f,
};
GLfloat mvp[16];
GLfloat vp[16];
_gltMat4Mult(projection, view, vp);
_gltMat4Mult(vp, model, mvp);
_gltDrawText();
}
GLT_API void gltColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) {
glUniform4f(_gltText2DShaderColorUniformLocation, r, g, b, a);
}
GLT_API void gltGetColor(GLfloat* r, GLfloat* g, GLfloat* b, GLfloat* a) {
GLfloat color[4];
glGetUniformfv(_gltText2DShader, _gltText2DShaderColorUniformLocation,
color);
if (r) (*r) = color[0];
if (g) (*g) = color[1];
if (b) (*b) = color[2];
if (a) (*a) = color[3];
}
GLT_API GLfloat gltGetLineHeight(GLfloat scale) {
return (GLfloat)_gltFontGlyphHeight * scale;
}
GLT_API GLfloat gltGetTextWidth(const GLTtext* text, GLfloat scale) {
if (!text || !text->_text) return 0.0f;
GLfloat maxWidth = 0.0f;
GLfloat width = 0.0f;
_GLTglyph glyph;
char c;
int i;
for (i = 0; i < text->_textLength; i++) {
c = text->_text[i];
if ((c == '\n') || (c == '\r')) {
if (width > maxWidth) maxWidth = width;
width = 0.0f;
continue;
}
if (!gltIsCharacterSupported(c)) {
#ifdef GLT_UNKNOWN_CHARACTER
c = GLT_UNKNOWN_CHARACTER;
if (!gltIsCharacterSupported(c)) continue;
#else
continue;
#endif
}
glyph = _gltFontGlyphs2[c - _gltFontGlyphMinChar];
width += (GLfloat)glyph.w;
}
if (width > maxWidth) maxWidth = width;
return maxWidth * scale;
}
GLT_API GLfloat gltGetTextHeight(const GLTtext* text, GLfloat scale) {
if (!text || !text->_text) return 0.0f;
return (GLfloat)(gltCountNewLines(text->_text) + 1) *
gltGetLineHeight(scale);
}
GLT_API GLboolean gltIsCharacterSupported(const char c) {
if (c == '\t') return GL_TRUE;
if (c == '\n') return GL_TRUE;
if (c == '\r') return GL_TRUE;
int i;
for (i = 0; i < _gltFontGlyphCount; i++) {
if (_gltFontGlyphCharacters[i] == c) return GL_TRUE;
}
return GL_FALSE;
}
GLT_API GLint gltCountSupportedCharacters(const char* str) {
if (!str) return 0;
GLint count = 0;
while ((*str) != '\0') {
if (gltIsCharacterSupported(*str)) count++;
str++;
}
return count;
}
GLT_API GLboolean gltIsCharacterDrawable(const char c) {
if (c < _gltFontGlyphMinChar) return GL_FALSE;
if (c > _gltFontGlyphMaxChar) return GL_FALSE;
if (_gltFontGlyphs2[c - _gltFontGlyphMinChar].drawable) return GL_TRUE;
return GL_FALSE;
}
GLT_API GLint gltCountDrawableCharacters(const char* str) {
if (!str) return 0;
GLint count = 0;
while ((*str) != '\0') {
if (gltIsCharacterDrawable(*str)) count++;
str++;
}
return count;
}
GLT_API GLint gltCountNewLines(const char* str) {
GLint count = 0;
while ((str = strchr(str, '\n')) != NULL) {
count++;
str++;
}
return count;
}
GLT_API void _gltGetViewportSize(GLint* width, GLint* height) {
GLint dimensions[4];
glGetIntegerv(GL_VIEWPORT, dimensions);
if (width) (*width) = dimensions[2];
if (height) (*height) = dimensions[3];
}
GLT_API void _gltMat4Mult(const GLfloat lhs[16], const GLfloat rhs[16],
GLfloat result[16]) {
int c, r, i;
for (c = 0; c < 4; c++) {
for (r = 0; r < 4; r++) {
result[_GLT_MAT4_INDEX(r, c)] = 0.0f;
for (i = 0; i < 4; i++)
result[_GLT_MAT4_INDEX(r, c)] +=
lhs[_GLT_MAT4_INDEX(r, i)] * rhs[_GLT_MAT4_INDEX(i, c)];
}
}
}
GLT_API void _gltUpdateBuffers(GLTtext* text) {
if (!text || !text->_dirty) return;
if (text->_vertices) {
text->vertexCount = 0;
free(text->_vertices);
text->_vertices = GLT_NULL;
}
if (!text->_text || !text->_textLength) {
text->_dirty = GL_FALSE;
return;
}
const GLsizei countDrawable = gltCountDrawableCharacters(text->_text);
if (!countDrawable) {
text->_dirty = GL_FALSE;
return;
}
const GLsizei vertexCount =
countDrawable * 2 *
3; // 3 vertices in a triangle, 2 triangles in a quad
const GLsizei vertexSize = _GLT_TEXT2D_VERTEX_SIZE;
GLfloat* vertices =
(GLfloat*)malloc(vertexCount * vertexSize * sizeof(GLfloat));
if (!vertices) return;
GLsizei vertexElementIndex = 0;
GLfloat glyphX = 0.0f;
GLfloat glyphY = 0.0f;
GLfloat glyphWidth;
const GLfloat glyphHeight = (GLfloat)_gltFontGlyphHeight;
const GLfloat glyphAdvanceX = 0.0f;
const GLfloat glyphAdvanceY = 0.0f;
_GLTglyph glyph;
char c;
int i;
for (i = 0; i < text->_textLength; i++) {
c = text->_text[i];
if (c == '\n') {
glyphX = 0.0f;
glyphY += glyphHeight + glyphAdvanceY;
continue;
} else if (c == '\r') {
glyphX = 0.0f;
continue;
}
if (!gltIsCharacterSupported(c)) {
#ifdef GLT_UNKNOWN_CHARACTER
c = GLT_UNKNOWN_CHARACTER;
if (!gltIsCharacterSupported(c)) continue;
#else
continue;
#endif
}
glyph = _gltFontGlyphs2[c - _gltFontGlyphMinChar];
glyphWidth = (GLfloat)glyph.w;
if (glyph.drawable) {
vertices[vertexElementIndex++] = glyphX;
vertices[vertexElementIndex++] = glyphY;
vertices[vertexElementIndex++] = glyph.u1;
vertices[vertexElementIndex++] = glyph.v1;
vertices[vertexElementIndex++] = glyphX + glyphWidth;
vertices[vertexElementIndex++] = glyphY + glyphHeight;
vertices[vertexElementIndex++] = glyph.u2;
vertices[vertexElementIndex++] = glyph.v2;
vertices[vertexElementIndex++] = glyphX + glyphWidth;
vertices[vertexElementIndex++] = glyphY;
vertices[vertexElementIndex++] = glyph.u2;
vertices[vertexElementIndex++] = glyph.v1;
vertices[vertexElementIndex++] = glyphX;
vertices[vertexElementIndex++] = glyphY;
vertices[vertexElementIndex++] = glyph.u1;
vertices[vertexElementIndex++] = glyph.v1;
vertices[vertexElementIndex++] = glyphX;
vertices[vertexElementIndex++] = glyphY + glyphHeight;
vertices[vertexElementIndex++] = glyph.u1;
vertices[vertexElementIndex++] = glyph.v2;
vertices[vertexElementIndex++] = glyphX + glyphWidth;
vertices[vertexElementIndex++] = glyphY + glyphHeight;
vertices[vertexElementIndex++] = glyph.u2;
vertices[vertexElementIndex++] = glyph.v2;
}
glyphX += glyphWidth + glyphAdvanceX;
}
text->vertexCount = vertexCount;
text->_vertices = vertices;
glBindBuffer(GL_ARRAY_BUFFER, text->_vbo);
glBufferData(GL_ARRAY_BUFFER,
vertexCount * _GLT_TEXT2D_VERTEX_SIZE * sizeof(GLfloat),
vertices, GL_DYNAMIC_DRAW);
text->_dirty = GL_FALSE;
}
GLT_API GLboolean gltInit(void) {
/* if (gltInitialized) return GL_TRUE; */
if (!_gltCreateText2DShader()) return GL_FALSE;
if (!_gltCreateText2DFontTexture()) return GL_FALSE;
gltInitialized = GL_TRUE;
return GL_TRUE;
}
GLT_API void gltTerminate(void) {
if (_gltText2DShader != GLT_NULL_HANDLE) {
glDeleteProgram(_gltText2DShader);
_gltText2DShader = GLT_NULL_HANDLE;
}
if (_gltText2DFontTexture != GLT_NULL_HANDLE) {
glDeleteTextures(1, &_gltText2DFontTexture);
_gltText2DFontTexture = GLT_NULL_HANDLE;
}
gltInitialized = GL_FALSE;
}
static const GLchar* _gltText2DVertexShaderSource =
"#version 330 core\n"
"\n"
"in vec2 position;\n"
"in vec2 texCoord;\n"
"\n"
"uniform mat4 mvp;\n"
"\n"
"out vec2 fTexCoord;\n"
"\n"
"void main()\n"
"{\n"
" fTexCoord = texCoord;\n"
" \n"
" gl_Position = mvp * vec4(position, 0.0, 1.0);\n"
"}\n";
static const GLchar* _gltText2DFragmentShaderSource =
"#version 330 core\n"
"\n"
"out vec4 fragColor;\n"
"\n"
"uniform sampler2D diffuse;\n"
"\n"
"uniform vec4 color = vec4(1.0, 1.0, 1.0, 1.0);\n"
"\n"
"in vec2 fTexCoord;\n"
"\n"
"void main()\n"
"{\n"
" fragColor = texture(diffuse, fTexCoord) * color;\n"
"}\n";
GLT_API GLboolean _gltCreateText2DShader(void) {
GLuint vertexShader, fragmentShader;
GLint compileStatus, linkStatus;
#ifdef GLT_DEBUG_PRINT
GLint infoLogLength;
GLsizei infoLogSize;
GLchar* infoLog;
#endif
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &_gltText2DVertexShaderSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus != GL_TRUE) {
#ifdef GLT_DEBUG_PRINT
glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &infoLogLength);
// If no information log exists 0 is returned or 1 for a
// string only containing the null termination char.
if (infoLogLength > 1) {
infoLogSize = infoLogLength * sizeof(GLchar);
infoLog = (GLchar*)malloc(infoLogSize);
glGetShaderInfoLog(vertexShader, infoLogSize, NULL, infoLog);
printf("Vertex Shader #%u <Info Log>:\n%s\n", vertexShader,
infoLog);
free(infoLog);
}
#endif
glDeleteShader(vertexShader);
gltTerminate();
#ifdef GLT_DEBUG
_GLT_ASSERT(compileStatus == GL_TRUE);
return GL_FALSE;
#else
return GL_FALSE;
#endif
}
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &_gltText2DFragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus != GL_TRUE) {
#ifdef GLT_DEBUG_PRINT
glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &infoLogLength);
// If no information log exists 0 is returned or 1 for a
// string only containing the null termination char.
if (infoLogLength > 1) {
infoLogSize = infoLogLength * sizeof(GLchar);
infoLog = (GLchar*)malloc(infoLogSize);
glGetShaderInfoLog(fragmentShader, infoLogSize, NULL, infoLog);
printf("Fragment Shader #%u <Info Log>:\n%s\n", fragmentShader,
infoLog);
free(infoLog);
}
#endif
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
gltTerminate();
#ifdef GLT_DEBUG
_GLT_ASSERT(compileStatus == GL_TRUE);
return GL_FALSE;
#else
return GL_FALSE;
#endif
}
_gltText2DShader = glCreateProgram();
glAttachShader(_gltText2DShader, vertexShader);
glAttachShader(_gltText2DShader, fragmentShader);
glBindAttribLocation(_gltText2DShader, _GLT_TEXT2D_POSITION_LOCATION,
"position");
glBindAttribLocation(_gltText2DShader, _GLT_TEXT2D_TEXCOORD_LOCATION,
"texCoord");
glBindFragDataLocation(_gltText2DShader, 0, "fragColor");
glLinkProgram(_gltText2DShader);
glDetachShader(_gltText2DShader, vertexShader);
glDeleteShader(vertexShader);
glDetachShader(_gltText2DShader, fragmentShader);
glDeleteShader(fragmentShader);
glGetProgramiv(_gltText2DShader, GL_LINK_STATUS, &linkStatus);
if (linkStatus != GL_TRUE) {
#ifdef GLT_DEBUG_PRINT
glGetProgramiv(_gltText2DShader, GL_INFO_LOG_LENGTH, &infoLogLength);
// If no information log exists 0 is returned or 1 for a
// string only containing the null termination char.
if (infoLogLength > 1) {
infoLogSize = infoLogLength * sizeof(GLchar);
infoLog = (GLchar*)malloc(infoLogSize);
glGetProgramInfoLog(_gltText2DShader, infoLogSize, NULL, infoLog);
printf("Program #%u <Info Log>:\n%s\n", _gltText2DShader, infoLog);
free(infoLog);
}
#endif
gltTerminate();
#ifdef GLT_DEBUG
_GLT_ASSERT(linkStatus == GL_TRUE);
return GL_FALSE;
#else
return GL_FALSE;
#endif
}
glUseProgram(_gltText2DShader);
_gltText2DShaderMVPUniformLocation =
glGetUniformLocation(_gltText2DShader, "mvp");
_gltText2DShaderColorUniformLocation =
glGetUniformLocation(_gltText2DShader, "color");
glUniform1i(glGetUniformLocation(_gltText2DShader, "diffuse"), 0);
glUseProgram(0);
return GL_TRUE;
}
static const uint64_t _gltFontGlyphRects[_gltFontGlyphCount] = {
0x1100040000, 0x304090004, 0x30209000D, 0x304090016, 0x30209001F,
0x304090028, 0x302090031, 0x409003A, 0x302090043, 0x30109004C,
0x1080055, 0x30209005D, 0x302090066, 0x3040A006F, 0x304090079,
0x304090082, 0x409008B, 0x4090094, 0x30409009D, 0x3040900A6,
0x3020900AF, 0x3040900B8, 0x3040900C1, 0x3040A00CA, 0x3040900D4,
0x40A00DD, 0x3040900E7, 0x3020900F0, 0x3020900F9, 0x302090102,
0x30209010B, 0x302090114, 0x30209011D, 0x302090126, 0x30209012F,
0x302070138, 0x30209013F, 0x302090148, 0x302090151, 0x3020A015A,
0x3020A0164, 0x30209016E, 0x302090177, 0x102090180, 0x302090189,
0x302090192, 0x30209019B, 0x3020901A4, 0x3020901AD, 0x3020A01B6,
0x3020901C0, 0x3020901C9, 0x3020901D2, 0x3020901DB, 0x3020901E4,
0x3020901ED, 0x3020901F6, 0x3020A01FF, 0x302090209, 0x302090212,
0x30209021B, 0x302090224, 0x30209022D, 0x309060236, 0x10906023C,
0x302070242, 0x302090249, 0x706090252, 0x50409025B, 0x202090264,
0x10207026D, 0x102070274, 0x30406027B, 0x104060281, 0x2010B0287,
0x3020A0292, 0xB0007029C, 0x5040A02AA, 0x3020A02B4, 0x6050902BE,
0x20702C7, 0x20702CE, 0xB010902D5,
};
#define _GLT_FONT_GLYPH_DATA_TYPE uint64_t
#define _GLT_FONT_PIXEL_SIZE_BITS 2
#define _gltFontGlyphDataCount 387
static const _GLT_FONT_GLYPH_DATA_TYPE
_gltFontGlyphData[_gltFontGlyphDataCount] = {
0x551695416A901554, 0x569695A5A56AA55A, 0x555554155545AA9,
0x916AA41569005A40, 0xA5A569695A5A5696, 0x51555556AA569695,
0x696916A941554155, 0x69155A55569555A5, 0x15541555456A9569,
0xA9569545A4005500, 0x569695A5A569695A, 0x5545AA9569695A5A,
0x916A941554555415, 0x55A56AA95A5A5696, 0x40555416A9555695,
0x55A45AA505550155, 0xA55AAA455A555691, 0x169005A45569155,
0xA945554015400554, 0x569695A5A569695A, 0x9545AA9569695A5A,
0x4555555AA95A5556, 0x55A4016900154555, 0xA569695A5A45AA90,
0x69695A5A569695A5, 0x9001541555455555, 0x5AA4155505A4016,
0xA40169005A501695, 0x155555AAA4569505, 0x5A405A4015405555,
0x5A505A545AA45554, 0x5A405A405A405A40, 0x555556A95A555A40,
0x569005A400551554, 0x9569A569695A5A45, 0xA5A56969169A556A,
0xA405555555155555, 0x169005A50169505A, 0x9505A40169005A40,
0x5555155555AAA456, 0x95A66916AA905555, 0x695A6695A6695A66,
0x154555555A5695A6, 0x5696916AA4155555, 0x9695A5A569695A5A,
0x45555155555A5A56, 0xA5A5696916A94155, 0x9569695A5A569695,
0x155515541555456A, 0x695A5A5696916AA4, 0x56AA569695A5A569,
0x5540169155A55569, 0x56AA515550015400, 0x9695A5A569695A5A,
0x5A5516AA55A5A56, 0x500155005A401695, 0xA56A695A5A455555,
0x169015A55569556, 0x54005500155005A4, 0x555A555695AA9455,
0xAA569555A5505AA5, 0x15415551555556, 0x5A55AAA455A50169,
0x40169005A4556915, 0x550155505AA5055A, 0xA569695A5A455555,
0x69695A5A569695A5, 0x555554155545AA95, 0x5A5A569695A5A455,
0xA515AA55A5A56969, 0x1545505500555055, 0x95A6695A6695A569,
0xA4569A55A6695A66, 0x5551555015554569, 0x456A9569695A5A45,
0xA5A5696916A95569, 0x4155545555155555, 0xA45A5A45A5A45A5A,
0xA945A5A45A5A45A5, 0x56A915A555695056, 0x4555501554055551,
0x6945695169555AAA, 0x55AAA45569156955, 0x5A50055055551555,
0xA569695A5A45AA50, 0x69695A5A56AA95A5, 0x555555155555A5A5,
0x5A5A5696916AA415, 0x5A5696956AA56969, 0x1555556AA569695A,
0x96916A9415541555, 0x9555A555695A5A56, 0x6A9569695A5A4556,
0xA405551554155545, 0x69695A5A45A6905A, 0x695A5A569695A5A5,
0x5550555555AA55A, 0x5A555695AAA45555, 0x4556916AA4156955,
0x5555AAA45569155A, 0x95AAA45555555515, 0x6AA41569555A5556,
0xA40169155A455691, 0x1554005500155005, 0x695A5A5696916A94,
0x5A5A56A69555A555, 0x54155545AA956969, 0x569695A5A4555555,
0x9695AAA569695A5A, 0x55A5A569695A5A56, 0x55AA455555551555,
0x5A416905A456915A, 0x515555AA45A51690, 0x169005A400550055,
0x9555A40169005A40, 0x456A9569695A5A56, 0xA5A4555515541555,
0xA55A69569A569695, 0x6969169A45A6915A, 0x555555155555A5A5,
0x5A40169005A400, 0x5A40169005A40169, 0x155555AAA4556900,
0x695A569154555555, 0x6695A6695A9A95A5, 0xA5695A5695A6695A,
0x55154555555A5695, 0x95A5695A56915455, 0x695AA695A6A95A5A,
0x5695A5695A5695A9, 0x155455154555555A, 0x695A5A5696916A94,
0x5A5A569695A5A569, 0x541555456A956969, 0x5696916AA4155515,
0x56956AA569695A5A, 0x5005A40169155A55, 0x6A94155400550015,
0xA569695A5A569691, 0x69695A5A569695A5, 0x5A5415A5456A95,
0x16AA415555500155, 0xAA569695A5A56969, 0x569695A5A55A6956,
0x5545555155555A5A, 0x5555A5696916A941, 0xA5545A5005A5155A,
0x41555456A9569695, 0x56955AAA45555155, 0x9005A40169055A51,
0x5A40169005A4016, 0x5A45555055001550, 0x569695A5A569695A,
0x9695A5A569695A5A, 0x515541555456A956, 0xA5A569695A5A4555,
0xA569695A5A569695, 0x555055A515AA55A5, 0x95A5691545505500,
0x695A6695A5695A56, 0x9A4569A55A6695A6, 0x555015554169A456,
0x9569695A5A455551, 0x5A6515A515694566, 0x555A5A569695A5A4,
0x5A5A455555555155, 0xA9569695A5A56969, 0x169015A41569456,
0x55505500155005A4, 0x5A55169555AAA45, 0x55A455A555A515A5,
0x5155555AAA455690, 0x696916A941554555, 0xA95A5A56A695A9A5,
0x56A9569695A6A569, 0x9401540155415554, 0x5A5516AA45A9516,
0xA40169005A401695, 0x4154005540169005, 0xA5A5696916A94155,
0x9556945695169555, 0x55555AAA45569156, 0x6916A94155455551,
0x56A5169555A5A569, 0xA9569695A5A56955, 0x15415541555456,
0x4169A4055A4005A4, 0xA916969169A5169A, 0x50056954569555AA,
0x5AAA455551540015, 0xAA41569555A55569, 0x55A555A551695516,
0x55005550555555AA, 0x915694569416A401, 0xA5A569695A5A45AA,
0x41555456A9569695, 0x69555AAA45555155, 0x9415A415A5056951,
0x169015A40569056, 0xA941554015400554, 0x569A95A5A5696916,
0x9695A5A56A6956A9, 0x415541555456A956, 0xA5A5696916A94155,
0x516AA55A5A569695, 0x155415A915694569, 0x555A95A915505540,
0x5A55A95A91555545, 0x1694154154555569, 0xA456956A95AA56A9,
0x55416905A415515, 0x696916A941554154, 0x9055A515A555A5A5,
0x5A4016900554056, 0xAA45555055001550, 0x5505555155555A,
0x6955AAA4569505A4, 0x5500155055A515, 0x690169405A400550,
0x90569415A415A505, 0x569015A415A5056, 0x6941540015400554,
0xA456915A55A55691, 0x16905A505A416905, 0x6901555405541694,
0x16905A505A416941, 0x6955A45A516905A4, 0xA455415415545695,
0x6A45555515556A56, 0x56A45555515556A5, 0xA56A45555515556A,
0x5505515555A56956, 0x690569A4016A5001, 0x4056954169A9459A,
0x416A690156941569, 0x15A9505A695169A6, 0x4015505540055540,
0x94169A4169A405A9, 0x5A56A9A4555A415A, 0x555169A955A5A55A,
0x6945A90555555415, 0x1555154055416941, 0x56AAA456A545A690,
0x40555515A69156A5, 0x6945A69015550555, 0xA6915A6956AAA45A,
0x5A6956AAA45A6955, 0x455540555515A691, 0xAA9555556AA91555,
0xA915555554555556, 0x416905A556955A56, 0x5A416905A416905A,
0x555515555AA45690, 0x6905A516955AA455, 0x416905A416905A41,
0x55556A95A556905A, 0xA5A5696915555554, 0x5555155555,
};
GLT_API GLboolean _gltCreateText2DFontTexture(void) {
/* if (gltInitialized) return GL_TRUE; */
memset(_gltFontGlyphs, 0, _gltFontGlyphCount * sizeof(_GLTglyph));
memset(_gltFontGlyphs2, 0, _gltFontGlyphLength * sizeof(_GLTglyph));
GLsizei texWidth = 0;
GLsizei texHeight = 0;
GLsizei drawableGlyphCount = 0;
_GLTglyphdata* glyphsData =
(_GLTglyphdata*)calloc(_gltFontGlyphCount, sizeof(_GLTglyphdata));
uint64_t glyphPacked;
uint32_t glyphMarginPacked;
uint16_t glyphX, glyphY, glyphWidth, glyphHeight;
uint16_t glyphMarginLeft, glyphMarginTop, glyphMarginRight,
glyphMarginBottom;
uint16_t glyphDataWidth, glyphDataHeight;
glyphMarginLeft = 0;
glyphMarginRight = 0;
_GLTglyph* glyph;
_GLTglyphdata* glyphData;
char c;
int i;
int x, y;
for (i = 0; i < _gltFontGlyphCount; i++) {
c = _gltFontGlyphCharacters[i];
glyphPacked = _gltFontGlyphRects[i];
glyphX = (glyphPacked >> (uint64_t)(8 * 0)) & 0xFFFF;
glyphWidth = (glyphPacked >> (uint64_t)(8 * 2)) & 0xFF;
glyphY = 0;
glyphHeight = _gltFontGlyphHeight;
glyphMarginPacked = (glyphPacked >> (uint64_t)(8 * 3)) & 0xFFFF;
glyphMarginTop = (glyphMarginPacked >> (uint16_t)(0)) & 0xFF;
glyphMarginBottom = (glyphMarginPacked >> (uint16_t)(8)) & 0xFF;
glyphDataWidth = glyphWidth;
glyphDataHeight = glyphHeight - (glyphMarginTop + glyphMarginBottom);
glyph = &_gltFontGlyphs[i];
glyph->c = c;
glyph->x = glyphX;
glyph->y = glyphY;
glyph->w = glyphWidth;
glyph->h = glyphHeight;
glyphData = &glyphsData[i];
glyphData->x = glyphX;
glyphData->y = glyphY;
glyphData->w = glyphWidth;
glyphData->h = glyphHeight;
glyphData->marginLeft = glyphMarginLeft;
glyphData->marginTop = glyphMarginTop;
glyphData->marginRight = glyphMarginRight;
glyphData->marginBottom = glyphMarginBottom;
glyphData->dataWidth = glyphDataWidth;
glyphData->dataHeight = glyphDataHeight;
glyph->drawable = GL_FALSE;
if ((glyphDataWidth > 0) && (glyphDataHeight > 0))
glyph->drawable = GL_TRUE;
if (glyph->drawable) {
drawableGlyphCount++;
texWidth += (GLsizei)glyphWidth;
if (texHeight < glyphHeight) texHeight = glyphHeight;
}
}
const GLsizei textureGlyphPadding =
1; // amount of pixels added around the whole bitmap texture
const GLsizei textureGlyphSpacing =
1; // amount of pixels added between each glyph on the final bitmap
// texture
texWidth += textureGlyphSpacing * (drawableGlyphCount - 1);
texWidth += textureGlyphPadding * 2;
texHeight += textureGlyphPadding * 2;
const GLsizei texAreaSize = texWidth * texHeight;
const GLsizei texPixelComponents = 4; // R, G, B, A
GLubyte* texData =
(GLubyte*)malloc(texAreaSize * texPixelComponents * sizeof(GLubyte));
GLsizei texPixelIndex;
for (texPixelIndex = 0; texPixelIndex < (texAreaSize * texPixelComponents);
texPixelIndex++)
texData[texPixelIndex] = 0;
#define _GLT_TEX_PIXEL_INDEX(x, y) \
((y)*texWidth * texPixelComponents + (x)*texPixelComponents)
#define _GLT_TEX_SET_PIXEL(x, y, r, g, b, a) \
{ \
texPixelIndex = _GLT_TEX_PIXEL_INDEX(x, y); \
texData[texPixelIndex + 0] = r; \
texData[texPixelIndex + 1] = g; \
texData[texPixelIndex + 2] = b; \
texData[texPixelIndex + 3] = a; \
}
const int glyphDataTypeSizeBits =
sizeof(_GLT_FONT_GLYPH_DATA_TYPE) * 8; // 8 bits in a byte
int data0Index = 0;
int data1Index = 0;
int bit0Index = 0;
int bit1Index = 1;
char c0 = '0';
char c1 = '0';
GLuint r = 0, g = 0, b = 0, a = 0;
GLfloat u1, v1;
GLfloat u2, v2;
GLsizei texX = 0;
GLsizei texY = 0;
texX += textureGlyphPadding;
for (i = 0; i < _gltFontGlyphCount; i++) {
glyph = &_gltFontGlyphs[i];
glyphData = &glyphsData[i];
if (!glyph->drawable) continue;
c = glyph->c;
glyphX = glyph->x;
glyphY = glyph->y;
glyphWidth = glyph->w;
glyphHeight = glyph->h;
glyphMarginLeft = glyphData->marginLeft;
glyphMarginTop = glyphData->marginTop;
glyphMarginRight = glyphData->marginRight;
glyphMarginBottom = glyphData->marginBottom;
glyphDataWidth = glyphData->dataWidth;
glyphDataHeight = glyphData->dataHeight;
texY = textureGlyphPadding;
u1 = (GLfloat)texX / (GLfloat)texWidth;
v1 = (GLfloat)texY / (GLfloat)texHeight;
u2 = (GLfloat)glyphWidth / (GLfloat)texWidth;
v2 = (GLfloat)glyphHeight / (GLfloat)texHeight;
glyph->u1 = u1;
glyph->v1 = v1;
glyph->u2 = u1 + u2;
glyph->v2 = v1 + v2;
texX += glyphMarginLeft;
texY += glyphMarginTop;
for (y = 0; y < glyphDataHeight; y++) {
for (x = 0; x < glyphDataWidth; x++) {
c0 = (_gltFontGlyphData[data0Index] >> bit0Index) & 1;
c1 = (_gltFontGlyphData[data1Index] >> bit1Index) & 1;
if ((c0 == 0) && (c1 == 0)) {
r = 0;
g = 0;
b = 0;
a = 0;
} else if ((c0 == 0) && (c1 == 1)) {
r = 255;
g = 255;
b = 255;
a = 255;
} else if ((c0 == 1) && (c1 == 0)) {
r = 0;
g = 0;
b = 0;
a = 255;
}
_GLT_TEX_SET_PIXEL(texX + x, texY + y, r, g, b, a);
bit0Index += _GLT_FONT_PIXEL_SIZE_BITS;
bit1Index += _GLT_FONT_PIXEL_SIZE_BITS;
if (bit0Index >= glyphDataTypeSizeBits) {
bit0Index = bit0Index % glyphDataTypeSizeBits;
data0Index++;
}
if (bit1Index >= glyphDataTypeSizeBits) {
bit1Index = bit1Index % glyphDataTypeSizeBits;
data1Index++;
}
}
}
texX += glyphDataWidth;
texY += glyphDataHeight;
texX += glyphMarginRight;
texX += textureGlyphSpacing;
}
for (i = 0; i < _gltFontGlyphCount; i++) {
glyph = &_gltFontGlyphs[i];
_gltFontGlyphs2[glyph->c - _gltFontGlyphMinChar] = *glyph;
}
#undef _GLT_TEX_PIXEL_INDEX
#undef _GLT_TEX_SET_PIXEL
glGenTextures(1, &_gltText2DFontTexture);
glBindTexture(GL_TEXTURE_2D, _gltText2DFontTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA,
GL_UNSIGNED_BYTE, texData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
free(texData);
free(glyphsData);
return GL_TRUE;
}
#endif
#ifdef __cplusplus
}
#endif
#endif
|
UTS-CAS/ouster_example | ouster_viz/src/misc.h | /**
* Copyright (c) 2021, Ouster, Inc.
* All rights reserved.
*/
#pragma once
#include <Eigen/Core>
#include <array>
#include <cstddef>
#include "camera.h"
#include "glfw.h"
#include "gltext.h"
#include "ouster/point_viz.h"
namespace ouster {
namespace viz {
namespace impl {
/*
* Render a set of rings on the ground as markers to helpvisualize lidar range.
*/
class GLRings {
static bool initialized;
static GLuint ring_program_id;
static GLuint ring_xyz_id;
static GLuint ring_proj_view_id;
static GLuint ring_range_id;
const size_t points_per_ring;
GLuint xyz_buffer;
int ring_size_;
bool rings_enabled;
public:
/*
* Parameter etermines number of points used to draw ring, the more the
* rounder
*/
GLRings(const size_t points_per_ring_ = 512);
void update(const TargetDisplay& target);
/*
* Draws the rings from the point of view of the camera. The rings are
* always centered on the camera's target.
*/
void draw(const WindowCtx& ctx, const CameraData& camera);
/*
* Initializes shader program, vertex buffers and handles after OpenGL
* context has been created
*/
static void initialize();
static void uninitialize();
};
/*
* Manages opengl state for drawing a cuboid
*/
class GLCuboid {
static bool initialized;
static GLuint cuboid_program_id;
static GLuint cuboid_xyz_id;
static GLuint cuboid_proj_view_id;
static GLuint cuboid_rgba_id;
const std::array<GLfloat, 24> xyz;
const std::array<GLubyte, 36> indices;
const std::array<GLubyte, 24> edge_indices;
GLuint xyz_buffer{0};
GLuint indices_buffer{0};
GLuint edge_indices_buffer{0};
Eigen::Matrix4d transform;
std::array<float, 4> rgba;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
GLCuboid();
/*
* For Indexed<T, U>, arg ignored
*/
GLCuboid(const Cuboid&);
~GLCuboid();
/*
* Draws the cuboids from the point of view of the camera
*/
void draw(const WindowCtx& ctx, const CameraData& camera, Cuboid& cuboid);
/*
* Initializes shader program and handles
*/
static void initialize();
static void uninitialize();
static void beginDraw();
static void endDraw();
};
class GLLabel {
GLTtext* gltext;
Eigen::Vector3d text_position;
bool is_3d;
float scale;
int halign;
int valign;
std::array<float, 4> rgba;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
GLLabel();
// for Indexed<T, U>
GLLabel(const Label&);
GLLabel(const GLLabel&) = delete;
~GLLabel();
GLLabel& operator=(const GLLabel&) = delete;
void draw(const WindowCtx& ctx, const CameraData& camera, Label& label);
static void beginDraw();
static void endDraw();
};
} // namespace impl
} // namespace viz
} // namespace ouster
|
chengfzy/SLAM | Sphere/Sphere06_CeresPoseParameterization/PoseParameterization.h | <filename>Sphere/Sphere06_CeresPoseParameterization/PoseParameterization.h
#pragma once
#include "ceres/local_parameterization.h"
#include "types.h"
class PoseParameterization : public ceres::LocalParameterization {
public:
// x: [q, p], delta: [delta phi, delta p]
// q = q0 * dq; p = p0 + R(q0) * dp
bool Plus(const double* x, const double* delta, double* x_plus_delta) const override {
Eigen::Map<const Eigen::Quaterniond> q0(x);
Eigen::Map<const Eigen::Vector3d> p0(x + 4);
Eigen::Map<const Eigen::Vector3d> dPhi(delta);
Eigen::Map<const Eigen::Vector3d> dp(delta + 3);
Eigen::Map<Eigen::Quaterniond> q(x_plus_delta);
Eigen::Map<Eigen::Vector3d> p(x_plus_delta + 4);
// convert dPhi to quaternion
const double normDelta = dPhi.norm();
// q = q0 * Exp(dPhi), p = p + q0 * dp
if (normDelta > 0.0) {
const double sinDeltaByDelta = sin(normDelta / 2.0) / normDelta;
Eigen::Quaterniond dq(cos(normDelta / 2.0), sinDeltaByDelta * dPhi[0], sinDeltaByDelta * dPhi[1],
sinDeltaByDelta * dPhi[2]);
q = q0 * dq;
p = p0 + q0 * dp;
} else {
q = q0;
p = p0 + dp;
}
return true;
}
bool ComputeJacobian(const double* x, double* jacobian) const override {
Eigen::Map<const Eigen::Quaterniond> q(x);
Eigen::Map<const Eigen::Vector3d> p(x + 4);
Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> J(jacobian);
// J = [Dq / DdeltaPhi, 0; 0, Dp / DdeltaP]
J.setZero();
double w2 = q.w() * q.w();
double x2 = q.x() * q.x();
double y2 = q.y() * q.y();
double z2 = q.z() * q.z();
double xy = q.x() * q.y();
double yz = q.y() * q.z();
double zx = q.x() * q.z();
double wx = q.w() * q.x();
double wy = q.w() * q.y();
double wz = q.w() * q.z();
// clang-format off
J(0, 0) = 0.5 * q.w(); J(0, 1) = -0.5 * q.z(); J(0, 2) = 0.5 * q.y();
J(1, 0) = 0.5 * q.z(); J(1, 1) = 0.5 * q.w(); J(1, 2) = -0.5 * q.x();
J(2, 0) = -0.5 * q.y(); J(2, 1) = 0.5 * q.x(); J(2, 2) = 0.5 * q.w();
J(3, 0) = -0.5 * q.x(); J(3, 1) = -0.5 * q.y(); J(3, 2) = -0.5 * q.z();
J(4, 3) = w2 + x2 - y2 - z2; J(4, 4) = 2 * (xy - wz); J(4, 5) = 2 * (zx + wy);
J(5, 3) = 2 * (xy + wz); J(5, 4) = w2 - x2 + y2 - z2; J(5, 5) = 2 * (yz - wx);
J(6, 3) = 2 * (zx - wy); J(6, 4) = 2 * (yz + wx); J(6, 5) = w2 - x2 - y2 + z2;
// clang-format on
return true;
}
int GlobalSize() const override { return 7; };
int LocalSize() const override { return 6; };
}; |
chengfzy/SLAM | Sphere/Sphere06_CeresPoseParameterization/G2OReader.h | <filename>Sphere/Sphere06_CeresPoseParameterization/G2OReader.h
#pragma once
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include "glog/logging.h"
// read a single pose from the input and inserts it into the map, return false if there is a duplicate entry
template <typename Pose, typename Allocator>
bool readVertex(std::istream& fs, std::map<int, Pose, std::less<int>, Allocator>& poses) {
int id;
Pose pose;
fs >> id >> pose;
// ensure we don't have duplicate poses
if (poses.count(id) == 1) {
LOG(ERROR) << "Duplicate vertex with ID = " << id;
return false;
}
poses[id] = pose;
return true;
}
// read the constraints between two vertices in the pose graph
template <typename Constraint, typename Allocator>
void readConstraints(std::istream& fs, std::vector<Constraint, Allocator>& constraints) {
Constraint constraint;
fs >> constraint;
constraints.emplace_back(constraint);
}
/**
* Reads a file in the g2o filename format that describes a pose graph problem. The g2o format consists of two entries,
* vertices and constraints.
*
* In 2D, a vertex is defined as follows:
* VERTEX_SE2 ID x_meters y_meters yaw_radians
*
* A constraint is defined as follows:
* EDGE_SE2 ID_A ID_B A_x_B A_y_B A_yaw_B I_11 I_12 I_13 I_22 I_23 I_33
* where I_ij is the (i, j)-th entry of the information matrix for the measurement. Only the upper-triangular part is
* stored
*
*
* In 3D, a vertex is defined as follows:
* VERTEX_SE3:QUAT ID x y z q_x q_y q_z q_w
* where the quaternion is in Hamilton form.
*
* A constraint is defined as follows:
* EDGE_SE3:QUAT ID_a ID_b x_ab y_ab z_ab q_x_ab q_y_ab q_z_ab q_w_ab I_11 I_12 I_13 .. I_16 I_22 I_23 .. I_26 .. I_66
* where I_ij is the (i, j)-th entry of the information matrix for the measurement. Only the upper-triangular part is
* stored. The measurement order is the delta position followed by the delta orientation.
*/
template <typename Pose, typename Constraint, typename MapAllocator, typename VectorAllocator>
bool readG2OFile(const std::string& filename, std::map<int, Pose, std::less<int>, MapAllocator>& poses,
std::vector<Constraint, VectorAllocator>& constraints) {
poses.clear();
constraints.clear();
// read file
std::ifstream fs(filename);
if (!fs.is_open()) {
LOG(ERROR) << "cannot open file \"" << filename << "\"";
return false;
}
std::string dataType;
while (fs.good()) {
// read whether the type is a node or a constraint
fs >> dataType;
if (dataType == Pose::name()) {
if (!readVertex(fs, poses)) {
return false;
}
} else if (dataType == Constraint::name()) {
readConstraints(fs, constraints);
} else {
LOG(ERROR) << "unknown data type: " << dataType;
return false;
}
// clear any trailing whitespace from the line
fs >> std::ws;
}
return true;
} |
chengfzy/SLAM | Sphere/Sphere06_CeresPoseParameterization/PoseGraph3DErrorTerm.h | #pragma once
#include "Eigen/Core"
#include "ceres/ceres.h"
#include "types.h"
class PoseGraph3DErrorTerm {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PoseGraph3DErrorTerm(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation)
: t_ab_(t_ab), sqrtInfo_(sqrtInformation) {}
template <typename T>
bool operator()(const T* const p_a, const T* const p_b, T* residual) const {
Eigen::Map<const Eigen::Quaternion<T>> qA(p_a);
Eigen::Map<const Eigen::Matrix<T, 3, 1>> pA(p_a + 4);
Eigen::Map<const Eigen::Quaternion<T>> qB(p_b);
Eigen::Map<const Eigen::Matrix<T, 3, 1>> pB(p_b + 4);
// compute the relative transformation between the two frames
Eigen::Matrix<T, 3, 1> pAB = qA.inverse() * (pB - pA);
Eigen::Quaternion<T> qAB = qA.inverse() * qB;
// compute the residuals
Eigen::Map<Eigen::Matrix<T, 6, 1>> residualMat(residual);
residualMat.template block<3, 1>(0, 0) = pAB - t_ab_.p.template cast<T>();
// r_phi = Log(dq)
Eigen::Quaternion<T> dq = qAB.inverse() * (t_ab_.q.template cast<T>());
T norm2Dqv = dq.vec().squaredNorm();
// use the below version to calculate Log(dq) will no be convergence for this problem, maybe caused by jacobian
// calculation using jet
// if (norm2Dqv < 1e-6) {
// approximate: r_phi ~ 2 * [dq_x, dq_y. dq_z]
// residualMat.template block<3, 1>(3, 0) = T(2.0) * copysign(1, dq.w()) * dq.vec();
residualMat.template block<3, 1>(3, 0) = T(2.0) * dq.vec();
/*} else {
// r_phi = Log(dq)
T normDqv = sqrt(norm2Dqv);
residualMat.template block<3, 1>(3, 0) = T(2.0) * atan2(normDqv, dq.w()) * dq.vec() / normDqv;
}*/
// scale the residuals by the measurement uncertainty
residualMat.applyOnTheLeft(sqrtInfo_.template cast<T>());
return true;
}
static ceres::CostFunction* create(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation) {
return (new ceres::AutoDiffCostFunction<PoseGraph3DErrorTerm, 6, 7, 7>(
new PoseGraph3DErrorTerm(t_ab, sqrtInformation)));
}
private:
const Pose t_ab_; // the measurement for the position of B relative to A in the frame A
const Eigen::Matrix<double, 6, 6> sqrtInfo_; // the square root of the measurement information matrix
}; |
chengfzy/SLAM | Sphere/Sphere01_CeresQuaternion/PoseGraph3DErrorTerm.h | <reponame>chengfzy/SLAM
#pragma once
#include "Eigen/Core"
#include "ceres/ceres.h"
#include "types.h"
// Compute the error term for two poses that have a relative pose measurement between them.
// Let the hat variables be the measurement, we have two poses x_a and x_b, and through sensor measurements we can
// measurement the measure the transformation of frame B wrt frame A denotes as hat(t_ab).
//
// We have chosen to the rigid transformation as a Hamiltonian quaternion q, and position p, the quaternion ordering is
// [x, y, z, w]. The estimated measurements is
// t_ab = [ p_ab ] = [ R(q_a)^T * (p_b - p_a) ]
// [ q_ab ] = [ q_a^{-1} * q_b ]
//
// and
//
// residual = information^{1/2} * [ p_ab - hat(p_ab) ]
// [ 2.0 * Vec(q_ab * hat(q_ab)^{-1} ]
//
// where Vec(*) returns the vector(imaginary) part of the quaternion
class PoseGraph3DErrorTerm {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PoseGraph3DErrorTerm(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation)
: t_ab_(t_ab), sqrtInfo_(sqrtInformation) {}
template <typename T>
bool operator()(const T* const p_a, const T* const q_a, const T* const p_b, const T* const q_b, T* residual) const {
Eigen::Map<const Eigen::Matrix<T, 3, 1>> pA(p_a);
Eigen::Map<const Eigen::Quaternion<T>> qA(q_a);
Eigen::Map<const Eigen::Matrix<T, 3, 1>> pB(p_b);
Eigen::Map<const Eigen::Quaternion<T>> qB(q_b);
// compute the relative transformation between the two frames
Eigen::Matrix<T, 3, 1> pAB = qA.conjugate() * (pB - pA);
Eigen::Quaternion<T> qAB = qA.conjugate() * qB;
// compute the residuals
Eigen::Map<Eigen::Matrix<T, 6, 1>> residualMat(residual);
residualMat.template block<3, 1>(0, 0) = pAB - t_ab_.p.template cast<T>();
residualMat.template block<3, 1>(3, 0) = T(2.0) * (qAB.conjugate() * t_ab_.q.template cast<T>()).vec();
// scale the residuals by the measurement uncertainty
residualMat.applyOnTheLeft(sqrtInfo_.template cast<T>());
return true;
}
static ceres::CostFunction* create(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation) {
return (new ceres::AutoDiffCostFunction<PoseGraph3DErrorTerm, 6, 3, 4, 3, 4>(
new PoseGraph3DErrorTerm(t_ab, sqrtInformation)));
}
private:
const Pose t_ab_; // the measurement for the position of B relative to A in the frame A
const Eigen::Matrix<double, 6, 6> sqrtInfo_; // the square root of the measurement information matrix
}; |
chengfzy/SLAM | Sphere/Sphere04_CeresSO3/SO3Parameterization.h | #pragma once
#include "ceres/local_parameterization.h"
#include "sophus/so3.hpp"
class SO3Parameterization : public ceres::LocalParameterization {
public:
virtual bool Plus(const double* x, const double* delta, double* x_plus_delta) const {
Eigen::Map<const Sophus::SO3d> R0(x);
Eigen::Map<const Eigen::Matrix<double, 3, 1>> dPhi(delta);
Eigen::Map<Sophus::SO3d> R1(x_plus_delta);
R1 = R0 * Sophus::SO3d::exp(dPhi);
return true;
}
virtual bool ComputeJacobian(const double* x, double* jacobian) const {
Eigen::Map<const Sophus::SO3d> T(x);
Eigen::Map<Eigen::Matrix<double, 4, 3, Eigen::RowMajor>> jacobianMat(jacobian);
jacobianMat = T.Dx_this_mul_exp_x_at_0();
return true;
}
// Size of x: 4
virtual int GlobalSize() const { return Sophus::SO3d::num_parameters; }
// Size of delta: 3
virtual int LocalSize() const { return Sophus::SO3d::DoF; }
}; |
chengfzy/SLAM | Sphere/Sphere06_CeresPoseParameterization/types.h | <reponame>chengfzy/SLAM<filename>Sphere/Sphere06_CeresPoseParameterization/types.h
#pragma once
#include <iostream>
#include <map>
#include <string>
#include "Eigen/Core"
#include "Eigen/Geometry"
// the state for each vertex in the pose graph
struct Pose {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
inline const double* data() const { return q.coeffs().data(); }
double* data() { return q.coeffs().data(); }
Eigen::Quaterniond q;
Eigen::Vector3d p;
// the name of the data type in g2o file format
static const std::string name() { return "VERTEX_SE3:QUAT"; }
};
// the constraint between two vertices in the pose graph, ie, the transform form vertex id_begin to vertex it_end
struct Constraint {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
int idBegin;
int idEnd;
// the transformation represents the pose of the end frame E w.r.t the begin frame B. In other words, it transforms
// a vector in the E frame to the B frame
Pose t_be;
// the inverse of the covariance matrix for the measurement, the order are x, y, z, delta orientation
Eigen::Matrix<double, 6, 6> information;
// the name of the data type in the g2o file format
static const std::string name() { return "EDGE_SE3:QUAT"; }
};
using MapOfPoses = std::map<int, Pose, std::less<int>, Eigen::aligned_allocator<std::pair<const int, Pose>>>;
using VectorOfConstaints = std::vector<Constraint, Eigen::aligned_allocator<Constraint>>;
// read for Pose2d
std::istream& operator>>(std::istream& is, Pose& pose) {
is >> pose.p.x() >> pose.p.y() >> pose.p.z() >> pose.q.x() >> pose.q.y() >> pose.q.z() >> pose.q.w();
// normalize the quaternion to account for precision loss due to serialization
pose.q.normalize();
return is;
}
// read for Constraint2d
std::istream& operator>>(std::istream& is, Constraint& constraint) {
is >> constraint.idBegin >> constraint.idEnd >> constraint.t_be;
for (int i = 0; i < 6 && is.good(); ++i) {
for (int j = i; j < 6 && is.good(); ++j) {
is >> constraint.information(i, j);
if (i != j) {
constraint.information(j, i) = constraint.information(i, j);
}
}
}
return is;
} |
chengfzy/SLAM | Sphere/Sphere04_CeresSO3/PoseGraph3DErrorTerm.h | <gh_stars>10-100
#pragma once
#include "Eigen/Core"
#include "ceres/ceres.h"
#include "types.h"
class PoseGraph3DErrorTerm {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PoseGraph3DErrorTerm(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation)
: t_ab_(t_ab), sqrtInfo_(sqrtInformation) {}
template <typename T>
bool operator()(const T* const p_a, const T* const p_b, T* residual) const {
Eigen::Map<const Sophus::SO3<T>> rA(p_a);
Eigen::Map<const Eigen::Matrix<T, 3, 1>> pA(p_a + 4);
Eigen::Map<const Sophus::SO3<T>> rB(p_b);
Eigen::Map<const Eigen::Matrix<T, 3, 1>> pB(p_b + 4);
// compute the relative transformation between the two frames
Eigen::Matrix<T, 3, 1> pAB = rA.inverse() * (pB - pA);
Sophus::SO3<T> rAB = rA.inverse() * rB;
// compute the residuals
Eigen::Map<Eigen::Matrix<T, 6, 1>> residualMat(residual);
residualMat.template block<3, 1>(0, 0) = pAB - t_ab_.p.template cast<T>();
residualMat.template block<3, 1>(3, 0) = (rAB.inverse() * t_ab_.R).log();
// scale the residuals by the measurement uncertainty
residualMat.applyOnTheLeft(sqrtInfo_.template cast<T>());
return true;
}
static ceres::CostFunction* create(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation) {
return (new ceres::AutoDiffCostFunction<PoseGraph3DErrorTerm, 6, 7, 7>(
new PoseGraph3DErrorTerm(t_ab, sqrtInformation)));
}
private:
const Pose t_ab_; // the measurement for the position of B relative to A in the frame A
const Eigen::Matrix<double, 6, 6> sqrtInfo_; // the square root of the measurement information matrix
}; |
chengfzy/SLAM | Sphere/Sphere05_CeresSE3/PoseGraph3DErrorTerm.h | <filename>Sphere/Sphere05_CeresSE3/PoseGraph3DErrorTerm.h
#pragma once
#include "Eigen/Core"
#include "ceres/ceres.h"
#include "types.h"
class PoseGraph3DErrorTerm {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PoseGraph3DErrorTerm(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation)
: t_ab_(t_ab), sqrtInfo_(sqrtInformation) {}
template <typename T>
bool operator()(const T* const p_a, const T* const p_b, T* residual) const {
Eigen::Map<const Sophus::SE3<T>> pA(p_a);
Eigen::Map<const Sophus::SE3<T>> pB(p_b);
Sophus::SE3<T> pAB = pA.inverse() * pB;
Sophus::SE3<T> res = pAB.inverse() * t_ab_.T.template cast<T>();
Eigen::Map<Eigen::Matrix<T, 6, 1>> residualMat(residual);
residualMat = res.log();
residualMat.applyOnTheLeft(sqrtInfo_.template cast<T>());
return true;
}
static ceres::CostFunction* create(const Pose& t_ab, const Eigen::Matrix<double, 6, 6>& sqrtInformation) {
return (new ceres::AutoDiffCostFunction<PoseGraph3DErrorTerm, 6, 7, 7>(
new PoseGraph3DErrorTerm(t_ab, sqrtInformation)));
}
private:
const Pose t_ab_; // the measurement for the position of B relative to A in the frame A
const Eigen::Matrix<double, 6, 6> sqrtInfo_; // the square root of the measurement information matrix
}; |
chengfzy/SLAM | Sphere/Sphere05_CeresSE3/SE3Parameterization.h | #pragma once
#include "ceres/local_parameterization.h"
#include "sophus/se3.hpp"
class SE3Parameterization : public ceres::LocalParameterization {
public:
virtual bool Plus(const double* x, const double* delta, double* x_plus_delta) const {
Eigen::Map<const Sophus::SE3d> T0(x);
Eigen::Map<const Eigen::Matrix<double, 6, 1>> dPhi(delta);
Eigen::Map<Sophus::SE3d> T1(x_plus_delta);
T1 = T0 * Sophus::SE3d::exp(dPhi);
return true;
}
virtual bool ComputeJacobian(const double* x, double* jacobian) const {
Eigen::Map<const Sophus::SE3d> T(x);
Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> jacobianMat(jacobian);
jacobianMat = T.Dx_this_mul_exp_x_at_0();
return true;
}
// Size of x: 7
virtual int GlobalSize() const { return Sophus::SE3d::num_parameters; }
// Size of delta: 6
virtual int LocalSize() const { return Sophus::SE3d::DoF; }
}; |
mesgu002/visitorPattern | Lab7/src/command.h | <reponame>mesgu002/visitorPattern
#ifndef __COMMAND_CLASS__
#define __COMMAND_CLASS__
#include "composite.h"
class Command {
protected:
Base* root;
public:
Command() { };
double execute() {
return root->evaluate();
};
Base* get_root() {
return root;
};
};
class OpCommand : public Command {
public:
OpCommand(int a) {
root = new Op(a);
}
};
class AddCommand : public Command {
public:
AddCommand(Command* cmd, int b) {
root = new Add(cmd->get_root(), new Op(b));
}
};
class SubCommand : public Command {
public:
SubCommand(Command* cmd, int b) {
root = new Sub(cmd->get_root(), new Op(b));
}
};
class MultCommand : public Command {
public:
MultCommand(Command* cmd, int b) {
root = new Mult(cmd->get_root(), new Op(b));
}
};
class SqrCommand : public Command {
public:
SqrCommand(Command* cmd) {
root = new Sqr(cmd->get_root());
}
};
#endif //__COMMAND_CLASS__
|
mesgu002/visitorPattern | Lab7/src/composite.h | <gh_stars>0
#ifndef __COMPOSITE_CLASS__
#define __COMPOSITE_CLASS__
#include <iostream>
#include <sstream>
#include <math.h>
#include <string>
#include <stack>
using namespace std;
class Iterator;
class NullIterator;
class UnaryIterator;
//Abstract Base Class
class Base {
public:
Base(){};
//virtual
virtual void print() = 0;
virtual double evaluate() = 0;
virtual Iterator* create_iterator() = 0;
virtual Base* get_left() = 0;
virtual Base* get_right() = 0;
};
class Iterator {
protected:
Base* self_ptr;
Base* current_ptr;
public:
Iterator (Base* ptr) { this->self_ptr = ptr; };
virtual void first() = 0;
virtual void next() = 0;
virtual bool is_done() = 0;
virtual Base* current() = 0;
};
class OperatorIterator : public Iterator {
public:
OperatorIterator(Base* ptr) : Iterator(ptr) { current_ptr = self_ptr; };
void first() {
current_ptr = self_ptr->get_left();
}
void next() {
if(current_ptr == self_ptr->get_left()) {
current_ptr = self_ptr->get_right();
}
else if(current_ptr == self_ptr->get_right()) {
current_ptr = NULL;
}
}
bool is_done() {
if(current_ptr == NULL) {
return true;
}
return false;
}
Base* current() {
return current_ptr;
}
};
class UnaryIterator : public Iterator {
public:
UnaryIterator(Base* ptr) : Iterator(ptr) { current_ptr = self_ptr; };
void first() {
current_ptr = self_ptr->get_left();
}
void next() {
current_ptr = NULL;
}
bool is_done() {
if(current_ptr == NULL) {
return true;
}
return false;
}
Base* current() {
return current_ptr;
}
};
class NullIterator : public Iterator {
public:
NullIterator(Base* ptr) : Iterator(ptr) { current_ptr = self_ptr; };
void first() {};
void next() {};
bool is_done() {
return true;
}
Base* current() {
return NULL;
}
};
class PreOrderIterator : public Iterator {
protected:
stack<Iterator*> iterator; //LIFO Queue
public:
PreOrderIterator(Base* ptr) : Iterator(ptr) { current_ptr = self_ptr; };
void first() {
while(!iterator.empty()) {
iterator.pop();
}
Iterator* Base = self_ptr->create_iterator();
Base->first();
iterator.push(Base);
}
void next() {
Iterator* next = iterator.top()->current()->create_iterator();
next->first();
iterator.push(next);
while(!iterator.empty() && iterator.top()->is_done()) {
iterator.pop();
if(!iterator.empty()) {
iterator.top()->next();
}
}
}
bool is_done() {
if(iterator.empty()) {
return true;
}
return false;
}
Base* current() {
return iterator.top()->current();
}
};
//Leaf Class
class Op: public Base {
private:
double value;
public:
Op() : Base(), value(0) {};
Op(double val) : Base(), value(val) {};
Base* get_left() { return NULL; };
Base* get_right() { return NULL; };
double evaluate() { return this->value; };
void print() { cout << this->value; };
Iterator* create_iterator() { return new NullIterator(this); };
};
//Composite Base Classes
class Operator: public Base {
protected:
Base* left, *right;
public:
Operator() : Base() {};
Operator(Base* l, Base* r) : left(l), right(r) {};
Base* get_left() { return left; };
Base* get_right() { return right; };
virtual double evaluate() = 0; //Note: this is implicit in the inheritance, but can also be made explicit
Iterator* create_iterator() { return new OperatorIterator(this); };
};
class UnaryOperator: public Base {
protected:
Base* child;
public:
UnaryOperator() : Base() {};
UnaryOperator(Base* c) : child(c) {};
Base* get_left() { return child; };
Base* get_right() { return NULL; };
virtual double evaluate() = 0; //Note: this is implicit in the inheritance, but can also be made explicit
Iterator* create_iterator() { return new UnaryIterator(this); };
};
//Composite Classes
class Add: public Operator {
public:
Add() : Operator() {};
Add(Base* left, Base* right) : Operator(left, right) {};
void print() { cout << "+"; };
double evaluate() { return this->left->evaluate() - this->right->evaluate(); };
};
class Sub: public Operator {
public:
Sub() : Operator() {};
Sub(Base* left, Base* right) : Operator(left, right) {};
void print() { cout << "-"; };
double evaluate() { return this->left->evaluate() * this->right->evaluate(); };
};
class Mult: public Operator {
public:
Mult() : Operator() {};
Mult(Base* left, Base* right) : Operator(left, right) {};
void print() { cout << "*"; };
double evaluate() { return this->left->evaluate() * this->right->evaluate(); };
};
class Sqr: public UnaryOperator {
public:
Sqr() : UnaryOperator() {};
Sqr(Base* child) : UnaryOperator(child) {};
void print() { cout << "^2"; };
double evaluate() { return pow(this->child->evaluate(), 2); };
};
class Root: public UnaryOperator {
public:
Root() : UnaryOperator() {};
Root(Base* child) : UnaryOperator(child) {};
void print() { cout << "ROOT"; };
double evaluate() { return this->child->evaluate(); };
};
#endif //__COMPOSITE_CLASS__
|
mesgu002/visitorPattern | visitor.h | #ifndef VISITOR_H
#define VISITOR_H
#include <string>
using namespace std;
class Visitor
{
};
class PrintVisitor : public Visitor
{
private:
string output;
public:
PrintVisitor();
void rootNode(); //For visiting a root node (do nothing)
void sqrNode(); //For visiting a square node
void multNode(); //For visiting a multiple node
void subNode(); //For visiting a subtraction node
void addNode(); //For visiting an add node
void opNode(Op* op); //For visiting a leaf node
void execute(); //Prints all visited nodes
};
|
mesgu002/visitorPattern | Lab7/src/menu.h | <gh_stars>0
#ifndef __MENU_CLASS__
#define __MENU_CLASS__
#include <iostream>
#include "command.h"
using namespace std;
class Menu {
private:
int history_index;
vector<Command*> history;
public:
Menu() {
history_index = -1;
};
void execute() {
if(history_index == -1)
cout << "0" << endl;
else
cout << history.at(history_index)->execute() << endl;
};
bool initialized() {
if(history.size() > 0)
return true;
return false;
};
void add_command(Command* cmd) {
while(history_index < history.size()-1) {
history.pop_back();
}
history.push_back(cmd);
history_index++;
};
Command* get_command() {
return history.at(history_index);
};
void undo() {
if(history_index == -1) {
cout << "history Container empty" << endl;
}
else {
history_index--;
}
};
void redo() {
if(history_index != history.size()-1) {
history_index++;
}
else {
cout << "Error, history_index == history.size()-1" << endl;
}
};
};
#endif //__MENU_CLASS__
|
SmallRoomLabs/espbtc | network.h | #ifndef _NETWORK_H_
#define _NETWORK_H_
extern ip_addr_t hostIp;
void StartNetwork(char *_ssid,char *_pw);
void ResolveHost(char *hostName);
void HttpRequest(ip_addr_t hostIp, char *host, char *url);
#endif
|
SmallRoomLabs/espbtc | 4bittube.h | #ifndef _4BITTUBE_H_
#define _4BITTUBE_H_
extern const uint8_t font4bit[];
uint8_t *Init_4bittube(
uint8_t _displayCount,
uint8_t _data,
uint8_t _clock,
uint8_t _latch);
// Functions added specifically for this project
void DisplayNumber(uint32_t num);
void Display(uint8_t d0,uint8_t d1,uint8_t d2,uint8_t d3);
void DisplayDots(uint8_t on);
#endif
|
SmallRoomLabs/espbtc | jsonutils.h | #ifndef _JSONUTILS_H_
#define _JSONUTILS_H_
uint8_t ICACHE_FLASH_ATTR ExtractFromJson(
char *json,
char *searchKey,
char *result,
uint16_t resultLen);
#endif
|
SmallRoomLabs/espbtc | 4bittube.c | //
// Code to drive the cheap 4-digit LED display modules from QIFEI.
// labelled 4-Bit LED Digital Tube Module
//
// Project is available at https://github.com/SmallRoomLabs/4bittube
//
// Copyright 2017 <NAME>, Released under the MIT licence
//
#include "osapi.h"
#include "os_type.h"
#include "mem.h"
#include "gpio.h"
#include "4bittube.h"
// Functions missing in SDK declarations :-(
void *pvPortZalloc(size_t, const char * file, int line);
void ets_timer_disarm(ETSTimer *a);
void ets_timer_setfn(ETSTimer *t, ETSTimerFunc *fn, void *pArg);
void ets_timer_arm_new(ETSTimer *a, int b, int c, int isMstimer);
// Local static storage
static uint8_t pinData;
static uint8_t pinClock;
static uint8_t pinLatch;
static uint8_t displayCount;
// Timer for refreshing the displays
static os_timer_t ledRefreshTimer;
// pointer to malloced display memory
static uint8_t *displayBuf;
// 7-segment "Font" for numbers and some punctuation
const uint8_t font4bit[]= {
0x3F, 0x06, 0x5B, 0x4F, // 0123
0x66, 0x6d, 0x7D, 0x07, // 4567
0x7F, 0x6F, 0x77, 0x7C, // 89AB
0x58, 0x5E, 0x79, 0x71, // CDEF
0x40, 0x80, 0x00 // -.<blank>
};
//
// Shift out one byte of data to the display (chain)
// Since these displays have inverted the logic level
// of the segments (0=on 1=off) we invert the data
// while shifting instead of letting the caller handle
// the inverted data
//
static void ICACHE_FLASH_ATTR ShiftOut(uint8_t data) {
uint8_t mask;
for (mask=0x80; mask; mask>>=1) {
if (data & mask) {
GPIO_OUTPUT_SET(pinData,0);
} else {
GPIO_OUTPUT_SET(pinData,1);
}
GPIO_OUTPUT_SET(pinClock,0);
GPIO_OUTPUT_SET(pinClock,1);
}
}
//
// Timer callback function that refreshes the LED display
//
void ICACHE_FLASH_ATTR ledRefreshCB(void *arg) {
static uint8_t digit;
uint8_t dc;
uint8_t i;
if (digit++>3) digit=0;
i=displayCount*4-1-digit;
// Send segments & digit for each connected display
for (dc=0; dc<displayCount; dc++) {
ShiftOut(displayBuf[i]); // Segments (inverted), LSB=Segment A,
i-=4;
ShiftOut((1<<digit)^0xFF); // Digit#, LSB=Rightmost digit
}
// Latch the data by a brief low-going pulse
GPIO_OUTPUT_SET(pinLatch,0);
GPIO_OUTPUT_SET(pinLatch,1);
}
//
// Inittalize and setup the displays.
//
uint8_t * ICACHE_FLASH_ATTR Init_4bittube(
uint8_t _displayCount,
uint8_t _data,
uint8_t _clock,
uint8_t _latch) {
// Keep track of the GPIO pins connected to the display
pinData=_data;
pinClock=_clock;
pinLatch=_latch;
displayCount=_displayCount;
// Set the display GPIOs as outputs
GPIO_OUTPUT_SET(pinData,1);
GPIO_OUTPUT_SET(pinClock,1);
GPIO_OUTPUT_SET(pinLatch,1);
// Allocate memory for the display buffer
displayBuf=(uint8_t *)os_zalloc(displayCount*4);
// Create and start a timer for refreshing the LED display
// 5 ms gives 1000/(5*4) Hz = 50Hz refresh for a reasonably flicker-
// free display
os_timer_disarm(&ledRefreshTimer);
os_timer_setfn(&ledRefreshTimer, (os_timer_func_t *)ledRefreshCB, NULL);
os_timer_arm(&ledRefreshTimer, 5, 1);
// Return the allocated display buffer
return displayBuf;
}
//
/////////////////////////////////////////////////////////////////////////////
// Functions added unique for this project below
/////////////////////////////////////////////////////////////////////////////
//
//
// Display a number 0.9999 on the display with leading-zero suppression
//
void ICACHE_FLASH_ATTR DisplayNumber(uint32_t num) {
// Cap number a maximum of 9999
if (num>9999) num=9999;
// The three first digits might be blank for leading
// zero suppression
*(displayBuf+2)=0x00;
*(displayBuf+1)=0x00;
*(displayBuf+0)=0x00;
// Only show numbers > 0 for the first thee digits
*(displayBuf+3)=font4bit[num%10];
if (num>9) *(displayBuf+2)=font4bit[(num/10)%10];
if (num>99) *(displayBuf+1)=font4bit[(num/100)%10];
if (num>999) *(displayBuf+0)=font4bit[(num/1000)%10];
}
//
//
//
void ICACHE_FLASH_ATTR Display(uint8_t d0,uint8_t d1,uint8_t d2,uint8_t d3) {
*(displayBuf+0)=d0;
*(displayBuf+1)=d1;
*(displayBuf+2)=d2;
*(displayBuf+3)=d3;
}
//
//
//
void ICACHE_FLASH_ATTR DisplayDots(uint8_t on) {
if (on) {
*(displayBuf+0)|=0x80;
*(displayBuf+1)|=0x80;
*(displayBuf+2)|=0x80;
*(displayBuf+3)|=0x80;
} else {
*(displayBuf+0)&=~0x80;
*(displayBuf+1)&=~0x80;
*(displayBuf+2)&=~0x80;
*(displayBuf+3)&=~0x80;
}
} |
SmallRoomLabs/espbtc | main.c | //
// A small project that fetces the current BTC excange rate from
// the coindesk API and displays it on a 4-digit LED display
//
// The code is available at https://github.com/SmallRoomLabs/espbtc
//
#include "c_types.h"
#include "os_type.h"
#include "osapi.h"
#include "user_interface.h"
#include "espconn.h"
#include "4bittube.h"
#include "network.h"
#include "jsonutils.h"
// Functions missing in SDK declarations :-(
void ets_delay_us(int ms);
void ets_timer_disarm(ETSTimer *a);
void ets_timer_setfn(ETSTimer *t, ETSTimerFunc *fn, void *pArg);
void ets_timer_arm_new(ETSTimer *a, int b, int c, int isMstimer);
int os_printf_plus(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
// Wifi settings
#define SSID "true_homewifi_012"
#define PASSWORD "<PASSWORD>"
// GPIO-pins on the NodeMCU connected to the display modules
// and number of modules connected in the chain
#define TUBE_DATA 5 // D1 GPIO5
#define TUBE_LATCH 4 // D2 GPIO4
#define TUBE_CLOCK 0 // D3 GPIO0
#define TUBE_COUNT 1 // We have one modules in the chain
// Display buffer - memory allocated by the Init_4bittube() function
uint8_t *disp;
// Defines for the main processing task
#define procTaskPrio 0
#define procTaskQueueLen 1
os_event_t procTaskQueue[procTaskQueueLen];
void procTask(os_event_t *events);
// Timer handling network connections and requests
static os_timer_t networkTimer;
#define MSG_IDLE 0b10000000,0b10000000,0b10000000,0b10000000 // ....
#define MSG_PASS <PASSWORD>,<PASSWORD>1101101,<PASSWORD>01<PASSWORD> // PASS
#define MSG_SSID 0b01101101,0b01101101,0b00000100,0b01011110 // SSid
#define MSG_NOIP 0b01010100,0b01011100,0b00000100,0b01110011 // noiP
#define MSG_FAIL 0b01110001,0b01110111,0b00000100,0b00111000 // FAiL
#define MSG_DNS 0b01011110,0b01010100,0b01101101,0b00000000 // dnS
//
// Timer callback for network function
//
void ICACHE_FLASH_ATTR NetworkTimerCB(void *arg) {
static int cnt;
int netStatus;
netStatus=wifi_station_get_connect_status();
switch (netStatus) {
case STATION_IDLE:
Display(MSG_IDLE);
cnt=0;
break;
case STATION_CONNECTING:
Display(MSG_NOIP);
cnt=0;
break;
case STATION_WRONG_PASSWORD:
Display(MSG_PASS);
cnt=0;
break;
case STATION_NO_AP_FOUND:
Display(MSG_SSID);
cnt=0;
break;
case STATION_CONNECT_FAIL:
Display(MSG_FAIL);
cnt=0;
break;
case STATION_GOT_IP:
if (cnt==0) {
// If we don't already have the IP then send a DNS request'
if (hostIp.addr==0) {
Display(MSG_DNS);
ResolveHost("api.coindesk.com");
break;
}
HttpRequest(hostIp,"api.coindesk.com","/v1/bpi/currentprice.json");
}
// Do the API lookup every 30 seconds
if (cnt++>10*30) cnt=0;
break;
}
}
//
// The main procsssing task. Currently empty.
//
void ICACHE_FLASH_ATTR procTask(os_event_t *events) {
system_os_post(procTaskPrio, 0, 0 );
os_delay_us(10);
}
//
// Init/Setup function that gets run once at boot.
//
void ICACHE_FLASH_ATTR user_init() {
// Start the Wifi/network
StartNetwork(SSID, PASSWORD);
// Initialize the display module
disp=Init_4bittube(TUBE_COUNT, TUBE_DATA, TUBE_CLOCK, TUBE_LATCH);
// Start a 100ms timer handling network connections and requests
os_timer_disarm(&networkTimer);
os_timer_setfn(&networkTimer, (os_timer_func_t *)NetworkTimerCB, NULL);
os_timer_arm(&networkTimer, 100, 1);
// Start the main processing task that does nothing in this example
system_os_task(procTask,
procTaskPrio,
procTaskQueue,
procTaskQueueLen);
system_os_post(procTaskPrio, 0, 0 );
}
|
SmallRoomLabs/espbtc | network.c | <reponame>SmallRoomLabs/espbtc
#include "c_types.h"
#include "os_type.h"
#include "osapi.h"
#include "user_interface.h"
#include "espconn.h"
#include "4bittube.h"
#include "jsonutils.h"
#include "network.h"
// Functions missing in SDK declarations :-(
int atoi(const char *nptr);
char *ets_strstr(const char *haystack, const char *needle);
void *ets_memcpy(void *dest, const void *src, size_t n);
int ets_sprintf(char *str, const char *format, ...) __attribute__ ((format (printf, 2, 3)));
int os_printf_plus(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
//
struct ICACHE_FLASH_ATTR station_config wifiConf;
ip_addr_t hostIp;
struct espconn conn;
esp_tcp tcp;
#define MSG_DATAERR 0b00111001,0b01011100,0b00000100,0b01010100 // Coin
// Note! The sizes here must be adjusted to fit your data
#define MAXREPLYLEN 1024
#define MAXHOSTLEN 64
#define MAXURLLEN 64
char host[MAXHOSTLEN];
char url[MAXURLLEN];
//
//
//
void ICACHE_FLASH_ATTR GotDNS(
const char *name,
ip_addr_t *ipaddr,
void *arg) {
// struct espconn *pespconn=(struct espconn *)arg;
if (ipaddr!=NULL) {
hostIp.addr=ipaddr->addr;
os_printf("Resolved IP is %d.%d.%d.%d\n",
*((uint8 *)&ipaddr->addr),
*((uint8 *)&ipaddr->addr+1),
*((uint8 *)&ipaddr->addr+2),
*((uint8 *)&ipaddr->addr+3));
}
}
//
//
//
void ICACHE_FLASH_ATTR ResolveHost(char *hostName) {
espconn_gethostbyname(
&conn,
hostName,
&hostIp,
GotDNS
);
}
//
//
//
void ICACHE_FLASH_ATTR StartNetwork(char *_ssid,char *_pw) {
strcpy((char *)wifiConf.ssid, _ssid);
strcpy((char *)wifiConf.password, _pw);
wifiConf.bssid_set=0;
wifi_station_set_config_current(&wifiConf);
}
//
//
//
void ICACHE_FLASH_ATTR TcpDisconnected(void *arg) {
os_printf("TcpDisconnected()\n");
}
//
//
//
void ICACHE_FLASH_ATTR TcpReceive(void *arg, char *data, uint16_t len) {
char buf[MAXREPLYLEN];
char *p;
os_printf("TcpReceive()\n");
// Find beginning of payload and copy it to the local buffer for processing
p=strstr(data,"\r\n\r\n");
p+=4;
strncpy(buf,p,sizeof(buf));
espconn_disconnect(&conn);
// Extract value from JSON data and display it
char sRate[20];
uint32_t rate;
int res;
res=ExtractFromJson(buf,":bpi:USD:rate_float",sRate,sizeof(sRate));
if (res==0) {
Display(MSG_DATAERR);
} else {
rate=atoi(sRate);
DisplayNumber(rate);
}
}
//
//
//
void ICACHE_FLASH_ATTR TcpConnected(void *arg) {
char buf[256];
os_printf("TcpConnected()\n");
ets_sprintf(buf,"GET %s HTTP/1.1\r\n" \
"Host: %s\r\n" \
"User-Agent: SmallRoomLabs\r\n" \
"Accept: */*\r\n" \
"\r\n\r\n", \
url,host);
// os_printf("[%s]\n",buf);
espconn_regist_recvcb(&conn,TcpReceive);
espconn_sent(&conn,(uint8_t *)buf,strlen(buf));
}
//
//
//
void ICACHE_FLASH_ATTR HttpRequest(ip_addr_t hostIp, char *_host, char *_url) {
// Save the host/url for later usage in the connect callback function
strcpy(host,_host);
strcpy(url,_url);
conn.type=ESPCONN_TCP;
conn.state=ESPCONN_NONE;
conn.proto.tcp=&tcp;
conn.proto.tcp->local_port=espconn_port();
conn.proto.tcp->remote_port=80;
os_memcpy(conn.proto.tcp->remote_ip, &hostIp,4);
DisplayDots(1);
espconn_regist_connectcb(&conn, TcpConnected);
espconn_regist_disconcb(&conn, TcpDisconnected);
espconn_connect(&conn);
}
/*
GET /v1/bpi/currentprice.json HTTP/1.1<crlf>
Host: api.coindesk.com<crlf>
User-Agent: curl/7.50.1<crlf>
Accept: * / *<crlf>
<crlf>
<crlf>
HTTP/1.1 200 OK..Date: Thu, 04 May 2017 06:34:54 GMT..Content-Type: applica
tion/javascript..Content-Length: 668..Set-Cookie: __cfduid=d845ff6c6639d25d
8714325da40065a8b1493879693; expires=Fri, 04-May-18 06:34:53 GMT; path=/; d
omain=.coindesk.com; HttpOnly..X-Powered-By: Bitcoin Love..Cache-Control: m
ax-age=15..Expires: Thu, 04 May 2017 06:35:07 UTC..X-BE: stinger..X-Proxy-C
ache: HIT..Access-Control-Allow-Origin: *..X-Cache-Status-A: HIT..Server: c
loudflare-nginx..CF-RAY: 35996fd616c1707a-SIN..Connection: keep-alive....{"
time":{"updated":"May 4, 2017 06:34:00 UTC","updatedISO":"2017-05-04T06:34:
00+00:00","updateduk":"May 4, 2017 at 07:34 BST"},"disclaimer":"This data w
as produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency d
ata converted using hourly conversion rate from openexchangerates.org","cha
rtName":"Bitcoin","bpi":{"USD":{"code":"USD","symbol":"$","rate":"1,505
.8000","description":"United States Dollar","rate_float":1505.8},"GBP":{"co
de":"GBP","symbol":"£","rate":"1,169.4419","description":"British Pou
nd Sterling","rate_float":1169.4419},"EUR":{"code":"EUR","symbol":"€",
"rate":"1,382.2943","description":"Euro","rate_float":1382.2943}}}
*/
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/Points.h | /*
* Copyright [2014] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef POINTS_H
#define POINTS_H
#include <string.h>
#include <iostream>
#include <Point.h>
using namespace std;
template <typename T> class Points {
public:
Points() {
}
void clear() {
vector < Point < T >> ().swap(points);
}
void add(Point < T > point) {
points.push_back(point);
}
Point<T>& getPoint(int index) {
return this->points.at(index);
}
T getX(int index) {
return points.at(index).getX();
}
T getY(int index) {
return points.at(index).getY();
}
int getLastX() {
return points.at(points.size() - 1).getX();
}
int getLastY() {
return points.at(points.size() - 1).getY();
}
bool isEmpty() {
return points.size() == 0;
}
double size() {
return (double) points.size();
}
private:
vector<Point<T >> points;
};
#endif /* POINTS_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/appStateAnimation.h | <reponame>Blinky0815/MyLittleGuiLibrary
/*
* Copyright [2012] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef APPSTATEANIMATION_H
#define APPSTATEANIMATION_H
#include <iostream>
#include <vector>
#include <string>
#include <mouseEventHandler.h>
#include <Point.h>
#include "RGBA.h"
using namespace std;
class AppStateAnimation {
public:
AppStateAnimation() : point(new Point<int>()), lastTime(SDL_GetTicks()), animationDelay(200), enabled(false), animationStep(0), maxAnimationsSteps(5) {
circleColor.setColor(100, 100, 255, 255);
};
virtual ~AppStateAnimation() {
delete point;
};
void setCircleColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->circleColor.setColor(r, g, b, a);
}
void paint(SDL2Image* image) {
if (enabled) {
if ((SDL_GetTicks() - lastTime) > animationDelay) {
lastTime = SDL_GetTicks();
if (animationStep == maxAnimationsSteps) {
animationStep = 0;
}
animationStep++;
}
image->_filledCircleRGBA(getPosition()->getX() - 1 + getWidth() / 2, getPosition()->getY() + getHeight() / 2, (getWidth() / 2) - 3 + animationStep, circleColor.getR(), circleColor.getG(), circleColor.getB(), circleColor.getA());
}
}
void setDimensions(int width, int height) {
this->width = width;
this->height = height;
}
int getWidth() {
return width;
}
int getHeight() {
return height;
}
void setPosition(int x, int y) {
point->setX(x);
point->setY(y);
}
Point<int>* getPosition() {
return this->point;
}
void setEnabled(bool value) {
this->enabled = value;
}
bool isEnabled() {
return this->enabled;
}
private:
uint32_t lastTime;
int animationStep;
int maxAnimationsSteps;
uint32_t animationDelay;
int width;
int height;
Point<int>* point;
bool enabled;
RGBA circleColor;
};
#endif /* APPSTATEANIMATION_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/Point.h | <reponame>Blinky0815/MyLittleGuiLibrary
/*
* Copyright [2014] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <cmath>
using namespace std;
template <typename T> class Point {
public:
Point() {
}
Point(T x, T y) {
this->point.first = x;
this->point.second = y;
}
bool operator<(Point<T> &p) {
return getX() < p.getX() || (getX() == p.getX() && getY() < p.getY());
}
T getX() {
return this->point.first;
}
T getY() {
return this->point.second;
}
void setX(T x) {
this->point.first = x;
}
void setY(T y) {
this->point.second = y;
}
double euclideanDistance(Point<T>& p) {
int dx = getX() - p.getX();
int dy = getY() - p.getY();
int dx2 = dx*dx;
int dy2 = dy*dy;
return sqrt(dx2 + dy2);
}
double cross(Point &A, Point &B) {
return (A.getX() - getX()) * (B.getY() - getY()) - (A.getY() - getY()) * (B.getX() - getX());
}
float getAngleOfLineBetweenTwoPoints(Point<float> p) {
float xDiff = getX() - p.getX();
float yDiff = getY() - p.getY();
return atan2(yDiff, xDiff) * (180 / M_PI);
}
private:
pair<T, T > point;
};
#endif /* POINT_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/DiskSpace.h | <gh_stars>0
/*
* Copyright [2012] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef DISKSPACE_H
#define DISKSPACE_H
#include <sys/statfs.h>
#include <iomanip>
#include <sstream>
#include <SDL2Panel.h>
#include <Point.h>
using namespace std;
class DiskSpace : public SDL2Panel {
public:
DiskSpace() {
textColor.setColor(255, 255, 255, 200);
}
virtual ~DiskSpace() {
}
void paint(SDL2Image* image) {
float usage = getFreeDiskSpace(path);
Point<int>& position = getPosition();
image->_boxRGBA(position.getX(), position.getY(), position.getX() + SDL2Panel::getWidth(), position.getY() + SDL2Panel::getHeight() - 2, backgroundColor.getR(), backgroundColor.getG(), backgroundColor.getB(), backgroundColor.getA());
image->_boxRGBA(position.getX(), position.getY(), position.getX() + SDL2Panel::getWidth() * usage, position.getY() + getHeight() - 2, barColor.getR(), barColor.getG(), barColor.getB(), barColor.getA());
image->_rectangleRGBA(position.getX(), position.getY(), position.getX() + SDL2Panel::getWidth(), position.getY() + SDL2Panel::getHeight(), borderColor.getR(), borderColor.getG(), borderColor.getB(), borderColor.getA());
std::ostringstream buff;
buff << "Disk usage: %" << setprecision(2) << usage * 100;
string freeSpace = buff.str();
image->_stringRGBA(position.getX() + 30, position.getY() + (SDL2Panel::getHeight() / 2) - 4, freeSpace.c_str(), textColor.getR(), textColor.getG(), textColor.getB(), textColor.getA());
}
void setPath(const char* path) {
this->path = path;
}
void setTextColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->textColor.setColor(r, g, b, a);
}
void setBackgroundColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->backgroundColor.setColor(r, g, b, a);
}
void setBarColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->barColor.setColor(r, g, b, a);
}
void setBorderColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->borderColor.setColor(r, g, b, a);
}
private:
float getFreeDiskSpace(const char* absoluteFilePath) {
struct statfs buf;
if (!statfs(absoluteFilePath, &buf)) {
unsigned long blksize, blocks, freeblks, free;
float disk_size, used;
blksize = buf.f_bsize;
blocks = buf.f_blocks;
freeblks = buf.f_bfree;
disk_size = blocks*blksize;
free = freeblks*blksize;
used = disk_size - free;
return used / disk_size;
} else {
return -1;
}
}
const char* path;
RGBA backgroundColor;
RGBA barColor;
RGBA borderColor;
RGBA textColor;
};
#endif /* DISKSPACE_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/mouseEventHandler.h | <gh_stars>0
/*
* Copyright [2012] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef MOUSEEVENTHANDLER_H
#define MOUSEEVENTHANDLER_H
#include <iostream>
#include <vector>
#include <SDL2Image.h>
using namespace std;
template <typename T> class MouseEventHandler {
public:
MouseEventHandler() {
}
MouseEventHandler(T* t) {
this->t = t;
}
MouseEventHandler(const MouseEventHandler& orig) {
}
virtual ~MouseEventHandler() {
}
virtual void onMouseMove(int mX, int mY, int relX, int relY, bool left, bool right, bool middle) {
}
virtual void onLButtonDown(int mX, int mY) {
}
virtual void onLButtonUp(int mX, int mY) {
}
virtual void onRButtonDown(int mX, int mY) {
}
virtual void onRButtonUp(int mX, int mY) {
}
virtual void onMButtonDown(int mX, int mY) {
}
virtual void onMButtonUp(int mX, int mY) {
}
virtual T* getT() {
return t;
}
virtual int getButtonID() {
}
virtual void setButtonID(int value) {
}
private:
T* t;
};
#endif /* MOUSEEVENTHANDLER_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/sliderbutton.h | <reponame>Blinky0815/MyLittleGuiLibrary
/*
* Copyright [2012] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef SLIDERBUTTON_H
#define SLIDERBUTTON_H
#include <iostream>
#include <vector>
#include <string>
#include <mouseEventHandler.h>
#include <SDL2Image.h>
#include <RGBA.h>
#include <button.h>
using namespace std;
template <typename T> class SliderButton : public Button<T> {
public:
void checkCollision(SDL_Event* event) {
Button<T>::checkCollision(event);
}
void paint(SDL2Image* image) {
Button<T>::paint(image);
}
int getSliderHeight() {
return this->sliderHeight;
}
void setSliderHeight(int value) {
this->sliderHeight = value;
}
int getSliderWidth() {
return this->sliderWidth;
}
void setSliderWidth(int value) {
this->sliderWidth = value;
}
private:
int sliderWidth;
int sliderHeight;
double sliderValue;
};
#endif /* SLIDERBUTTON_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/ProgressBar.h | <gh_stars>0
/*
* Copyright [2014] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef PROGRESSBAR_H
#define PROGRESSBAR_H
#include <SDL2Image.h>
#include <Point.h>
#include <RGBA.h>
class ProgressBar {
public:
ProgressBar() : percentage(1.0) {
}
void setColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->color.setColor(r, g, b, a);
}
void paint(SDL2Image* image) {
if (isVisible()) {
image->_boxRGBA(position.getX(), position.getY(), getWidth() + position.getX(), getHeight() + position.getY(), color.getR(), color.getG(), color.getB(), color.getA());
image->_boxRGBA(position.getX() + 20, (position.getY() + getHeight() / 2) - (getHeight() / 2) + 20, position.getX() + 20 + (getWidth() - 40) * percentage, (position.getY() + getHeight() / 2) + (getHeight() / 2) - 20, color.getR(), color.getG(), color.getB(), color.getA()*1.5);
SDL_RenderCopy(image->getRenderer(), this->text, NULL, &rect);
}
}
void setPosition(int x, int y) {
position.setX(x);
position.setY(y);
}
void setText(SDL_Texture *text) {
this->text = text;
int w, h;
SDL_QueryTexture(text, NULL, NULL, &w, &h);
rect.x = position.getX() + (getWidth() / 2) - (w / 2);
rect.y = position.getY() + (getHeight() / 2) - (h / 2);
rect.w = w;
rect.h = h;
}
void update(int steps) {
this->percentage = (float) steps / (float) getNumSteps();
}
Point<int>& getPosition() {
return this->position;
}
bool isVisible() {
return this->visble;
}
void setVisible(bool value) {
this->visble = value;
}
int getWidth() {
return this->width;
}
int getHeight() {
return this->height;
}
void setWidth(int value) {
this->width = value;
}
void setHeight(int value) {
this->height = value;
}
int getNumSteps() {
return this->numSteps;
}
void setNumSteps(int value) {
this->numSteps = value;
}
virtual ~ProgressBar() {
}
private:
int width;
int height;
Point<int> position;
RGBA color;
int numSteps;
float percentage;
SDL_Texture *text;
SDL_Rect rect;
bool visble = false;
};
#endif /* PROGRESSBAR_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/observable.h | <filename>MyLittleGuiLibrary/observable.h
/*
* Copyright [2013] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef OBSERVABLE_H
#define OBSERVABLE_H
#include <mutex>
#include <vector>
#include <algorithm>
#include <iterator>
#include <observer.h>
using namespace std;
class Observable {
public:
Observable() {
}
virtual ~Observable() {
}
void addObserver(Observer *observer) {
std::lock_guard<std::mutex> lock(_mutex);
if (!binary_search(observers.begin(), observers.end(), observer)) {
observers.push_back(observer);
}
}
void notifyObservers() {
for (typename vector<Observer *>::iterator it = observers.begin(); it != observers.end(); it++) {
(*it)->update();
}
}
template <typename Object> inline void notifyObservers(Object* object) {
for (typename vector<Observer *>::iterator it = observers.begin(); it != observers.end(); it++) {
(*it)->update(object);
}
}
void deleteObserver(Observer *observer) {
std::lock_guard<std::mutex> lock(_mutex);
const int index = std::distance(observers.begin(), std::lower_bound(observers.begin(), observers.end(), observer));
if (observers.size() > 0 and index < observers.size()) {
observers.erase(observers.begin() + index);
}
}
void deleteObservers() {
std::lock_guard<std::mutex> lock(_mutex);
vector<Observer *>().swap(observers);
}
const int numObservers() {
std::lock_guard<std::mutex> lock(_mutex);
return observers.size();
}
private:
std::vector<Observer *> observers;
std::mutex _mutex;
};
#endif /* ABSTRACTOBSERVABLE_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/Stopwatch.h | /*
* Copyright [2014] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef STOPWATCH_H
#define STOPWATCH_H
#include <iostream>
#include <SDL2Image.h>
#include <TimeConverter.h>
#include <iomanip>
#include <RGBA.h>
#include <chrono>
#include <Point.h>
using namespace std;
class Stopwatch {
public:
Stopwatch() : running(false), startTime(0), stopTime(0), currentTime(0), currentHours(0), currentMinutes(0), currentSeconds(0), currentMilliseconds(0), width(200), height(150), delay(1000), blink(true), normalClock(true), showDate(false) {
setPosition(0, 0);
lastTime = SDL_GetTicks();
title = string("Timer");
}
virtual ~Stopwatch() {
TTF_CloseFont(this->font);
}
void paint(SDL2Image* image) {
updateTime();
//timeStringStream.clear();
stringstream timeStringStream;
timeStringStream << std::setfill('0') << std::setw(2) << currentHours << ":" << std::setfill('0') << std::setw(2) << currentMinutes << ":" << std::setfill('0') << std::setw(2) << currentSeconds << endl;
image->_roundedBoxRGBA(position.getX() + 25, position.getY() + 12, position.getX() + getWidth(), position.getY() + getHeight(), 5, backgroundColor.getR(), backgroundColor.getG(), backgroundColor.getB(), backgroundColor.getA());
SDL_Color textColor;
textColor.r = digitColor.getR();
textColor.g = digitColor.getG();
textColor.b = digitColor.getB();
textColor.a = digitColor.getA();
string strg = timeStringStream.str();
//changeDigitColor();
SDL_Surface *surf = TTF_RenderText_Blended(font, strg.c_str(), textColor);
SDL_Texture *texture = SDL_CreateTextureFromSurface(image->getRenderer(), surf);
SDL_FreeSurface(surf);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
SDL_SetTextureAlphaMod(texture, digitColor.getA());
int w, h;
SDL_Rect rect;
SDL_QueryTexture(texture, NULL, NULL, &w, &h);
rect.x = position.getX() + 25;
rect.y = position.getY() + 12;
rect.w = w;
rect.h = h;
SDL_RenderCopy(image->getRenderer(), texture, NULL, &rect);
image->_stringRGBA(position.getX() + 25, position.getY() + 12, title.c_str(), 0, 0, 0, 255);
if (blink) {
image->_boxRGBA(rect.x + 44, rect.y + 19, rect.x + 49, rect.y + 24, 255, 0, 0, digitColor.getA());
image->_boxRGBA(rect.x + 44, rect.y + 30, rect.x + 49, rect.y + 35, 255, 0, 0, digitColor.getA());
image->_boxRGBA(rect.x + 97, rect.y + 19, rect.x + 102, rect.y + 24, 255, 0, 0, digitColor.getA());
image->_boxRGBA(rect.x + 97, rect.y + 30, rect.x + 102, rect.y + 35, 255, 0, 0, digitColor.getA());
}
if ((SDL_GetTicks() - lastTime) > delay) {
blink = !blink;
lastTime = SDL_GetTicks();
}
SDL_DestroyTexture(texture);
}
void setDelay(int value) {
this->delay = value;
}
void reset() {
currentHours = 0;
currentMinutes = 0;
currentSeconds = 0;
}
void start() {
reset();
this->running = true;
startTime = SDL_GetTicks();
}
void pause() {
this->running = false;
}
void resume() {
this->running = true;
}
void stop() {
this->running = false;
stopTime = SDL_GetTicks();
}
void setBackgroundColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->backgroundColor.setColor(r, g, b, a);
}
void setDigitColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->digitColor.setColor(r, g, b, a);
}
void setColonColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->colonColor.setColor(r, g, b, a);
}
void setWidth(int value) {
this->width = value;
}
int getWidth() {
return this->width;
}
void setHeight(int value) {
this->height = value;
}
int getHeight() {
return this->height;
}
void setPosition(int x, int y) {
this->position.setX(x);
this->position.setY(y);
}
Point<int>& getPosition() {
return this->position;
}
void setFont(TTF_Font* font) {
this->font = font;
if (font == nullptr) {
cout << "font is NULL" << endl;
}
}
RGBA& getBackgroundColor() {
return this->backgroundColor;
}
RGBA& getDigitColor() {
return this->digitColor;
}
RGBA& getColonColor() {
return this->colonColor;
}
int getCurrentTime() {
return this->currentTime;
}
void setTitle(string title) {
this->title = title;
}
string& getTitle() {
return this->title;
}
tm* getDate() {
return this->date;
}
double getMilliseconds() {
std::chrono::time_point<std::chrono::high_resolution_clock> t1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> time_span = t1 - t0;
return time_span.count();
}
int getHour() {
return timeConverter.millisToHours(getMilliseconds()) % 24;
}
int getMinute() {
return timeConverter.millisToMinutes(getMilliseconds()) % 60;
}
int getSeconds() {
return timeConverter.millisToSeconds(getMilliseconds()) % 60;
}
int getMillis() {
return timeConverter.millisToMillis(getMilliseconds()) % 1000;
}
void updateTime() {
std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
time_t tnow = std::chrono::high_resolution_clock::to_time_t(now);
this->date = std::localtime(&tnow);
if (this->running) {
currentTime = SDL_GetTicks() - startTime;
}
currentHours = timeConverter.millisToHours(currentTime) % 24;
currentMinutes = timeConverter.millisToMinutes(currentTime) % 60;
currentSeconds = timeConverter.millisToSeconds(currentTime) % 60;
if (!this->running && normalClock) {
currentHours = date->tm_hour;
currentMinutes = date->tm_min;
currentSeconds = date->tm_sec;
}
currentMilliseconds = currentTime;
}
private:
void changeDigitColor() {
if (this->currentHours == 17 && currentMinutes == 21 && currentSeconds == 0) {
digitColor.setColor((int) (digitColor.getR() / 2.0), (int) (digitColor.getG() / 2.0), (int) (digitColor.getB() / 2.0), digitColor.getA());
} else if (this->currentHours == 17 && currentMinutes == 23 && currentSeconds == 0) {
digitColor.setColor((int) (digitColor.getR() * 2.0), (int) (digitColor.getG() * 2.0), (int) (digitColor.getB() * 2.0), digitColor.getA());
}
}
std::chrono::time_point<std::chrono::high_resolution_clock> t0 = std::chrono::high_resolution_clock::now();
tm *date;
int startTime;
int stopTime;
int currentTime;
bool running;
bool normalClock;
bool showDate;
int currentHours;
int currentMinutes;
int currentSeconds;
int currentMilliseconds;
TimeConverter timeConverter;
RGBA backgroundColor;
RGBA digitColor;
RGBA colonColor;
Point<int> position;
int width;
int height;
TTF_Font* font;
int delay;
bool blink;
int lastTime;
string title;
};
#endif /* STOPWATCH_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/FileInfo.h | <reponame>Blinky0815/MyLittleGuiLibrary
/*
* Copyright [2014] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef FILEINFO_H
#define FILEINFO_H
#include <iostream>
#include <sys/statfs.h>
#include <SDL2Image.h>
#include <RGBA.h>
#include <Point.h>
#include <sstream>
using namespace std;
class FileInfo {
public:
FileInfo() {
}
void paint(SDL2Image* image) {
image->_boxRGBA(position.getX(), position.getY(), position.getX() + getWidth(), position.getY() + getHeight(), backgroundColor.getR(), backgroundColor.getG(), backgroundColor.getB(), backgroundColor.getA());
image->_rectangleRGBA(position.getX(), position.getY(), position.getX() + getWidth(), position.getY() + getHeight(), borderColor.getR(), borderColor.getG(), borderColor.getB(), borderColor.getA());
image->_stringRGBA(position.getX() + 5, position.getY() + (getHeight() / 2) - 4, pathInfo.c_str(), 255, 255, 255, 200);
}
void setWidth(int value) {
this->width = value;
}
int getWidth() {
return this->width;
}
void setHeight(int value) {
this->height = value;
}
int getHeight() {
return this->height;
}
void setPosition(int x, int y) {
this->position.setX(x);
this->position.setY(y);
}
Point<int>& getPosition() {
return this->position;
}
void setPath(const char* path) {
this->path = path;
std::ostringstream buff;
buff << "Path:" << this->path;
pathInfo.clear();
pathInfo = buff.str();
}
void setBackgroundColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->backgroundColor.setColor(r, g, b, a);
}
void setBorderColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->borderColor.setColor(r, g, b, a);
}
virtual ~FileInfo() {
}
private:
Point<int> position;
int width;
int height;
const char* path;
RGBA backgroundColor;
RGBA borderColor;
string pathInfo;
};
#endif /* FILEINFO_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/Slider.h | <reponame>Blinky0815/MyLittleGuiLibrary<filename>MyLittleGuiLibrary/Slider.h
/*
* Copyright [2014] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef SLIDER_H
#define SLIDER_H
#include <sliderbutton.h>
#include <SliderButtonEventHandler.h>
#include <SDL2Image.h>
#include <Point.h>
using namespace std;
template <typename T> class ChangeEventHandler {
public:
ChangeEventHandler() {
}
ChangeEventHandler(T* t) {
this->t = t;
}
ChangeEventHandler(const ChangeEventHandler& orig) {
}
virtual void onChange() {
getT()->handleChange();
}
virtual ~ChangeEventHandler() {
}
virtual T* getT() {
return t;
}
private:
T* t;
};
template <typename T> class Slider {
public:
Slider() : height(30), width(100), minValue(0), maxValue(255), percentage(0), doubleValue(0) {
position.setX(10);
position.setY(768 - 300);
color.setColor(255, 255, 255, 255);
}
void init(SDL2Image* anSDL2ImagePtr) {
SDL_Surface * sliderButtonImage = IMG_Load("./SliderButton.png");
sliderButton = new SliderButton<SliderButtonEventHandler<Slider> > ();
sliderButton->setTexture(SDL_CreateTextureFromSurface(anSDL2ImagePtr->getRenderer(), sliderButtonImage));
sliderButton->setMousePressedTexture(SDL_CreateTextureFromSurface(anSDL2ImagePtr->getRenderer(), sliderButtonImage));
sliderButton->setMouseOverTexture(SDL_CreateTextureFromSurface(anSDL2ImagePtr->getRenderer(), sliderButtonImage));
sliderButton->setDimensions(getHeigth(), getHeigth());
sliderButton->setCaption("");
sliderButton->setPosition(getPosition().getX(), getPosition().getY());
sliderButton->setButtonID(SLIDER_BUTTON_HORIZONTAL_ID);
sliderButtonEventHandler = new SliderButtonEventHandler<Slider > (this);
sliderButton->addEventHandler(sliderButtonEventHandler);
SDL_FreeSurface(sliderButtonImage);
value = 0;
originalPosition.setX(sliderButton->getPosition()->first);
originalPosition.setY(sliderButton->getPosition()->second);
}
void checkCollision(SDL_Event* event) {
this->sliderButton->checkCollision(event);
}
void paint(SDL2Image* anSDL2ImagePtr) {
anSDL2ImagePtr->_lineRGBA((sliderButton->getWidth() / 2) + position.getX(), position.getY() - 5 + (getHeigth() / 2), position.getX() + getWidth() + sliderButton->getWidth()-(sliderButton->getWidth() / 2), position.getY() - 5 + (getHeigth() / 2), color.getR(), color.getG(), color.getB(), color.getA());
sliderButton->paint(anSDL2ImagePtr);
//anSDL2ImagePtr->_rectangleRGBA(position.getX(), position.getY() - 5, position.getX() + getWidth() + sliderButton->getWidth(), position.getY() + getHeigth(), color.getR(), color.getG(), color.getB(), color.getA());
}
Slider(const Slider& orig) {
}
virtual ~Slider() {
}
void onMouseMove(int mX, int mY, int relX, int relY, bool left, bool right, bool middle) {
if (buttonPressed) {
int oldValue = value;
int x = sliderButton->getPosition()->first;
int y = sliderButton->getPosition()->second;
value += relX;
if (value < 0) {
value = 0;
}
if (value > getWidth()) {
value = getWidth();
}
percentage = ((double) value / (double) getWidth());
if (percentage < 0.0) {
percentage = 0;
} else if (percentage > 1.0) {
percentage = 1.0;
}
this->doubleValue = minValue + (percentage * maxValue);
if (x >= originalPosition.getX() && x <= (originalPosition.getX() + getWidth())) {
sliderButton->setPosition(originalPosition.getX() + value, sliderButton->getPosition()->second);
}
if (oldValue != value) {
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->onChange();
}
}
}
}
void setSliderPosition(double percentage) {
int oldValue = value;
value = (double) getWidth() * percentage;
this->doubleValue = minValue + (percentage * maxValue);
sliderButton->setPosition(originalPosition.getX() + value, sliderButton->getPosition()->second);
if (oldValue != value) {
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->onChange();
}
}
}
void onLButtonUp(int mX, int mY) {
buttonPressed = false;
}
void onLButtonDown(int mX, int mY) {
buttonPressed = true;
}
void setWidth(int value) {
this->width = value;
}
void setHeight(int value) {
this->height = value;
}
int getHeigth() {
return this->height;
}
int getWidth() {
return this->width;
}
double getDoubleValue() {
return this->doubleValue;
}
double getPercentage() {
return this->percentage;
}
int getMaxValue() {
return this->maxValue;
}
int getMinValue() {
return this->minValue;
}
void setMaxValue(int value) {
this->maxValue = value;
}
void setMinValue(int value) {
this->minValue = value;
}
void setColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->color.setColor(r, g, b, a);
}
void setPosition(int x, int y) {
this->position.setX(x);
this->position.setY(y);
}
Point<int>& getPosition() {
return this->position;
}
void addEventHandler(T* value) {
eventHandler.push_back(value);
}
T* removeEventHandler(T* value) {
for (int i = 0; i < eventHandler.size(); i++) {
if (eventHandler[i] == value) {
eventHandler.erase(eventHandler.begin() + i);
}
}
}
private:
SliderButtonEventHandler<Slider>* sliderButtonEventHandler;
SliderButton<SliderButtonEventHandler<Slider> >* sliderButton;
bool buttonPressed;
int height;
int width;
int value;
int minValue;
int maxValue;
double percentage;
Point<int> position;
Point<int> originalPosition;
double doubleValue;
RGBA color;
vector<T*> eventHandler;
};
#endif /* SLIDER_H */
|
Blinky0815/MyLittleGuiLibrary | MyLittleGuiLibrary/button.h | /*
* Copyright [2012] Olaf - blinky0815 - christ ]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: blinky0815
* email: <EMAIL>
*/
#ifndef BUTTON_H
#define BUTTON_H
#include <iostream>
#include <vector>
#include <string>
#include <mouseEventHandler.h>
#include <SDL2Image.h>
#include <RGBA.h>
using namespace std;
template <typename T> class Button {
public:
Button() : state(IDLE), point(new pair<int, int>()), alpha(255), buttonID(0), captionXoffset(0), captionYoffset(0) {
captionColor.setColor(0, 0, 0, 255);
}
Button(const Button& orig) {
}
~Button() {
delete point;
SDL_DestroyTexture(getTexture());
}
void setCaption(const char* caption) {
this->caption = caption;
}
SDL_Texture* getTexture() {
return imageTexture;
}
void setTexture(SDL_Texture* image) {
this->imageTexture = image;
SDL_SetTextureAlphaMod(this->imageTexture, this->alpha);
}
SDL_Texture* getMouseOverTexture() {
return mouseOverImageTexture;
}
void setMouseOverTexture(SDL_Texture* image) {
mouseOverImageTexture = image;
SDL_SetTextureAlphaMod(this->mouseOverImageTexture, this->alpha);
}
SDL_Texture* getMousePressedTexture() {
return mousePressedImageTexture;
}
void setMousePressedTexture(SDL_Texture* image) {
mousePressedImageTexture = image;
SDL_SetTextureAlphaMod(this->mousePressedImageTexture, this->alpha);
}
void setPosition(int x, int y) {
point->first = x;
point->second = y;
}
pair<int, int>* getPosition() {
return point;
}
int getID() {
return id;
}
void setID(int id) {
this->id = id;
}
void setDimensions(int width, int height) {
this->width = width;
this->height = height;
}
int getWidth() {
return width;
}
int getHeight() {
return height;
}
void addEventHandler(T* value) {
eventHandler.push_back(value);
}
T* removeEventHandler(T* value) {
for (int i = 0; i < eventHandler.size(); i++) {
if (eventHandler[i] == value) {
eventHandler.erase(eventHandler.begin() + i);
}
}
}
void checkCollision(SDL_Event* event) {
pair<int, int> center;
center.first = getPosition()->first + (getWidth() / 2);
center.second = getPosition()->second + (getHeight() / 2);
int distance;
this->state = IDLE;
switch (event->type) {
case SDL_MOUSEMOTION:
{
distance = sqrt(pow(center.first - event->motion.x, 2) + pow(center.second - event->motion.y, 2));
if (distance < (getWidth() / 2) && distance < (getHeight() / 2)) {
state = MOUSE_OVER;
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->onMouseMove(event->motion.x, event->motion.y, event->motion.xrel, event->motion.yrel, (event->motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0, (event->motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0, (event->motion.state & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0);
}
}
break;
}
case SDL_MOUSEBUTTONDOWN:
{
distance = sqrt(pow(center.first - event->button.x, 2) + pow(center.second - event->button.y, 2));
switch (event->button.button) {
case SDL_BUTTON_LEFT:
{
if (distance < (getWidth() / 2) && distance < (getHeight() / 2)) {
state = MOUSE_PRESSED;
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->setButtonID(getButtonID());
eventHandler[i]->onLButtonDown(event->button.x, event->button.y);
}
}
break;
}
case SDL_BUTTON_RIGHT:
{
if (distance < (getWidth() / 2) && distance < (getHeight() / 2)) {
state = MOUSE_PRESSED;
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->setButtonID(getButtonID());
eventHandler[i]->onRButtonDown(event->button.x, event->button.y);
}
}
break;
}
case SDL_BUTTON_MIDDLE:
{
if (distance < (getWidth() / 2) && distance < (getHeight() / 2)) {
state = MOUSE_PRESSED;
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->setButtonID(getButtonID());
eventHandler[i]->onMButtonDown(event->button.x, event->button.y);
}
}
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP:
{
distance = sqrt(pow(center.first - event->button.x, 2) + pow(center.second - event->button.y, 2));
switch (event->button.button) {
case SDL_BUTTON_LEFT:
{
if (distance < (getWidth() / 2) && distance < (getHeight() / 2)) {
state = MOUSE_RELEASED;
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->setButtonID(getButtonID());
eventHandler[i]->onLButtonUp(event->button.x, event->button.y);
}
}
break;
}
case SDL_BUTTON_RIGHT:
{
if (distance < (getWidth() / 2) && distance < (getHeight() / 2)) {
state = MOUSE_RELEASED;
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->setButtonID(getButtonID());
eventHandler[i]->onRButtonUp(event->button.x, event->button.y);
}
}
break;
}
case SDL_BUTTON_MIDDLE:
{
if (distance < (getWidth() / 2) && distance < (getHeight() / 2)) {
state = MOUSE_RELEASED;
for (int i = 0; i < eventHandler.size(); i++) {
eventHandler[i]->setButtonID(getButtonID());
eventHandler[i]->onMButtonUp(event->button.x, event->button.y);
}
}
break;
}
}
break;
}
}
}
void setCaptionColor(RGBA& color) {
this->captionColor.setColor(color.getR(), color.getG(), color.getB(), color.getA());
}
RGBA& getCaptionColor() {
return this->captionColor;
}
void setAlpha(unsigned char value) {
this->alpha = value;
SDL_SetTextureAlphaMod(this->imageTexture, this->alpha);
SDL_SetTextureAlphaMod(this->mouseOverImageTexture, this->alpha);
SDL_SetTextureAlphaMod(this->mousePressedImageTexture, this->alpha);
}
unsigned char getAlpha() {
return this->alpha;
}
void setButtonID(int value) {
this->buttonID = value;
}
int getButtonID() {
return this->buttonID;
}
void paint(SDL2Image* image) {
SDL_Rect DestR;
DestR.x = getPosition()->first;
DestR.y = getPosition()->second;
DestR.w = getWidth();
DestR.h = getHeight();
switch (state) {
case IDLE:
SDL_RenderCopy(image->getRenderer(), getTexture(), NULL, &DestR);
break;
case MOUSE_OVER:
SDL_RenderCopy(image->getRenderer(), getMouseOverTexture(), NULL, &DestR);
break;
case MOUSE_PRESSED:
SDL_RenderCopy(image->getRenderer(), getMousePressedTexture(), NULL, &DestR);
break;
case MOUSE_RELEASED:
SDL_RenderCopy(image->getRenderer(), getTexture(), NULL, &DestR);
break;
}
image->_stringRGBA((getPosition()->first + getWidth() / 4) + this->captionXoffset, (getPosition()->second + getHeight() + 10) + this->captionYoffset, caption, captionColor.getR(), captionColor.getG(), captionColor.getB(), captionColor.getA());
}
void setCaptionXoffset(int value) {
this->captionXoffset = value;
}
void setCaptionYoffset(int value) {
this->captionYoffset = value;
}
private:
enum STATE {
IDLE = 0, MOUSE_OVER = 1, MOUSE_PRESSED = 2, MOUSE_RELEASED = 3
};
const char* caption;
int width;
int height;
STATE state;
int id;
SDL_Texture* imageTexture;
SDL_Texture* mouseOverImageTexture;
SDL_Texture* mousePressedImageTexture;
pair<int, int>* point;
vector<T*> eventHandler;
RGBA captionColor;
unsigned char alpha;
int buttonID;
int captionXoffset;
int captionYoffset;
};
#endif /* BUTTON_H */
|
ftsrg/gazer | include/gazer/Trace/VerificationResult.h | <gh_stars>1-10
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_TRACE_VerificationResult_H
#define GAZER_TRACE_VerificationResult_H
#include "gazer/Trace/Trace.h"
#include <llvm/ADT/Twine.h>
namespace gazer
{
class VerificationResult
{
public:
static constexpr unsigned SuccessErrorCode = 0;
static constexpr unsigned GeneralFailureCode = 1;
enum Status { Success, Fail, Timeout, Unknown, BoundReached, InternalError };
protected:
explicit VerificationResult(Status status, std::string message = "")
: mStatus(status), mMessage(message)
{}
public:
[[nodiscard]] bool isSuccess() const { return mStatus == Success; }
[[nodiscard]] bool isFail() const { return mStatus == Fail; }
[[nodiscard]] bool isUnknown() const { return mStatus == Unknown; }
[[nodiscard]] Status getStatus() const { return mStatus; }
llvm::StringRef getMessage() const { return mMessage; }
static std::unique_ptr<VerificationResult> CreateSuccess();
static std::unique_ptr<VerificationResult> CreateFail(unsigned ec, std::unique_ptr<Trace> trace = nullptr);
static std::unique_ptr<VerificationResult> CreateUnknown();
static std::unique_ptr<VerificationResult> CreateTimeout();
static std::unique_ptr<VerificationResult> CreateInternalError(llvm::Twine message);
static std::unique_ptr<VerificationResult> CreateBoundReached();
virtual ~VerificationResult() = default;
private:
Status mStatus;
std::string mMessage;
};
class FailResult final : public VerificationResult
{
public:
explicit FailResult(
unsigned errorCode,
std::unique_ptr<Trace> trace = nullptr
) : VerificationResult(VerificationResult::Fail), mErrorID(errorCode),
mTrace(std::move(trace))
{}
[[nodiscard]] bool hasTrace() const { return mTrace != nullptr; }
[[nodiscard]] Trace& getTrace() const { return *mTrace; }
[[nodiscard]] unsigned getErrorID() const { return mErrorID; }
static bool classof(const VerificationResult* result) {
return result->getStatus() == VerificationResult::Fail;
}
private:
unsigned mErrorID;
std::unique_ptr<Trace> mTrace;
};
} // end namespace gazer
#endif |
ftsrg/gazer | include/gazer/LLVM/Memory/MemoryInstructionHandler.h | //==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 This file declares the MemoryInstructionHandler interface, which
/// will be used by the LLVM IR translation process to represent memory
/// instructions.
///
//===----------------------------------------------------------------------===//
#ifndef GAZER_LLVM_MEMORY_MEMORYINSTRUCTIONHANDLER_H
#define GAZER_LLVM_MEMORY_MEMORYINSTRUCTIONHANDLER_H
#include "gazer/LLVM/Automaton/ModuleToAutomata.h"
namespace gazer
{
/// An interface which allows the translation of pointer and array types.
class MemoryTypeTranslator
{
public:
explicit MemoryTypeTranslator(GazerContext& context)
: mContext(context)
{}
/// Returns the representation of a given pointer type.
virtual gazer::Type& handlePointerType(const llvm::PointerType* type) = 0;
/// Translates types of constant arrays and initializers.
virtual gazer::Type& handleArrayType(const llvm::ArrayType* type) = 0;
virtual ~MemoryTypeTranslator() = default;
GazerContext& getContext() const { return mContext; }
protected:
GazerContext& mContext;
};
/// An interface for translating memory-related instructions.
class MemoryInstructionHandler
{
public:
// Variables
//==--------------------------------------------------------------------==//
/// Allows the declaration of top-level procedure variables.
virtual void declareFunctionVariables(llvm2cfa::VariableDeclExtensionPoint& ep) {}
/// Allows the declaration of loop-procedure level variables.
virtual void declareLoopProcedureVariables(
llvm::Loop* loop, llvm2cfa::LoopVarDeclExtensionPoint& ep) {}
// Allocations
//==--------------------------------------------------------------------==//
/// Translates an alloca instruction into an assignable expression.
virtual ExprPtr handleAlloca(
const llvm::AllocaInst& alloc,
llvm2cfa::GenerationStepExtensionPoint& ep) = 0;
// Pointer value representation
//==--------------------------------------------------------------------==//
// These methods are used to translate various pointer-related values.
// As they are supposed to return expressions without side-effects, these
// do not get access to an extension point. Instead, they receive the
// already-translated operands of their instruction as an input parameter.
/// Represents a given non-instruction pointer.
virtual ExprPtr handlePointerValue(const llvm::Value* value) = 0;
/// Represents a pointer casting instruction.
virtual ExprPtr handlePointerCast(
const llvm::CastInst& cast,
const ExprPtr& origPtr) = 0;
/// Represents a pointer arithmetic instruction.
virtual ExprPtr handleGetElementPtr(
const llvm::GetElementPtrInst& gep,
llvm::ArrayRef<ExprPtr> ops) = 0;
/// Translates constant arrays.
virtual ExprPtr handleConstantDataArray(
const llvm::ConstantDataArray* cda, llvm::ArrayRef<ExprRef<LiteralExpr>> elems) = 0;
virtual ExprPtr handleZeroInitializedAggregate(const llvm::ConstantAggregateZero* caz) = 0;
// Memory definitions and uses
//==--------------------------------------------------------------------==//
/// Translates the given store instruction.
virtual void handleStore(
const llvm::StoreInst& store,
llvm2cfa::GenerationStepExtensionPoint& ep) = 0;
/// Handles possible memory definitions in the beginning of blocks.
virtual void handleBlock(
const llvm::BasicBlock& bb, llvm2cfa::GenerationStepExtensionPoint& ep)
{}
/// Handles possible memory phi-nodes on basic block edges.
virtual void handleBasicBlockEdge(
const llvm::BasicBlock& source,
const llvm::BasicBlock& target,
llvm2cfa::GenerationStepExtensionPoint& ep)
{}
/// Returns the value of a load as an assignable expression.
virtual ExprPtr handleLoad(
const llvm::LoadInst& load,
llvm2cfa::GenerationStepExtensionPoint& ep) = 0;
/// Translates a given call instruction. Clients can assume that the callee
/// function has a definition and a corresponding automaton already exists.
/// The parameters \p inputAssignments and \p outputAssignments will be placed
/// on the resulting automaton call _after_ the regular input/output assignments.
virtual void handleCall(
llvm::CallSite call,
llvm2cfa::GenerationStepExtensionPoint& callerEp,
llvm2cfa::AutomatonInterfaceExtensionPoint& calleeEp,
llvm::SmallVectorImpl<VariableAssignment>& inputAssignments,
llvm::SmallVectorImpl<VariableAssignment>& outputAssignments) = 0;
/// If the memory model wishes to handle external calls to unknown functions, it
/// may do so through this method. Note that known memory-related functions such
/// as malloc, memset, memcpy, etc. have their own overridable methods, therefore
/// they should not be handled here. Furthermore, if the call is to a non-void
/// function, the translation process already generates a havoc assignment for
/// it _before_ calling this function.
virtual void handleExternalCall(
llvm::CallSite call, llvm2cfa::GenerationStepExtensionPoint& ep) {}
// Memory safety predicates
//==--------------------------------------------------------------------==//
/// Returns a boolean expression which evaluates to true if a memory access
/// through \p ptr (represented by the expression in \p expr) is valid.
virtual ExprPtr isValidAccess(llvm::Value* ptr, const ExprPtr& expr) = 0;
virtual ~MemoryInstructionHandler() = default;
};
namespace memory
{
class MemorySSA;
}
/// A base class for MemorySSA-based instruction handlers.
class MemorySSABasedInstructionHandler : public MemoryInstructionHandler
{
public:
MemorySSABasedInstructionHandler(memory::MemorySSA& memorySSA, LLVMTypeTranslator& types)
: mMemorySSA(memorySSA), mTypes(types)
{}
void declareFunctionVariables(llvm2cfa::VariableDeclExtensionPoint& ep) override;
void declareLoopProcedureVariables(
llvm::Loop* loop, llvm2cfa::LoopVarDeclExtensionPoint& ep) override;
void handleBasicBlockEdge(
const llvm::BasicBlock& source,
const llvm::BasicBlock& target,
llvm2cfa::GenerationStepExtensionPoint& ep) override;
protected:
virtual gazer::Type& getMemoryObjectType(MemoryObject* object);
protected:
memory::MemorySSA& mMemorySSA;
LLVMTypeTranslator& mTypes;
};
} // namespace gazer
#endif
|
ftsrg/gazer | include/gazer/Automaton/CfaTransforms.h | <gh_stars>1-10
//==- CfaTransforms.h - Cfa transformation utilities ------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 This file declares common CFA transformation functions.
//
//===----------------------------------------------------------------------===//
#ifndef GAZER_AUTOMATON_CFATRANSFORMS_H
#define GAZER_AUTOMATON_CFATRANSFORMS_H
#include "gazer/Automaton/Cfa.h"
#include <llvm/ADT/StringRef.h>
#include <llvm/ADT/DenseMap.h>
namespace gazer
{
//===----------------------------------------------------------------------===//
/// Creates a clone of the given CFA with the given name.
/// Note that the clone shall be shallow one: automata called by the source
/// CFA shall be the same in the cloned one.
Cfa* CloneAutomaton(Cfa* cfa, llvm::StringRef name);
//===----------------------------------------------------------------------===//
struct RecursiveToCyclicResult
{
Location* errorLocation = nullptr;
Variable* errorFieldVariable = nullptr;
llvm::DenseMap<Location*, Location*> inlinedLocations;
llvm::DenseMap<Variable*, Variable*> inlinedVariables;
};
/// Transforms the given recursive CFA into a cyclic one, by inlining all
/// tail-recursive calls and adding latch edges.
/// Note that cyclic CFAs are non-canon, and should only be used if they are
/// transformed into the input format of a different verifier.
RecursiveToCyclicResult TransformRecursiveToCyclic(Cfa* cfa);
//===----------------------------------------------------------------------===//
struct InlineResult
{
llvm::DenseMap<Variable*, Variable*> VariableMap;
llvm::DenseMap<Location*, Location*> InlinedLocations;
llvm::SmallVector<Location*, 8> NewErrors;
std::vector<Location*> NewLocations;
};
//void InlineCall(CallTransition* call, InlineResult& result, ExprBuilder& exprBuilder, llvm::Twine suffix = "_inlined");
}
#endif |
ftsrg/gazer | test/verif/base/loops4_fail.c | // RUN: %bmc -bound 10 "%s" | FileCheck "%s"
// CHECK: Verification FAILED
#include <assert.h>
unsigned __VERIFIER_nondet_uint(void);
int main(void)
{
unsigned i = 0;
unsigned c = __VERIFIER_nondet_uint();
unsigned x = 1;
while (i < c) {
unsigned y = __VERIFIER_nondet_uint();
x = x + y;
++i;
}
assert(x != 0);
return 0;
}
|
ftsrg/gazer | test/theta/verif/memory/globals3.c | // RUN: %theta "%s" | FileCheck "%s"
// CHECK: Verification SUCCESSFUL
#include <limits.h>
int __VERIFIER_nondet_int(void);
void __VERIFIER_error(void) __attribute__((__noreturn__));
void __VERIFIER_assume(int expression);
int b = 1;
int c = 2;
int main(void)
{
int a = __VERIFIER_nondet_int();
int d = 3;
int* ptr;
if (a == 0) {
ptr = &b;
} else {
ptr = &c;
}
if (*ptr > d) {
__VERIFIER_error();
}
return 0;
} |
ftsrg/gazer | test/verif/regression/flat_memory_params.c | // RUN: %bmc -bound 1 -memory=flat -checks="assertion-fail" "%s" | FileCheck "%s"
// CHECK: Verification SUCCESSFUL
// This test failed because the SSA-based memory model inserted all memory objects
// as loop procedure inputs instead of just inserting the ones which were actually
// used by the loop. Furthermore, this test also produced a crash in the globals
// variable inling pass due to its incorrect handling of constant expressions.
void f(int i);
struct b *c;
struct b {
int d;
} e() {
f(c->d);
return *c;
}
int main() {
int a;
for (; a;)
;
e();
}
|
ftsrg/gazer | include/gazer/Core/LiteralExpr.h | //==- LiteralExpr.h - Literal expression subclasses -------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_CORE_LITERALEXPR_H
#define GAZER_CORE_LITERALEXPR_H
#include "gazer/Core/Expr.h"
#include <llvm/ADT/APInt.h>
#include <llvm/ADT/APFloat.h>
#include <boost/rational.hpp>
#include <map>
namespace llvm {
class ConstantData;
}
namespace gazer
{
class UndefExpr final : public AtomicExpr
{
friend class ExprStorage;
private:
explicit UndefExpr(Type& type)
: AtomicExpr(Expr::Undef, type)
{}
public:
static ExprRef<UndefExpr> Get(Type& type);
void print(llvm::raw_ostream& os) const override;
static bool classof(const Expr* expr) {
return expr->getKind() == Undef;
}
};
class BoolLiteralExpr final : public LiteralExpr
{
friend class GazerContextImpl;
private:
BoolLiteralExpr(BoolType& type, bool value)
: LiteralExpr(type), mValue(value)
{}
public:
static ExprRef<BoolLiteralExpr> True(BoolType& type);
static ExprRef<BoolLiteralExpr> True(GazerContext& context) { return True(BoolType::Get(context)); }
static ExprRef<BoolLiteralExpr> False(BoolType& type);
static ExprRef<BoolLiteralExpr> False(GazerContext& context) { return False(BoolType::Get(context)); }
static ExprRef<BoolLiteralExpr> Get(GazerContext& context, bool value) {
return Get(BoolType::Get(context), value);
}
static ExprRef<BoolLiteralExpr> Get(BoolType& type, bool value) {
return value ? True(type) : False(type);
}
BoolType& getType() const { return static_cast<BoolType&>(mType); }
void print(llvm::raw_ostream& os) const override;
bool getValue() const { return mValue; }
bool isTrue() const { return mValue == true; }
bool isFalse() const { return mValue == false; }
public:
static bool classof(const Expr* expr) {
return expr->getKind() == Literal && expr->getType().isBoolType();
}
static bool classof(const Expr& expr) {
return expr.getKind() == Literal && expr.getType().isBoolType();
}
private:
bool mValue;
};
class IntLiteralExpr final : public LiteralExpr
{
friend class ExprStorage;
public:
using ValueTy = int64_t;
private:
IntLiteralExpr(IntType& type, long long int value)
: LiteralExpr(type), mValue(value)
{}
public:
static ExprRef<IntLiteralExpr> Get(IntType& type, long long int value);
static ExprRef<IntLiteralExpr> Get(GazerContext& ctx, long long int value) {
return Get(IntType::Get(ctx), value);
}
public:
void print(llvm::raw_ostream& os) const override;
int64_t getValue() const { return mValue; }
bool isZero() const { return mValue == 0; }
bool isOne() const { return mValue == 1; }
IntType& getType() const { return static_cast<IntType&>(mType); }
static bool classof(const Expr* expr) {
return expr->getKind() == Literal && expr->getType().isIntType();
}
static bool classof(const Expr& expr) {
return expr.getKind() == Literal && expr.getType().isIntType();
}
private:
long long int mValue;
};
class RealLiteralExpr final : public LiteralExpr
{
friend class ExprStorage;
private:
RealLiteralExpr(RealType& type, boost::rational<long long int> value)
: LiteralExpr(type), mValue(value)
{}
public:
static ExprRef<RealLiteralExpr> Get(RealType& type, boost::rational<long long int> value);
static ExprRef<RealLiteralExpr> Get(RealType& type, long long int num, long long int denom) {
return Get(type, boost::rational<long long int>(num, denom));
}
public:
void print(llvm::raw_ostream& os) const override;
boost::rational<long long int> getValue() const { return mValue; }
RealType& getType() const { return static_cast<RealType&>(mType); }
static bool classof(const Expr* expr) {
return expr->getKind() == Literal && expr->getType().isRealType();
}
static bool classof(const Expr& expr) {
return expr.getKind() == Literal && expr.getType().isRealType();
}
private:
boost::rational<long long int> mValue;
};
class BvLiteralExpr final : public LiteralExpr
{
friend class ExprStorage;
friend class GazerContextImpl;
private:
BvLiteralExpr(BvType& type, llvm::APInt value)
: LiteralExpr(type), mValue(std::move(value))
{
assert(type.getWidth() == mValue.getBitWidth() && "Type and literal bit width must match.");
}
public:
void print(llvm::raw_ostream& os) const override;
public:
static ExprRef<BvLiteralExpr> Get(BvType& type, const llvm::APInt& value);
static ExprRef<BvLiteralExpr> Get(BvType& type, uint64_t value) {
return Get(type, llvm::APInt{type.getWidth(), value});
}
llvm::APInt getValue() const { return mValue; }
bool isOne() const { return mValue.isOneValue(); }
bool isZero() const { return mValue.isNullValue(); }
bool isAllOnes() const { return mValue.isAllOnesValue(); }
BvType& getType() const { return static_cast<BvType&>(mType); }
static bool classof(const Expr* expr) {
return expr->getKind() == Literal && expr->getType().isBvType();
}
static bool classof(const Expr& expr) {
return expr.getKind() == Literal && expr.getType().isBvType();
}
private:
llvm::APInt mValue;
};
class FloatLiteralExpr final : public LiteralExpr
{
friend class ExprStorage;
private:
FloatLiteralExpr(FloatType& type, llvm::APFloat value)
: LiteralExpr(type), mValue(std::move(value))
{}
public:
void print(llvm::raw_ostream& os) const override;
static ExprRef<FloatLiteralExpr> Get(FloatType& type, const llvm::APFloat& value);
llvm::APFloat getValue() const { return mValue; }
FloatType& getType() const {
return static_cast<FloatType&>(mType);
}
static bool classof(const Expr* expr) {
return expr->getKind() == Literal && expr->getType().isFloatType();
}
static bool classof(const Expr& expr) {
return expr.getKind() == Literal && expr.getType().isFloatType();
}
private:
llvm::APFloat mValue;
};
class ArrayLiteralExpr final : public LiteralExpr
{
friend class ExprStorage;
public:
// We cannot use unordered_map here, as we need to provide
// a predictable hash function for this container.
using MappingT = std::map<
ExprRef<LiteralExpr>,
ExprRef<LiteralExpr>
>;
/// Helper class for building array literals
class Builder
{
public:
explicit Builder(ArrayType& type, ExprRef<LiteralExpr> defaultValue)
: mType(type), mElse(defaultValue)
{
assert(mElse != nullptr);
}
Builder& addValue(const ExprRef<LiteralExpr>& index, ExprRef<LiteralExpr> element);
ExprRef<ArrayLiteralExpr> build();
private:
ArrayType& mType;
MappingT mValues;
ExprRef<LiteralExpr> mElse;
};
private:
ArrayLiteralExpr(ArrayType& type, MappingT mapping, ExprRef<LiteralExpr> elze)
: LiteralExpr(type), mMap(std::move(mapping)), mElse(std::move(elze))
{}
public:
void print(llvm::raw_ostream& os) const override;
static ExprRef<ArrayLiteralExpr> Get(
ArrayType& type,
const MappingT& value,
const ExprRef<LiteralExpr>& elze
);
static ExprRef<ArrayLiteralExpr> GetEmpty(
ArrayType& type,
const ExprRef<LiteralExpr>& elze) {
MappingT map;
return Get(type, map, elze);
}
ExprRef<AtomicExpr> getValue(const ExprRef<LiteralExpr>& key) const;
const MappingT& getMap() const { return mMap; }
ExprRef<LiteralExpr> getDefault() const { return mElse; }
ArrayType& getType() const {
return llvm::cast<ArrayType>(mType);
}
static bool classof(const Expr* expr) {
return expr->getKind() == Literal && expr->getType().isArrayType();
}
static bool classof(const Expr& expr) {
return expr.getKind() == Literal && expr.getType().isArrayType();
}
private:
MappingT mMap;
ExprRef<LiteralExpr> mElse;
};
namespace detail
{
template<Type::TypeID TypeID> struct GetLiteralExprTypeHelper {};
template<>
struct GetLiteralExprTypeHelper<Type::BoolTypeID> { using T = BoolLiteralExpr; };
template<>
struct GetLiteralExprTypeHelper<Type::IntTypeID> { using T = IntLiteralExpr; };
template<>
struct GetLiteralExprTypeHelper<Type::BvTypeID> { using T = BvLiteralExpr; };
template<>
struct GetLiteralExprTypeHelper<Type::FloatTypeID> { using T = FloatLiteralExpr; };
} // end namespace detail
/**
* Helper class that returns the literal expression type for a given Gazer type.
*/
template<Type::TypeID TypeID>
struct GetLiteralExprType
{
using T = typename detail::GetLiteralExprTypeHelper<TypeID>::T;
};
}
#endif
|
ftsrg/gazer | include/gazer/Verifier/VerificationAlgorithm.h | //==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_VERIFIER_VERIFICATIONALGORITHM_H
#define GAZER_VERIFIER_VERIFICATIONALGORITHM_H
#include "gazer/Core/Decl.h"
#include "gazer/Trace/VerificationResult.h"
namespace gazer
{
class Location;
class AutomataSystem;
using CfaTraceBuilder = TraceBuilder<Location*, std::vector<VariableAssignment>>;
class VerificationAlgorithm
{
public:
virtual std::unique_ptr<VerificationResult> check(
AutomataSystem& system,
CfaTraceBuilder& traceBuilder
) = 0;
virtual ~VerificationAlgorithm() = default;
};
}
#endif
|
ftsrg/gazer | include/gazer/LLVM/Automaton/ModuleToAutomata.h | //==- ModuleToAutomata.h ----------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_MODULETOAUTOMATA_H
#define GAZER_MODULETOAUTOMATA_H
#include "gazer/Automaton/Cfa.h"
#include "gazer/LLVM/Memory/MemoryObject.h"
#include "gazer/LLVM/Memory/ValueOrMemoryObject.h"
#include "gazer/LLVM/LLVMFrontendSettings.h"
#include "gazer/LLVM/LLVMTraceBuilder.h"
#include <llvm/Pass.h>
#include <variant>
namespace llvm
{
class Value;
class Loop;
class LoopInfo;
}
namespace gazer::llvm2cfa
{
class GenerationContext;
} // end namespace gazer::llvm2cfa
namespace gazer
{
class MemoryModel;
// Extension points
//==------------------------------------------------------------------------==//
// If a client (such as a memory model) wishes to hook into the CFA generation
// process, it may do so through extension points. Each hook will receive one
// of these extension point objects at the time they are called.
namespace llvm2cfa
{
using LoopInfoFuncTy = std::function<llvm::LoopInfo*(const llvm::Function*)>;
class CfaGenInfo;
class ExtensionPoint
{
protected:
ExtensionPoint(CfaGenInfo& genInfo)
: mGenInfo(genInfo)
{}
public:
ExtensionPoint(const ExtensionPoint&) = default;
ExtensionPoint& operator=(const ExtensionPoint&) = delete;
const Cfa& getCfa() const;
llvm::Loop* getSourceLoop() const;
llvm::Function* getSourceFunction() const;
llvm::Function* getParent() const;
bool isEntryProcedure() const;
protected:
CfaGenInfo& mGenInfo;
};
/// An extension point which may only query variables from the target automaton.
class AutomatonInterfaceExtensionPoint : public ExtensionPoint
{
public:
explicit AutomatonInterfaceExtensionPoint(CfaGenInfo& genInfo)
: ExtensionPoint(genInfo)
{}
Variable* getVariableFor(ValueOrMemoryObject val);
Variable* getInputVariableFor(ValueOrMemoryObject val);
Variable* getOutputVariableFor(ValueOrMemoryObject val);
};
/// This extension can be used to insert additional variables into the CFA at the
/// beginning of the generation process.
class VariableDeclExtensionPoint : public AutomatonInterfaceExtensionPoint
{
public:
VariableDeclExtensionPoint(CfaGenInfo& genInfo)
: AutomatonInterfaceExtensionPoint(genInfo)
{}
Variable* createInput(ValueOrMemoryObject val, Type& type, const std::string& suffix = "");
Variable* createLocal(ValueOrMemoryObject val, Type& type, const std::string& suffix = "");
/// \brief Creates an input variable which will be handled according to the
/// transformation rules used for PHI nodes.
Variable* createPhiInput(ValueOrMemoryObject val, Type& type, const std::string& suffix = "");
/// Marks an already declared variable as output.
void markOutput(ValueOrMemoryObject val, Variable* variable);
};
/// Variable declaration extension point for loops.
class LoopVarDeclExtensionPoint : public VariableDeclExtensionPoint
{
public:
using VariableDeclExtensionPoint::VariableDeclExtensionPoint;
/// Marks an already declared variable as a loop output, and creates an auxiliary
/// variable to hold the output value.
void createLoopOutput(
ValueOrMemoryObject val, Variable* output, const llvm::Twine& suffix = "_out");
};
/// An extension point which can access the representations of already-translated instructions
/// and insert assignments in the current transformation step.
class GenerationStepExtensionPoint : public AutomatonInterfaceExtensionPoint
{
public:
using AutomatonInterfaceExtensionPoint::AutomatonInterfaceExtensionPoint;
/// Creates a new local variable into the current automaton.
Variable* createAuxiliaryVariable(const std::string& name, Type& type);
virtual ExprPtr getAsOperand(ValueOrMemoryObject val) = 0;
/// Attempts to inline and eliminate a given variable from the CFA.
virtual bool tryToEliminate(ValueOrMemoryObject val, Variable* variable, const ExprPtr& expr) = 0;
virtual void insertAssignment(Variable* variable, const ExprPtr& value) = 0;
virtual void splitCurrentTransition(const ExprPtr& guard) = 0;
};
} // end namespace llvm2cfa
// Traceability
//==------------------------------------------------------------------------==//
/// Provides a mapping between CFA locations/variables and LLVM values.
class CfaToLLVMTrace
{
friend class llvm2cfa::GenerationContext;
public:
enum LocationKind { Location_Unknown, Location_Entry, Location_Exit };
struct BlockToLocationInfo
{
const llvm::BasicBlock* block;
LocationKind kind;
};
struct ValueMappingInfo
{
llvm::DenseMap<ValueOrMemoryObject, ExprPtr> values;
};
BlockToLocationInfo getBlockFromLocation(Location* loc) {
return mLocationsToBlocks.lookup(loc);
}
ExprPtr getExpressionForValue(const Cfa* parent, const llvm::Value* value);
Variable* getVariableForValue(const Cfa* parent, const llvm::Value* value);
private:
llvm::DenseMap<const Location*, BlockToLocationInfo> mLocationsToBlocks;
llvm::DenseMap<const Cfa*, ValueMappingInfo> mValueMaps;
};
// LLVM pass
//==------------------------------------------------------------------------==//
/// ModuleToAutomataPass - translates an LLVM IR module into an automata system.
class ModuleToAutomataPass : public llvm::ModulePass
{
public:
static char ID;
ModuleToAutomataPass(GazerContext& context, LLVMFrontendSettings& settings)
: ModulePass(ID), mContext(context), mSettings(settings)
{}
void getAnalysisUsage(llvm::AnalysisUsage& au) const override;
bool runOnModule(llvm::Module& module) override;
llvm::StringRef getPassName() const override {
return "Module to automata transformation";
}
AutomataSystem& getSystem() { return *mSystem; }
CfaToLLVMTrace& getTraceInfo() { return mTraceInfo; }
private:
std::unique_ptr<AutomataSystem> mSystem;
CfaToLLVMTrace mTraceInfo;
GazerContext& mContext;
LLVMFrontendSettings& mSettings;
};
class SpecialFunctions;
std::unique_ptr<AutomataSystem> translateModuleToAutomata(
llvm::Module& module,
const LLVMFrontendSettings& settings,
llvm2cfa::LoopInfoFuncTy loopInfos,
GazerContext& context,
MemoryModel& memoryModel,
CfaToLLVMTrace& blockEntries,
const SpecialFunctions* specialFunctions = nullptr
);
llvm::Pass* createCfaPrinterPass();
llvm::Pass* createCfaViewerPass();
}
#endif //GAZER_MODULETOAUTOMATA_H
|
ftsrg/gazer | test/theta/verif/base/loops2_fail.c | // RUN: %theta -memory=havoc "%s" | FileCheck "%s"
// CHECK: Verification FAILED
#include <assert.h>
extern int __VERIFIER_nondet_int(void);
int main(void)
{
int i = 0;
int n = __VERIFIER_nondet_int();
int sum = 0;
while (i < n) {
int j = 0;
int x = 0;
while (j < n) {
x = (x + 1) * j;
++j;
}
sum = sum + i + x;
++i;
}
assert(sum != 0);
return 0;
} |
ftsrg/gazer | test/verif/regression/inline_globals_error_fail.c | // RUN: %bmc -bound 1 -inline=all -trace "%s" | FileCheck "%s"
// CHECK: Verification FAILED
// Invalid handling of removed global variables caused this test to crash during trace generation.
int b;
void __VERIFIER_error();
int a();
int main() {
int c = a();
b = 0;
if (c)
b = 1;
__VERIFIER_error();
}
|
ftsrg/gazer | test/verif/regression/memoryssa_one_def_multiple_uses.c | // RUN: %bmc -memory=flat "%s" | FileCheck "%s"
// CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}}
int a() { return 0; }
int main() {
while (1) {
a();
a();
}
}
|
ftsrg/gazer | test/verif/base/separate_assert.c | // RUN: %bmc "%s" | FileCheck "%s"
// CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}}
void a(b) {
if (!b)
__VERIFIER_error();
}
main() { a(70789); }
|
ftsrg/gazer | test/verif/floats/double_mul_fail.c | // RUN: %bmc -bound 1 "%s" | FileCheck "%s"
// CHECK: Verification FAILED
extern void __VERIFIER_error(void);
extern double __VERIFIER_nondet_double(void);
int main(void)
{
double x = __VERIFIER_nondet_double();
double y = __VERIFIER_nondet_double();
double mul1 = x * x * y;
double mul2 = x * (x * y);
if (mul1 != mul2) {
__VERIFIER_error();
}
return 0;
}
|
ftsrg/gazer | include/gazer/Trace/WitnessWriter.h | <reponame>ftsrg/gazer
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_WITNESS_WITNESS_H
#define GAZER_WITNESS_WITNESS_H
#include <string>
#include <memory>
#include "gazer/Trace/TraceWriter.h"
#include "gazer/Trace/Trace.h"
#include <llvm/Support/raw_ostream.h>
#include <llvm/IR/DebugLoc.h>
#include <llvm/IR/DebugInfoMetadata.h>
namespace gazer
{
// Although it sounds like that this class should be more closely related to the ViolationWitnessWriter, they are not,
// as this one only outputs a hardcoded empty correctness witness (for now) and has nothing to do with traces
class CorrectnessWitnessWriter
{
public:
static std::string SourceFileName;
CorrectnessWitnessWriter(llvm::raw_ostream& os, std::string hash)
: mOS(os), mHash(hash) {}
void outputWitness();
private:
llvm::raw_ostream& mOS;
std::string mHash;
};
class ViolationWitnessWriter : public TraceWriter
{
public:
static std::string SourceFileName;
ViolationWitnessWriter(llvm::raw_ostream& os, std::string hash)
: TraceWriter(os), mHash(hash) {}
// After creating the WitnessWriter, the witness should be initialized, written and then closed
void initializeWitness();
void closeWitness();
private:
void visit(AssignTraceEvent& event) override;
void visit(FunctionEntryEvent& event) override;
void visit(FunctionReturnEvent& event) override;
void visit(FunctionCallEvent& event) override;
void visit(UndefinedBehaviorEvent& event) override;
unsigned int mNodeCounter = 0; // the values is always the id of the next node, that hasn't been created yet
bool mInProgress = false; // true, if witness is initialized, but not closed
const std::string mHash; // The hash of the source file
void createNode(bool violation = false);
void openEdge();
void closeEdge();
void writeLocation(gazer::LocationInfo location); // should be used in edges
};
}
#endif |
ftsrg/gazer | include/gazer/Support/SExpr.h | <reponame>ftsrg/gazer
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_SUPPORT_SEXPR_H
#define GAZER_SUPPORT_SEXPR_H
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/Casting.h>
#include <variant>
#include <vector>
namespace gazer::sexpr
{
class Atom;
class List;
class Value
{
using ListTy = std::vector<Value*>;
using VariantTy = std::variant<std::string, ListTy>;
public:
explicit Value(std::string str)
: mData(str)
{}
explicit Value(std::vector<Value*> vec)
: mData(std::move(vec))
{}
Value(const Value&) = delete;
Value& operator=(const Value&) = delete;
[[nodiscard]] bool isAtom() const { return mData.index() == 0; }
[[nodiscard]] bool isList() const { return mData.index() == 1; }
[[nodiscard]] llvm::StringRef asAtom() const { return std::get<0>(mData); }
[[nodiscard]] const std::vector<Value*>& asList() const { return std::get<1>(mData); }
bool operator==(const Value& rhs) const;
void print(llvm::raw_ostream& os) const;
~Value();
private:
VariantTy mData;
};
/// Creates a simple SExpr atom and returns a pointer to it.
/// It is the caller's responsibility to free the resulting SExpr node.
[[nodiscard]] Value* atom(llvm::StringRef data);
/// Creates an SExpr list and returns a pointer to it.
/// It is the caller's responsibility to free the resulting SExpr node.
[[nodiscard]] Value* list(std::vector<Value*> data);
std::unique_ptr<Value> parse(llvm::StringRef input);
}
#endif
|
ftsrg/gazer | tools/gazer-theta/lib/ThetaVerifier.h | //==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_TOOLS_GAZERTHETA_LIB_THETAVERIFIER_H
#define GAZER_TOOLS_GAZERTHETA_LIB_THETAVERIFIER_H
#include "gazer/Automaton/Cfa.h"
#include "gazer/Verifier/VerificationAlgorithm.h"
namespace gazer::theta
{
struct ThetaSettings
{
// Environment
std::string thetaCfaPath;
std::string thetaLibPath;
unsigned timeout = 0;
std::string modelPath;
bool stackTrace = false;
// Algorithm settings
std::string domain;
std::string refinement;
std::string search;
std::string precGranularity;
std::string predSplit;
std::string encoding;
std::string maxEnum;
std::string initPrec;
std::string pruneStrategy;
};
class ThetaVerifier : public VerificationAlgorithm
{
public:
explicit ThetaVerifier(ThetaSettings settings)
: mSettings(std::move(settings))
{}
std::unique_ptr<VerificationResult> check(AutomataSystem& system, CfaTraceBuilder& traceBuilder) override;
private:
ThetaSettings mSettings;
};
} // end namespace gazer
#endif
|
ftsrg/gazer | include/gazer/Core/Expr/ExprEvaluator.h | //==- ExprEvaluator.h - Expression evaluation -------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_CORE_EXPR_EXPREVALUATOR_H
#define GAZER_CORE_EXPR_EXPREVALUATOR_H
#include "gazer/Core/Expr/ExprWalker.h"
#include "gazer/Core/Expr/ExprBuilder.h"
#include "gazer/Core/Valuation.h"
namespace gazer
{
/// Interface for evaluating expressions.
class ExprEvaluator
{
public:
virtual ExprRef<AtomicExpr> evaluate(const ExprPtr& expr) = 0;
};
/// Base class for expression evaluation implementations.
/// This abstract class provides all methods to evaluate an expression, except for
/// the means of acquiring the value of a variable.
class ExprEvaluatorBase : public ExprEvaluator, private ExprWalker<ExprEvaluatorBase, ExprRef<AtomicExpr>>
{
friend class ExprWalker<ExprEvaluatorBase, ExprRef<AtomicExpr>>;
public:
ExprRef<AtomicExpr> evaluate(const ExprPtr& expr) override {
return this->walk(expr);
}
protected:
virtual ExprRef<AtomicExpr> getVariableValue(Variable& variable) = 0;
private:
ExprRef<AtomicExpr> visitExpr(const ExprPtr& expr);
// Nullary
ExprRef<AtomicExpr> visitUndef(const ExprRef<UndefExpr>& expr);
ExprRef<AtomicExpr> visitLiteral(const ExprRef<AtomicExpr>& expr);
ExprRef<AtomicExpr> visitVarRef(const ExprRef<VarRefExpr>& expr);
// Unary
ExprRef<AtomicExpr> visitNot(const ExprRef<NotExpr>& expr);
ExprRef<AtomicExpr> visitZExt(const ExprRef<ZExtExpr>& expr);
ExprRef<AtomicExpr> visitSExt(const ExprRef<SExtExpr>& expr);
ExprRef<AtomicExpr> visitExtract(const ExprRef<ExtractExpr>& expr);
ExprRef<AtomicExpr> visitBvConcat(const ExprRef<BvConcatExpr>& expr);
// Binary
ExprRef<AtomicExpr> visitAdd(const ExprRef<AddExpr>& expr);
ExprRef<AtomicExpr> visitSub(const ExprRef<SubExpr>& expr);
ExprRef<AtomicExpr> visitMul(const ExprRef<MulExpr>& expr);
ExprRef<AtomicExpr> visitDiv(const ExprRef<DivExpr>& expr);
ExprRef<AtomicExpr> visitMod(const ExprRef<ModExpr>& expr);
ExprRef<AtomicExpr> visitRem(const ExprRef<RemExpr>& expr);
ExprRef<AtomicExpr> visitBvSDiv(const ExprRef<BvSDivExpr>& expr);
ExprRef<AtomicExpr> visitBvUDiv(const ExprRef<BvUDivExpr>& expr);
ExprRef<AtomicExpr> visitBvSRem(const ExprRef<BvSRemExpr>& expr);
ExprRef<AtomicExpr> visitBvURem(const ExprRef<BvURemExpr>& expr);
ExprRef<AtomicExpr> visitShl(const ExprRef<ShlExpr>& expr);
ExprRef<AtomicExpr> visitLShr(const ExprRef<LShrExpr>& expr);
ExprRef<AtomicExpr> visitAShr(const ExprRef<AShrExpr>& expr);
ExprRef<AtomicExpr> visitBvAnd(const ExprRef<BvAndExpr>& expr);
ExprRef<AtomicExpr> visitBvOr(const ExprRef<BvOrExpr>& expr);
ExprRef<AtomicExpr> visitBvXor(const ExprRef<BvXorExpr>& expr);
// Logic
ExprRef<AtomicExpr> visitAnd(const ExprRef<AndExpr>& expr);
ExprRef<AtomicExpr> visitOr(const ExprRef<OrExpr>& expr);
ExprRef<AtomicExpr> visitImply(const ExprRef<ImplyExpr>& expr);
// Compare
ExprRef<AtomicExpr> visitEq(const ExprRef<EqExpr>& expr);
ExprRef<AtomicExpr> visitNotEq(const ExprRef<NotEqExpr>& expr);
ExprRef<AtomicExpr> visitLt(const ExprRef<LtExpr>& expr);
ExprRef<AtomicExpr> visitLtEq(const ExprRef<LtEqExpr>& expr);
ExprRef<AtomicExpr> visitGt(const ExprRef<GtExpr>& expr);
ExprRef<AtomicExpr> visitGtEq(const ExprRef<GtEqExpr>& expr);
ExprRef<AtomicExpr> visitBvSLt(const ExprRef<BvSLtExpr>& expr);
ExprRef<AtomicExpr> visitBvSLtEq(const ExprRef<BvSLtEqExpr>& expr);
ExprRef<AtomicExpr> visitBvSGt(const ExprRef<BvSGtExpr>& expr);
ExprRef<AtomicExpr> visitBvSGtEq(const ExprRef<BvSGtEqExpr>& expr);
ExprRef<AtomicExpr> visitBvULt(const ExprRef<BvULtExpr>& expr);
ExprRef<AtomicExpr> visitBvULtEq(const ExprRef<BvULtEqExpr>& expr);
ExprRef<AtomicExpr> visitBvUGt(const ExprRef<BvUGtExpr>& expr);
ExprRef<AtomicExpr> visitBvUGtEq(const ExprRef<BvUGtEqExpr>& expr);
// Floating-point queries
ExprRef<AtomicExpr> visitFIsNan(const ExprRef<FIsNanExpr>& expr);
ExprRef<AtomicExpr> visitFIsInf(const ExprRef<FIsInfExpr>& expr);
// Floating-point arithmetic
ExprRef<AtomicExpr> visitFAdd(const ExprRef<FAddExpr>& expr);
ExprRef<AtomicExpr> visitFSub(const ExprRef<FSubExpr>& expr);
ExprRef<AtomicExpr> visitFMul(const ExprRef<FMulExpr>& expr);
ExprRef<AtomicExpr> visitFDiv(const ExprRef<FDivExpr>& expr);
// Floating-point compare
ExprRef<AtomicExpr> visitFEq(const ExprRef<FEqExpr>& expr);
ExprRef<AtomicExpr> visitFGt(const ExprRef<FGtExpr>& expr);
ExprRef<AtomicExpr> visitFGtEq(const ExprRef<FGtEqExpr>& expr);
ExprRef<AtomicExpr> visitFLt(const ExprRef<FLtExpr>& expr);
ExprRef<AtomicExpr> visitFLtEq(const ExprRef<FLtEqExpr>& expr);
// Floating-point casts
ExprRef<AtomicExpr> visitFCast(const ExprRef<FCastExpr>& expr);
ExprRef<AtomicExpr> visitSignedToFp(const ExprRef<SignedToFpExpr>& expr);
ExprRef<AtomicExpr> visitUnsignedToFp(const ExprRef<UnsignedToFpExpr>& expr);
ExprRef<AtomicExpr> visitFpToSigned(const ExprRef<FpToSignedExpr>& expr);
ExprRef<AtomicExpr> visitFpToUnsigned(const ExprRef<FpToUnsignedExpr>& expr);
ExprRef<AtomicExpr> visitFpToBv(const ExprRef<FpToBvExpr>& expr);
ExprRef<AtomicExpr> visitBvToFp(const ExprRef<BvToFpExpr>& expr);
// Ternary
ExprRef<AtomicExpr> visitSelect(const ExprRef<SelectExpr>& expr);
// Arrays
ExprRef<AtomicExpr> visitArrayRead(const ExprRef<ArrayReadExpr>& expr);
ExprRef<AtomicExpr> visitArrayWrite(const ExprRef<ArrayWriteExpr>& expr);
};
/// Evaluates expressions based on a Valuation object
class ValuationExprEvaluator : public ExprEvaluatorBase
{
public:
explicit ValuationExprEvaluator(const Valuation& valuation)
: mValuation(valuation)
{}
protected:
ExprRef<AtomicExpr> getVariableValue(Variable& variable) override;
private:
const Valuation& mValuation;
};
}
#endif |
ftsrg/gazer | test/portfolio/zerodiv_example_finish_all.c | <reponame>ftsrg/gazer
// RUN: %portfolio -c "%S"/SVComp_finish_all_configuration.yml -l minimal -t "%s" -o /tmp | FileCheck "%s"
// CHECK: Result of bmc-inline: Verification FAILED.
// CHECK-NEXT: Result of bmc-inline-test-harness: Test harness SUCCESSFUL WITNESS
// CHECK: Result of theta-expl: Verification FAILED.
// CHECK-NEXT: Result of theta-expl-test-harness: Test harness SUCCESSFUL WITNESS
// CHECK: Result of theta-pred: Verification FAILED.
// CHECK-NEXT: Result of theta-pred-test-harness: Test harness SUCCESSFUL WITNESS
#include <stdio.h>
extern int ioread32(void);
int main(void) {
int k = ioread32();
int i = 0;
int j = k + 5;
while (i < 3) {
i = i + 1;
j = j + 3;
}
k = k / (i - j);
printf("%d\n", k);
return 0;
}
|
ftsrg/gazer | include/gazer/Support/Stopwatch.h | //==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_SUPPORT_STOPWATCH_H
#define GAZER_SUPPORT_STOPWATCH_H
#include <llvm/Support/Chrono.h>
namespace gazer
{
/// Simple Stopwatch class for measuring execution times.
template<
class TimeUnit = std::chrono::milliseconds,
class Clock = std::chrono::high_resolution_clock
>
class Stopwatch
{
public:
Stopwatch()
: mStarted(Clock::now()), mStopped(Clock::now()), mRunning(false)
{}
public:
void start()
{
if (!mRunning) {
mStarted = Clock::now();
mRunning = true;
}
}
void stop()
{
if (mRunning) {
mStopped = Clock::now();
mRunning = false;
}
}
void reset()
{
mRunning = false;
mStopped = mStarted;
}
TimeUnit elapsed()
{
if (mRunning) {
return std::chrono::duration_cast<TimeUnit>(Clock::now() - mStarted);
}
return std::chrono::duration_cast<TimeUnit>(mStopped - mStarted);
}
void format(llvm::raw_ostream& os, llvm::StringRef style = "")
{
auto tu = elapsed();
llvm::format_provider<TimeUnit>::format(tu, os, style);
}
private:
std::chrono::time_point<Clock> mStarted;
std::chrono::time_point<Clock> mStopped;
bool mRunning;
};
}
#endif
|
ftsrg/gazer | test/theta/verif/memory/pointers1.c | // RUN: %theta "%s" | FileCheck "%s"
// CHECK: Verification SUCCESSFUL
int __VERIFIER_nondet_int(void);
void __VERIFIER_error(void) __attribute__((__noreturn__));
void make_symbolic(void* ptr);
int a, b;
int main(void)
{
int* pA = &a;
int* pB = &b;
a = __VERIFIER_nondet_int();
b = a;
if (*pA != *pB) {
__VERIFIER_error();
}
return 0;
} |
ftsrg/gazer | include/gazer/LLVM/LLVMFrontendSettings.h | <reponame>ftsrg/gazer
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_LLVM_LLVMFRONTENDSETTINGS_H
#define GAZER_LLVM_LLVMFRONTENDSETTINGS_H
#include <string>
namespace llvm
{
class raw_ostream;
class Module;
class Function;
} // namespace llvm
namespace gazer
{
enum class InlineLevel
{
Off, ///< Do not inline procedures
Default, ///< Inline non-recursive, used-only-once procedures
All ///< Inline all non-recursive procedures
};
enum class IntRepresentation
{
BitVectors, ///< Use bitvectors to represent integer types.
Integers ///< Use the arithmetic integer type to represent integers.
};
enum class FloatRepresentation
{
Fpa, ///< Use floating-point bitvectors to represent floats.
Real, ///< Approximate floats using rational types.
Undef ///< Use undef's for float operations.
};
enum class LoopRepresentation
{
Recursion, ///< Represent loops as recursive functions.
Cycle ///< Represent loops as cycles.
};
enum class ElimVarsLevel
{
Off, ///< Do not try to eliminate variables
Normal, ///< Inline variables which have only one use
Aggressive ///< Inline all suitable variables
};
enum class MemoryModelSetting
{
Havoc,
Flat
};
class LLVMFrontendSettings
{
public:
LLVMFrontendSettings() = default;
LLVMFrontendSettings(const LLVMFrontendSettings&) = delete;
LLVMFrontendSettings& operator=(const LLVMFrontendSettings&) = delete;
LLVMFrontendSettings(LLVMFrontendSettings&&) = default;
LLVMFrontendSettings& operator=(LLVMFrontendSettings&&) = default;
public:
// Traceability
bool trace = false;
std::string witness;
std::string hash;
std::string testHarnessFile;
// LLVM transformations
InlineLevel inlineLevel = InlineLevel::Default;
bool inlineGlobals = false;
bool optimize = true;
bool liftAsserts = true;
bool slicing = true;
// Checks
std::string checks = "";
// IR translation
ElimVarsLevel elimVars = ElimVarsLevel::Off;
LoopRepresentation loops = LoopRepresentation::Recursion;
IntRepresentation ints = IntRepresentation::BitVectors;
FloatRepresentation floats = FloatRepresentation::Fpa;
bool simplifyExpr = true;
bool strict = false;
std::string function = "main";
// Memory models
bool debugDumpMemorySSA = false;
MemoryModelSetting memoryModel = MemoryModelSetting::Flat;
public:
/// Returns true if the current settings can be applied to the given module.
bool validate(const llvm::Module& module, llvm::raw_ostream& os) const;
llvm::Function* getEntryFunction(const llvm::Module& module) const;
bool isElimVarsOff() const { return elimVars == ElimVarsLevel::Off; }
bool isElimVarsNormal() const { return elimVars == ElimVarsLevel::Normal; }
bool isElimVarsAggressive() const { return elimVars == ElimVarsLevel::Aggressive; }
public:
static LLVMFrontendSettings initFromCommandLine();
std::string toString() const;
};
} // end namespace gazer
#endif
|
ftsrg/gazer | test/theta/verif/base/separate_assert.c | <gh_stars>1-10
// RUN: %theta -memory=havoc "%s" | FileCheck "%s"
// CHECK: Verification SUCCESSFUL
void a(b) {
if (!b)
__VERIFIER_error();
}
main() { a(70789); }
|
ftsrg/gazer | scripts/portfolio/test-tasks/overflow_example.c | #include <stdio.h>
int main(void) {
int k = 2147483643;
k+=5;
printf("%d\n", k);
return 0;
}
|
ftsrg/gazer | test/verif/floats/float_cast_fail.c | // RUN: %bmc -bound 1 "%s" | FileCheck "%s"
// CHECK: Verification FAILED
#include <assert.h>
#include <stdint.h>
float __VERIFIER_nondet_float(void);
uint32_t __VERIFIER_nondet_uint32(void);
int main(void)
{
double x = __VERIFIER_nondet_float();
uint32_t t = __VERIFIER_nondet_uint32();
double f = x * ((double) 1500) * ((float) t);
assert(f != 0);
return 0;
}
|
ftsrg/gazer | test/theta/verif/memory/globals4.c | <reponame>ftsrg/gazer
// RUN: %theta "%s" | FileCheck "%s"
// CHECK: Verification SUCCESSFUL
int __VERIFIER_nondet_int(void);
void __VERIFIER_error(void) __attribute__((__noreturn__));
int a = 1;
int b = 1;
int c = 3;
int main(void)
{
int input = 1;
while (input != 0) {
input = __VERIFIER_nondet_int();
if (input == 1) {
a = a + 1;
}
}
if (a < b) {
__VERIFIER_error();
}
return 0;
}
|
ftsrg/gazer | include/gazer/LLVM/Analysis/PDG.h | //==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_LLVM_ANALYSIS_PDG_H
#define GAZER_LLVM_ANALYSIS_PDG_H
#include <llvm/Analysis/PostDominators.h>
#include <llvm/Pass.h>
#include <memory>
#include <unordered_map>
namespace gazer
{
class PDGNode;
class PDGEdge
{
friend class ProgramDependenceGraph;
public:
enum Kind { Control, DataFlow, Memory };
private:
PDGEdge(PDGNode* source, PDGNode* target, Kind kind)
: mSource(source), mTarget(target), mKind(kind)
{}
PDGEdge(const PDGEdge&) = delete;
PDGEdge& operator=(const PDGEdge&) = delete;
public:
PDGNode* getSource() const { return mSource; }
PDGNode* getTarget() const { return mTarget; }
Kind getKind() const { return mKind; }
private:
PDGNode* mSource;
PDGNode* mTarget;
Kind mKind;
};
class PDGNode
{
friend class ProgramDependenceGraph;
private:
PDGNode(llvm::Instruction* inst)
: mInst(inst)
{}
PDGNode(const PDGNode&) = delete;
PDGNode& operator=(const PDGNode&) = delete;
public:
using edge_iterator = std::vector<PDGEdge*>::iterator;
edge_iterator incoming_begin() { return mIncoming.begin(); }
edge_iterator incoming_end() { return mIncoming.end(); }
llvm::iterator_range<edge_iterator> incoming() {
return llvm::make_range(incoming_begin(), incoming_end());
}
edge_iterator outgoing_begin() { return mOutgoing.begin(); }
edge_iterator outgoing_end() { return mOutgoing.end(); }
llvm::iterator_range<edge_iterator> outgoing() {
return llvm::make_range(outgoing_begin(), outgoing_end());
}
llvm::Instruction* getInstruction() const { return mInst; }
private:
void addIncoming(PDGEdge* edge) { mIncoming.push_back(edge); }
void addOutgoing(PDGEdge* edge) { mOutgoing.push_back(edge); }
private:
llvm::Instruction* mInst;
std::vector<PDGEdge*> mIncoming;
std::vector<PDGEdge*> mOutgoing;
};
class ProgramDependenceGraph final
{
using NodeMapTy = std::unordered_map<llvm::Instruction*, std::unique_ptr<PDGNode>>;
private:
ProgramDependenceGraph(
llvm::Function& function,
std::unordered_map<llvm::Instruction*, std::unique_ptr<PDGNode>> nodes,
std::vector<std::unique_ptr<PDGEdge>> edges
) : mFunction(function), mNodes(std::move(nodes)), mEdges(std::move(edges))
{}
private:
static PDGNode* getNodeFromIterator(NodeMapTy::value_type& pair) {
return &*pair.second;
}
public:
static std::unique_ptr<ProgramDependenceGraph> Create(
llvm::Function& function,
llvm::PostDominatorTree& pdt
);
PDGNode* getNode(llvm::Instruction* inst) const {
return &*mNodes.at(inst);
}
using node_iterator = llvm::mapped_iterator<NodeMapTy::iterator, decltype(&getNodeFromIterator)>;
node_iterator node_begin() { return node_iterator(mNodes.begin(), &getNodeFromIterator); }
node_iterator node_end() { return node_iterator(mNodes.end(), &getNodeFromIterator); }
unsigned node_size() const { return mNodes.size(); }
llvm::Function& getFunction() const { return mFunction; }
void view() const;
private:
llvm::Function& mFunction;
NodeMapTy mNodes;
std::vector<std::unique_ptr<PDGEdge>> mEdges;
};
class ProgramDependenceWrapperPass final : public llvm::FunctionPass
{
public:
static char ID;
public:
ProgramDependenceWrapperPass()
: FunctionPass(ID)
{}
virtual void getAnalysisUsage(llvm::AnalysisUsage& au) const override;
virtual bool runOnFunction(llvm::Function& function) override;
virtual llvm::StringRef getPassName() const override { return "ProgramDependenceWrapperPass"; }
ProgramDependenceGraph& getProgramDependenceGraph() const { return *mResult; }
private:
std::unique_ptr<ProgramDependenceGraph> mResult;
};
llvm::FunctionPass* createProgramDependenceWrapperPass();
}
// Graph traits specialization for PDGs
//===----------------------------------------------------------------------===//
namespace llvm
{
template<>
struct GraphTraits<gazer::ProgramDependenceGraph>
{
using NodeRef = gazer::PDGNode*;
using EdgeRef = gazer::PDGEdge*;
static gazer::PDGNode* GetEdgeTarget(gazer::PDGEdge* edge) {
return edge->getTarget();
}
using ChildIteratorType = llvm::mapped_iterator<
gazer::PDGNode::edge_iterator, decltype(&GetEdgeTarget)
>;
static ChildIteratorType child_begin(NodeRef node) {
return ChildIteratorType(node->outgoing_begin(), &GetEdgeTarget);
}
static ChildIteratorType child_end(NodeRef node) {
return ChildIteratorType(node->outgoing_end(), &GetEdgeTarget);
}
using ChildEdgeIteratorType = gazer::PDGNode::edge_iterator;
static ChildEdgeIteratorType child_edge_begin(NodeRef node) {
return node->outgoing_begin();
}
static ChildEdgeIteratorType child_edge_end(NodeRef node) {
return node->outgoing_end();
}
static NodeRef edge_dest(EdgeRef edge) {
return edge->getTarget();
}
using nodes_iterator = gazer::ProgramDependenceGraph::node_iterator;
static nodes_iterator nodes_begin(gazer::ProgramDependenceGraph& pdg) {
return pdg.node_begin();
}
static nodes_iterator nodes_end(gazer::ProgramDependenceGraph& pdg) {
return pdg.node_end();
}
static unsigned size(const gazer::ProgramDependenceGraph& pdg) {
return pdg.node_size();
}
};
}
#endif |
ftsrg/gazer | include/gazer/LLVM/Transform/BackwardSlicer.h | <gh_stars>1-10
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_LLVM_TRANSFORMS_BACKWARDSLICER_H
#define GAZER_LLVM_TRANSFORMS_BACKWARDSLICER_H
#include "gazer/LLVM/Analysis/PDG.h"
#include <llvm/ADT/SmallVector.h>
#include <functional>
namespace gazer
{
class BackwardSlicer
{
public:
BackwardSlicer(
llvm::Function& function,
std::function<bool(llvm::Instruction*)> criterion
);
/// Slices the given function according to the given criteria.
bool slice();
private:
bool collectRequiredNodes(llvm::DenseSet<llvm::Instruction*>& visited);
void sliceBlocks(
const llvm::DenseSet<llvm::Instruction*>& required,
llvm::SmallVectorImpl<llvm::BasicBlock*>& preservedBlocks
);
void sliceInstructions(llvm::BasicBlock& bb, const llvm::DenseSet<llvm::Instruction*>& required);
private:
llvm::Function& mFunction;
std::function<bool(llvm::Instruction*)> mCriterion;
std::unique_ptr<ProgramDependenceGraph> mPDG;
};
llvm::Pass* createBackwardSlicerPass(std::function<bool(llvm::Instruction*)> criteria);
} // end namespace gazer
#endif |
ftsrg/gazer | include/gazer/Core/Expr/ConstantFolder.h | <reponame>ftsrg/gazer
//==- ConstantFolder.h - Expression constant folding ------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 GAZER_CORE_EXPR_CONSTANTFOLDER_H
#define GAZER_CORE_EXPR_CONSTANTFOLDER_H
#include "gazer/Core/Expr.h"
#include <llvm/ADT/APFloat.h>
namespace gazer
{
class ConstantFolder
{
public:
static ExprPtr Not(const ExprPtr& op);
static ExprPtr ZExt(const ExprPtr& op, BvType& type);
static ExprPtr SExt(const ExprPtr& op, BvType& type);
static ExprPtr Trunc(const ExprPtr& op, BvType& type);
static ExprPtr Extract(const ExprPtr& op, unsigned offset, unsigned width);
//--- Binary ---//
static ExprPtr Add(const ExprPtr& left, const ExprPtr& right);
static ExprPtr Sub(const ExprPtr& left, const ExprPtr& right);
static ExprPtr Mul(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvSDiv(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvUDiv(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvSRem(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvURem(const ExprPtr& left, const ExprPtr& right);
static ExprPtr Shl(const ExprPtr& left, const ExprPtr& right);
static ExprPtr LShr(const ExprPtr& left, const ExprPtr& right);
static ExprPtr AShr(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvAnd(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvOr(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvXor(const ExprPtr& left, const ExprPtr& right);
static ExprPtr And(const ExprVector& vector);
static ExprPtr Or(const ExprVector& vector);
static ExprPtr And(const ExprPtr& left, const ExprPtr& right) {
return And({left, right});
}
static ExprPtr Or(const ExprPtr& left, const ExprPtr& right) {
return Or({left, right});
}
template<class InputIterator>
ExprPtr And(InputIterator begin, InputIterator end) {
return And(ExprVector(begin, end));
}
template<class InputIterator>
ExprPtr Or(InputIterator begin, InputIterator end) {
return Or(ExprVector(begin, end));
}
static ExprPtr Xor(const ExprPtr& left, const ExprPtr& right);
static ExprPtr Imply(const ExprPtr& left, const ExprPtr& right);
static ExprPtr Eq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr NotEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr Lt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr LtEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr Gt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr GtEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvSLt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvSLtEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvSGt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvSGtEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvULt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvULtEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvUGt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr BvUGtEq(const ExprPtr& left, const ExprPtr& right);
//--- Floating point ---//
static ExprPtr FIsNan(const ExprPtr& op);
static ExprPtr FIsInf(const ExprPtr& op);
static ExprPtr FAdd(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm);
static ExprPtr FSub(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm);
static ExprPtr FMul(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm);
static ExprPtr FDiv(const ExprPtr& left, const ExprPtr& right, llvm::APFloat::roundingMode rm);
static ExprPtr FEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr FGt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr FGtEq(const ExprPtr& left, const ExprPtr& right);
static ExprPtr FLt(const ExprPtr& left, const ExprPtr& right);
static ExprPtr FLtEq(const ExprPtr& left, const ExprPtr& right);
//--- Ternary ---//
static ExprPtr Select(const ExprPtr& condition, const ExprPtr& then, const ExprPtr& elze);
};
}
#endif |
ftsrg/gazer | test/verif/regression/abort_after_error_with_impl.c | <filename>test/verif/regression/abort_after_error_with_impl.c
// RUN: %bmc "%s" | FileCheck "%s"
// CHECK: Verification FAILED
extern void abort(void);
void __VERIFIER_error() {
// empty
}
extern int __VERIFIER_nondet_int();
int main() {
int x = __VERIFIER_nondet_int();
if (x) {
__VERIFIER_error();
abort();
}
return 0;
}
|
ftsrg/gazer | include/gazer/Support/Compiler.h | <reponame>ftsrg/gazer
//==-------------------------------------------------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 An extension to the functionality provided by LLVM's Compiler.h
//
//===----------------------------------------------------------------------===//
#include <llvm/Support/Compiler.h>
// These macros may be used to disable the leak sanitizer for certain allocations.
#if LLVM_ADDRESS_SANITIZER_BUILD
#include <sanitizer/lsan_interface.h>
#define GAZER_LSAN_DISABLE() __lsan_disable();
#define GAZER_LSAN_ENABLE() __lsan_enable();
#else
#define GAZER_LSAN_DISABLE()
#define GAZER_LSAN_ENABLE()
#endif
|
ftsrg/gazer | test/verif/memory/globals2.c | // RUN: %bmc -bound 1 -no-inline-globals "%s" | FileCheck "%s"
// CHECK: Verification {{(SUCCESSFUL|BOUND REACHED)}}
#include <limits.h>
int __VERIFIER_nondet_int(void);
void __VERIFIER_error(void) __attribute__((__noreturn__));
void __VERIFIER_assume(int expression);
int b = 1;
int main(void)
{
int a = __VERIFIER_nondet_int();
__VERIFIER_assume(a < INT_MAX - 1);
if (a == 0) {
b = a + 1;
} else {
b = a + 2;
}
if (a > b) {
__VERIFIER_error();
}
return 0;
} |
ftsrg/gazer | include/gazer/Automaton/Cfa.h | //==- Cfa.h - Control flow automaton interface ------------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 This file defines classes to represent control flow automata, their
/// locations and transitions.
///
//===----------------------------------------------------------------------===//
#ifndef GAZER_AUTOMATON_CFA_H
#define GAZER_AUTOMATON_CFA_H
#include "gazer/Core/Expr.h"
#include "gazer/ADT/Graph.h"
#include <llvm/ADT/GraphTraits.h>
#include <llvm/ADT/DenseMap.h>
#include <boost/iterator/indirect_iterator.hpp>
namespace gazer
{
class Cfa;
class Transition;
class Location : public GraphNode<Location, Transition>
{
friend class Cfa;
public:
enum LocationKind
{
State,
Error
};
private:
explicit Location(unsigned id, Cfa* parent, LocationKind kind = State)
: mID(id), mCfa(parent), mKind(kind)
{}
public:
Location(const Location&) = delete;
Location& operator=(const Location&) = delete;
unsigned getId() const { return mID; }
bool isError() const { return mKind == Error; }
Cfa* getAutomaton() const { return mCfa; }
private:
unsigned mID;
Cfa* mCfa;
LocationKind mKind;
};
/// A simple transition with a guard or summary expression.
class Transition : public GraphEdge<Location, Transition>
{
friend class Cfa;
public:
enum EdgeKind
{
Edge_Assign, ///< Variable assignment.
Edge_Call, ///< Call into another procedure.
};
protected:
Transition(Location* source, Location* target, ExprPtr expr, EdgeKind kind);
public:
Transition(Transition&) = delete;
Transition& operator=(Transition&) = delete;
ExprPtr getGuard() const { return mExpr; }
EdgeKind getKind() const { return mEdgeKind; }
bool isAssign() const { return mEdgeKind == Edge_Assign; }
bool isCall() const { return mEdgeKind == Edge_Call; }
void print(llvm::raw_ostream& os) const;
virtual ~Transition() = default;
private:
ExprPtr mExpr;
EdgeKind mEdgeKind;
};
/// Represents a (potentially guared) transition with variable assignments.
class AssignTransition final : public Transition
{
friend class Cfa;
protected:
AssignTransition(Location* source, Location* target, ExprPtr guard, std::vector<VariableAssignment> assignments);
public:
using iterator = std::vector<VariableAssignment>::const_iterator;
iterator begin() const { return mAssignments.begin(); }
iterator end() const { return mAssignments.end(); }
size_t getNumAssignments() const { return mAssignments.size(); }
void addAssignment(VariableAssignment assignment) {
mAssignments.push_back(assignment);
}
static bool classof(const Transition* edge) {
return edge->getKind() == Edge_Assign;
}
private:
std::vector<VariableAssignment> mAssignments;
};
/// Represents a (potentially guarded) transition with a procedure call.
class CallTransition final : public Transition
{
friend class Cfa;
protected:
CallTransition(
Location* source, Location* target,
ExprPtr guard,
Cfa* callee,
std::vector<VariableAssignment> inputArgs,
std::vector<VariableAssignment> outputArgs
);
public:
Cfa* getCalledAutomaton() const { return mCallee; }
//-------------------------- Iterator support ---------------------------//
using input_arg_iterator = std::vector<VariableAssignment>::const_iterator;
using output_arg_iterator = std::vector<VariableAssignment>::const_iterator;
input_arg_iterator input_begin() const { return mInputArgs.begin(); }
input_arg_iterator input_end() const { return mInputArgs.end(); }
llvm::iterator_range<input_arg_iterator> inputs() const {
return llvm::make_range(input_begin(), input_end());
}
size_t getNumInputs() const { return mInputArgs.size(); }
output_arg_iterator output_begin() const { return mOutputArgs.begin(); }
output_arg_iterator output_end() const { return mOutputArgs.end(); }
llvm::iterator_range<output_arg_iterator> outputs() const {
return llvm::make_range(output_begin(), output_end());
}
size_t getNumOutputs() const { return mOutputArgs.size(); }
std::optional<VariableAssignment> getInputArgument(Variable& input) const;
std::optional<VariableAssignment> getOutputArgument(Variable& variable) const;
static bool classof(const Transition* edge) {
return edge->getKind() == Edge_Call;
}
private:
Cfa* mCallee;
std::vector<VariableAssignment> mInputArgs;
std::vector<VariableAssignment> mOutputArgs;
};
class AutomataSystem;
/// Represents a control flow automaton.
class Cfa final : public Graph<Location, Transition>
{
friend class AutomataSystem;
private:
Cfa(GazerContext& context, std::string name, AutomataSystem& parent);
public:
Cfa(const Cfa&) = delete;
Cfa& operator=(const Cfa&) = delete;
public:
//===----------------------------------------------------------------------===//
// Locations and edges
Location* createLocation();
Location* createErrorLocation();
AssignTransition* createAssignTransition(
Location* source, Location* target, ExprPtr guard = nullptr, llvm::ArrayRef<VariableAssignment> assignments = {}
);
AssignTransition* createAssignTransition(
Location* source, Location* target, llvm::ArrayRef<VariableAssignment> assignments
) {
return createAssignTransition(source, target, nullptr, assignments);
}
CallTransition* createCallTransition(
Location* source, Location* target, const ExprPtr& guard,
Cfa* callee, llvm::ArrayRef<VariableAssignment> inputArgs, llvm::ArrayRef<VariableAssignment> outputArgs
);
CallTransition* createCallTransition(
Location* source, Location* target,
Cfa* callee, llvm::ArrayRef<VariableAssignment> inputArgs, llvm::ArrayRef<VariableAssignment> outputArgs
);
//===----------------------------------------------------------------------===//
// Variable handling
Variable* createInput(const std::string& name, Type& type);
Variable* createLocal(const std::string& name, Type& type);
/// Marks an already existing variable as an output.
void addOutput(Variable* variable);
void addErrorCode(Location* location, ExprPtr errorCodeExpr);
ExprPtr getErrorFieldExpr(Location* location);
//===----------------------------------------------------------------------===//
// Iterator for error locations
using error_iterator = llvm::SmallDenseMap<Location*, ExprPtr, 1>::const_iterator;
error_iterator error_begin() const { return mErrorFieldExprs.begin(); }
error_iterator error_end() const { return mErrorFieldExprs.end(); }
llvm::iterator_range<error_iterator> errors() const {
return llvm::make_range(error_begin(), error_end());
}
size_t getNumErrors() const { return mErrorFieldExprs.size(); }
// Variable iterators
using var_iterator = boost::indirect_iterator<std::vector<Variable*>::iterator>;
var_iterator input_begin() { return mInputs.begin(); }
var_iterator input_end() { return mInputs.end(); }
llvm::iterator_range<var_iterator> inputs() {
return llvm::make_range(input_begin(), input_end());
}
var_iterator output_begin() { return mOutputs.begin(); }
var_iterator output_end() { return mOutputs.end(); }
llvm::iterator_range<var_iterator> outputs() {
return llvm::make_range(output_begin(), output_end());
}
var_iterator local_begin() { return mLocals.begin(); }
var_iterator local_end() { return mLocals.end(); }
llvm::iterator_range<var_iterator> locals() {
return llvm::make_range(local_begin(), local_end());
}
//===----------------------------------------------------------------------===//
// Others
llvm::StringRef getName() const { return mName; }
Location* getEntry() const { return mEntry; }
Location* getExit() const { return mExit; }
AutomataSystem& getParent() const { return mParent; }
size_t getNumLocations() const { return node_size(); }
size_t getNumTransitions() const { return edge_size(); }
size_t getNumInputs() const { return mInputs.size(); }
size_t getNumOutputs() const { return mOutputs.size(); }
size_t getNumLocals() const { return mLocals.size(); }
/// Returns the index of a given input variable in the input list of this automaton.
size_t getInputNumber(Variable* variable) const;
size_t getOutputNumber(Variable* variable) const;
Variable* findInputByName(llvm::StringRef name) const;
Variable* findLocalByName(llvm::StringRef name) const;
Variable* findOutputByName(llvm::StringRef name) const;
Variable* getInput(size_t i) const { return mInputs[i]; }
Variable* getOutput(size_t i) const { return mOutputs[i]; }
Location* findLocationById(unsigned id);
bool isOutput(Variable* variable) const;
/// View the graph representation of this CFA with the
/// system's default GraphViz viewer.
void view() const;
void print(llvm::raw_ostream& os) const;
void printDeclaration(llvm::raw_ostream& os) const;
//------------------------------ Deletion -------------------------------//
void removeUnreachableLocations();
template<class Predicate>
void removeLocalsIf(Predicate p) {
mLocals.erase(
std::remove_if(mLocals.begin(), mLocals.end(), p),
mLocals.end()
);
}
using Graph::disconnectNode;
using Graph::disconnectEdge;
using Graph::clearDisconnectedElements;
~Cfa();
private:
Variable* createMemberVariable(const std::string& name, Type& type);
Variable* findVariableByName(const std::vector<Variable*>& vec, llvm::StringRef name) const;
private:
std::string mName;
GazerContext& mContext;
AutomataSystem& mParent;
llvm::SmallVector<Location*, 1> mErrorLocations;
llvm::SmallDenseMap<Location*, ExprPtr, 1> mErrorFieldExprs;
std::vector<Variable*> mInputs;
std::vector<Variable*> mOutputs;
std::vector<Variable*> mLocals;
Location* mEntry;
Location* mExit;
llvm::DenseMap<Variable*, std::string> mSymbolNames;
llvm::DenseMap<unsigned, Location*> mLocationNumbers;
Cfa* mParentAutomaton = nullptr;
unsigned mLocationIdx = 0;
unsigned mTmp = 0;
};
/// A system of CFA instances.
class AutomataSystem final
{
public:
explicit AutomataSystem(GazerContext& context);
AutomataSystem(const AutomataSystem&) = delete;
AutomataSystem& operator=(const AutomataSystem&) = delete;
public:
Cfa* createCfa(std::string name);
using iterator = boost::indirect_iterator<std::vector<std::unique_ptr<Cfa>>::iterator>;
using const_iterator = boost::indirect_iterator<std::vector<std::unique_ptr<Cfa>>::const_iterator>;
iterator begin() { return mAutomata.begin(); }
iterator end() { return mAutomata.end(); }
const_iterator begin() const { return mAutomata.begin(); }
const_iterator end() const { return mAutomata.end(); }
GazerContext& getContext() { return mContext; }
size_t getNumAutomata() const { return mAutomata.size(); }
Cfa* getAutomatonByName(llvm::StringRef name) const;
Cfa* getMainAutomaton() const { return mMainAutomaton; }
void setMainAutomaton(Cfa* cfa);
void print(llvm::raw_ostream& os) const;
private:
GazerContext& mContext;
std::vector<std::unique_ptr<Cfa>> mAutomata;
Cfa* mMainAutomaton;
};
inline llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const Transition& transition)
{
transition.print(os);
return os;
}
} // end namespace gazer
// GraphTraits specialization for automata
//-------------------------------------------------------------------------
namespace llvm
{
template<>
struct GraphTraits<gazer::Cfa> :
public GraphTraits<gazer::Graph<gazer::Location, gazer::Transition>>
{
static NodeRef getEntryNode(const gazer::Cfa& cfa) {
return cfa.getEntry();
}
};
template<>
struct GraphTraits<Inverse<gazer::Cfa>> :
public GraphTraits<Inverse<gazer::Graph<gazer::Location, gazer::Transition>>>
{
static NodeRef getEntryNode(Inverse<gazer::Cfa>& cfa) {
return cfa.Graph.getExit();
}
};
template<>
struct GraphTraits<gazer::Location*> :
public GraphTraits<gazer::GraphNode<gazer::Location, gazer::Transition>*>
{};
template<>
struct GraphTraits<Inverse<gazer::Location*>> :
public GraphTraits<Inverse<gazer::GraphNode<gazer::Location, gazer::Transition>*>>
{};
} // end namespace llvm
#endif
|
ftsrg/gazer | test/theta/verif/memory/passbyref3_fail.c | // REQUIRES: memory.burstall
// RUN: %theta "%s" | FileCheck "%s"
// CHECK: Verification FAILED
int __VERIFIER_nondet_int(void);
void __VERIFIER_error(void) __attribute__((__noreturn__));
void make_symbolic(void* ptr);
int main(void)
{
int a = __VERIFIER_nondet_int();
make_symbolic(&a);
if (a == 0) {
__VERIFIER_error();
}
return 0;
}
|
ftsrg/gazer | include/gazer/Verifier/BoundedModelChecker.h | //==- BoundedModelChecker.h - BMC engine interface --------------*- C++ -*--==//
//
// Copyright 2019 Contributors to the Gazer project
//
// 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 This file declares the BoundedModelChecker verification backend,
/// along with its possible configuration settings.
///
//===----------------------------------------------------------------------===//
#ifndef GAZER_VERIFIER_BOUNDEDMODELCHECKER_H
#define GAZER_VERIFIER_BOUNDEDMODELCHECKER_H
#include "gazer/Verifier/VerificationAlgorithm.h"
namespace gazer
{
class Location;
class SolverFactory;
class AutomataSystem;
struct BmcSettings
{
// Environment
bool trace;
// Debug
bool debugDumpCfa;
bool dumpFormula;
bool dumpSolver;
bool dumpSolverModel;
bool printSolverStats;
// Algorithm settings
unsigned maxBound;
unsigned eagerUnroll;
bool simplifyExpr;
};
class BoundedModelChecker : public VerificationAlgorithm
{
public:
explicit BoundedModelChecker(SolverFactory& solverFactory, BmcSettings settings)
: mSolverFactory(solverFactory), mSettings(settings)
{}
std::unique_ptr<VerificationResult> check(
AutomataSystem& system,
CfaTraceBuilder& traceBuilder
) override;
private:
SolverFactory& mSolverFactory;
BmcSettings mSettings;
};
}
#endif
|
ftsrg/gazer | test/verif/regression/constant_gv_fail.c | // RUN: %bmc "%s" | FileCheck "%s"
// CHECK: Verification FAILED
#include <assert.h>
int main(void) { assert(0); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.