<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_mpipl_chip_cleanup.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file   p9_mpipl_chip_cleanup.C
/// @brief  To enable MCD recovery
///
// *HWP HWP OWNER: Joshua Hannan            Email: jlhannan@us.ibm.com
// *HWP FW  OWNER: Thi Tran                 Email: thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: FSP/HB
//
//  Additional Note(s):
//
//   Checks to see if MCD recovery is already enabled by checking bit 0 of the
//   even and odd MCD config registers, which is the recovery enable bit.
//   If the bits are 0, then the procedure enables them to start MCD recovery
//
//
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_mpipl_chip_cleanup.H>
#include <p9_misc_scom_addresses.H>
#include <p9_misc_scom_addresses_fld.H>

extern "C"
{
    //------------------------------------------------------------------------------
    // Function definitions
    //------------------------------------------------------------------------------

    //------------------------------------------------------------------------------
    // name: p9_mpipl_chip_cleanup
    //------------------------------------------------------------------------------
    // purpose:
    // To enable MCD recovery
    //
    // Note: PHBs are left in ETU reset state after executing proc_mpipl_nest_cleanup, which runs before this procedure.  PHYP releases PHBs from ETU reset post HostBoot IPL.
    //
    // SCOM regs
    //
    // 1) MCD even recovery control register
    // PU_BANK0_MCD_REC (SCOM)
    // bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
    //
    // 2) MCD odd recovery control register
    // PU_MCD1_BANK0_MCD_REC (SCOM)
    // bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
    //
    //------------------------------------------------------------------------------
    fapi2::ReturnCode p9_mpipl_chip_cleanup(fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
    {
        const uint8_t MAX_MCD_DIRS = 2; //Max of 2 MCD Directories (even and odd)
        fapi2::buffer<uint64_t> fsi_data[MAX_MCD_DIRS];
        const uint64_t ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[MAX_MCD_DIRS] =
        {
            PU_BANK0_MCD_REC, //MCD even recovery control register address
            PU_MCD1_BANK0_MCD_REC  //MCD odd recovery control register address
        };
        const char* ARY_MCD_DIR_STRS[MAX_MCD_DIRS] =
        {
            "Even", //Ptr to char string "Even" for even MCD
            "Odd"   //Ptr to char string "Odd" for odd MCD
        };

        //Verify MCD recovery was previously disabled for even and odd slices
        //If not, this is an error condition
        for (uint8_t counter = 0; counter < MAX_MCD_DIRS; counter++)
        {
            FAPI_DBG("Verifying MCD %s Recovery is disabled", ARY_MCD_DIR_STRS[counter]);
            FAPI_TRY(fapi2::getScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
                     "getScom error veryfing that MCD recovery is disabled");

            FAPI_ASSERT(!fsi_data[counter].getBit<PU_BANK0_MCD_REC_ENABLE>(),
                        fapi2::P9_MPIPL_CHIP_CLEANUP_MCD_NOT_DISABLED().set_TARGET(i_target).set_ADDRESS(
                            ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter]).set_DATA(fsi_data[counter]), "MCD recovery not disabled as expected");
        }

        //Assert bit 0 of MCD Recovery Ctrl regs to enable MCD recovery
        for (int counter = 0; counter < MAX_MCD_DIRS; counter++)
        {
            FAPI_DBG("Enabling MCD %s Recovery", ARY_MCD_DIR_STRS[counter]);

            //Assert bit 0 of MCD Even or Odd Recovery Control reg to enable recovery
            fsi_data[counter].setBit<PU_BANK0_MCD_REC_ENABLE>();

            //Write data to MCD Even or Odd Recovery Control reg
            FAPI_TRY(fapi2::putScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
                     "putScom error assert bit 0 of MCD recovery control register");
        }

    fapi_try_exit:
        FAPI_DBG("Exiting...");
        return fapi2::current_err;
    }

} // extern "C"
<commit_msg>HW386071 defect workaround<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_mpipl_chip_cleanup.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file   p9_mpipl_chip_cleanup.C
/// @brief  To enable MCD recovery
///
// *HWP HWP OWNER: Joshua Hannan            Email: jlhannan@us.ibm.com
// *HWP FW  OWNER: Thi Tran                 Email: thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: FSP/HB
//
//  Additional Note(s):
//
//   Checks to see if MCD recovery is already enabled by checking bit 0 of the
//   even and odd MCD config registers, which is the recovery enable bit.
//   If the bits are 0, then the procedure enables them to start MCD recovery
//
//
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_mpipl_chip_cleanup.H>
#include <p9_misc_scom_addresses.H>
#include <p9_misc_scom_addresses_fld.H>

extern "C"
{
    //------------------------------------------------------------------------------
    // Function definitions
    //------------------------------------------------------------------------------

    //------------------------------------------------------------------------------
    // name: p9_mpipl_chip_cleanup
    //------------------------------------------------------------------------------
    // purpose:
    // To enable MCD recovery
    //
    // Note: PHBs are left in ETU reset state after executing proc_mpipl_nest_cleanup, which runs before this procedure.  PHYP releases PHBs from ETU reset post HostBoot IPL.
    //
    // SCOM regs
    //
    // 1) MCD even recovery control register
    // PU_BANK0_MCD_REC (SCOM)
    // bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
    //
    // 2) MCD odd recovery control register
    // PU_MCD1_BANK0_MCD_REC (SCOM)
    // bit 0 (PU_BANK0_MCD_REC_ENABLE): 0 to 1 transition needed to start, reset to 0 at end of request.
    //
    //------------------------------------------------------------------------------
    fapi2::ReturnCode p9_mpipl_chip_cleanup(fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
    {
        const uint8_t MAX_MCD_DIRS = 2; //Max of 2 MCD Directories (even and odd)
        fapi2::buffer<uint64_t> fsi_data[MAX_MCD_DIRS];
        fapi2::buffer<uint64_t> w_data(0x00030001);
        fapi2::buffer<uint64_t> r_data;
        const uint64_t C_INT_VC_VSD_TABLE_DATA(0x5013202);
        const uint64_t ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[MAX_MCD_DIRS] =
        {
            PU_BANK0_MCD_REC, //MCD even recovery control register address
            PU_MCD1_BANK0_MCD_REC  //MCD odd recovery control register address
        };
        const char* ARY_MCD_DIR_STRS[MAX_MCD_DIRS] =
        {
            "Even", //Ptr to char string "Even" for even MCD
            "Odd"   //Ptr to char string "Odd" for odd MCD
        };

        // HW386071:  INT unit has a defect that might result in fake ecc errors.  Have to do these four writes and reads to scom registers
        FAPI_TRY(fapi2::putScom(i_target, PU_INT_VC_VSD_TABLE_ADDR, w_data),
                 "putScom error selecting address 1");

        FAPI_TRY(fapi2::getScom(i_target, C_INT_VC_VSD_TABLE_DATA, r_data),
                 "getScom error reading from address 1");

        w_data.clearBit<63>();
        FAPI_TRY(fapi2::putScom(i_target, PU_INT_VC_VSD_TABLE_ADDR, w_data),
                 "putScom error selecting address 0");

        w_data.flush<0>();
        FAPI_TRY(fapi2::putScom(i_target, C_INT_VC_VSD_TABLE_DATA, w_data),
                 "putScom error writing to address 0");
        // HW386071

        //Verify MCD recovery was previously disabled for even and odd slices
        //If not, this is an error condition
        for (uint8_t counter = 0; counter < MAX_MCD_DIRS; counter++)
        {
            FAPI_DBG("Verifying MCD %s Recovery is disabled", ARY_MCD_DIR_STRS[counter]);
            FAPI_TRY(fapi2::getScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
                     "getScom error veryfing that MCD recovery is disabled");

            FAPI_ASSERT(!fsi_data[counter].getBit<PU_BANK0_MCD_REC_ENABLE>(),
                        fapi2::P9_MPIPL_CHIP_CLEANUP_MCD_NOT_DISABLED().set_TARGET(i_target).set_ADDRESS(
                            ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter]).set_DATA(fsi_data[counter]), "MCD recovery not disabled as expected");
        }

        //Assert bit 0 of MCD Recovery Ctrl regs to enable MCD recovery
        for (int counter = 0; counter < MAX_MCD_DIRS; counter++)
        {
            FAPI_DBG("Enabling MCD %s Recovery", ARY_MCD_DIR_STRS[counter]);

            //Assert bit 0 of MCD Even or Odd Recovery Control reg to enable recovery
            fsi_data[counter].setBit<PU_BANK0_MCD_REC_ENABLE>();

            //Write data to MCD Even or Odd Recovery Control reg
            FAPI_TRY(fapi2::putScom(i_target, ARY_MCD_RECOVERY_CTRL_REGS_ADDRS[counter], fsi_data[counter]),
                     "putScom error assert bit 0 of MCD recovery control register");
        }

    fapi_try_exit:
        FAPI_DBG("Exiting...");
        return fapi2::current_err;
    }

} // extern "C"
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>                /* low-level i/o */
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdint.h>

#include "Palettes.h"
#include "SPI.h"
#include "Lepton_I2C.h"

#define PACKET_SIZE 164
#define PACKET_SIZE_UINT16 (PACKET_SIZE/2)
#define PACKETS_PER_FRAME 60
#define FRAME_SIZE_UINT16 (PACKET_SIZE_UINT16*PACKETS_PER_FRAME)
#define FPS 27;

static char const *v4l2dev = "/dev/video1";
static int v4l2sink = -1;
static int width = 80;                //640;    // Default for Flash
static int height = 60;        //480;    // Default for Flash
static char *vidsendbuf = NULL;
static int vidsendsiz = 0;

static int resets = 0;
static uint8_t result[PACKET_SIZE*PACKETS_PER_FRAME];
static uint16_t *frameBuffer;

static void init_device() {
    SpiOpenPort(0);
}

static void grab_frame() {

    resets = 0;
    for (int j = 0; j < PACKETS_PER_FRAME; j++) {
        read(spi_cs0_fd, result + sizeof(uint8_t) * PACKET_SIZE * j, sizeof(uint8_t) * PACKET_SIZE);
        int packetNumber = result[j * PACKET_SIZE + 1];
        if (packetNumber != j) {
            j = -1;
            resets += 1;
            usleep(1000);
            if (resets == 750) {
                SpiClosePort(0);
                usleep(750000);
                SpiOpenPort(0);
            }
        }
    }
    if (resets >= 30) {
        fprintf( stderr, "done reading, resets: \n" );
    }

    frameBuffer = (uint16_t *)result;
    int row, column;
    uint16_t value;
    uint16_t minValue = 65535;
    uint16_t maxValue = 0;

    for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
        if (i % PACKET_SIZE_UINT16 < 2) {
            continue;
        }

        int temp = result[i * 2];
        result[i * 2] = result[i * 2 + 1];
        result[i * 2 + 1] = temp;

        value = frameBuffer[i];
        if (value > maxValue) {
            maxValue = value;
        }
        if (value < minValue) {
            minValue = value;
        }
        column = i % PACKET_SIZE_UINT16 - 2;
        row = i / PACKET_SIZE_UINT16;
    }

    float diff = maxValue - minValue;
    float scale = 255 / diff;
    memset(vidsendbuf, 0, 3);
    memcpy(vidsendbuf + 3, vidsendbuf, vidsendsiz - 3);
    for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
        if (i % PACKET_SIZE_UINT16 < 2) {
            continue;
        }
        value = (frameBuffer[i] - minValue) * scale;
        const int *colormap = colormap_ironblack;
        column = (i % PACKET_SIZE_UINT16) - 2;
        row = i / PACKET_SIZE_UINT16;

        int idx = row * width * 3 + column * 3;

        vidsendbuf[idx + 0] = colormap[3 * value];
        vidsendbuf[idx + 1] = colormap[3 * value + 1];
        vidsendbuf[idx + 2] = colormap[3 * value + 2];
    }

    /*
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    memset( vidsendbuf, 0, 3);
    memcpy( vidsendbuf+3, vidsendbuf, vidsendsiz-3 );
    */
}

static void stop_device() {
    SpiClosePort(0);
}

static void open_vpipe()
{
    v4l2sink = open(v4l2dev, O_WRONLY);
    if (v4l2sink < 0) {
        fprintf(stderr, "Failed to open v4l2sink device. (%s)\n", strerror(errno));
        exit(-2);
    }
    // setup video for proper format
    struct v4l2_format v;
    int t;
    v.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
    t = ioctl(v4l2sink, VIDIOC_G_FMT, &v);
    if( t < 0 )
        exit(t);
    v.fmt.pix.width = width;
    v.fmt.pix.height = height;
    v.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
    vidsendsiz = width * height * 3;
    v.fmt.pix.sizeimage = vidsendsiz;
    t = ioctl(v4l2sink, VIDIOC_S_FMT, &v);
    if( t < 0 )
        exit(t);
    vidsendbuf = (char*)malloc( vidsendsiz );
}

static pthread_t sender;
static sem_t lock1,lock2;
static void *sendvid(void *v)
{
    (void)v;
    for (;;) {
        sem_wait(&lock1);
        if (vidsendsiz != write(v4l2sink, vidsendbuf, vidsendsiz))
            exit(-1);
        sem_post(&lock2);
    }
}

int main(int argc, char **argv)
{
    struct timespec ts;

    if( argc == 2 )
        v4l2dev = argv[1];

    open_vpipe();

    // open and lock response
    if (sem_init(&lock2, 0, 1) == -1)
        exit(-1);
    sem_wait(&lock2);

    if (sem_init(&lock1, 0, 1) == -1)
        exit(-1);
    pthread_create(&sender, NULL, sendvid, NULL);

    for (;;) {
        // wait until a frame can be written
        fprintf( stderr, "Waiting for sink\n" );
        sem_wait(&lock2);
        // setup source
        init_device(); // open and setup SPI
        for (;;) {
            grab_frame();
            // push it out
            sem_post(&lock1);
            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += 2;
            // wait for it to get written (or is blocking)
            if (sem_timedwait(&lock2, &ts))
                break;
        }
        stop_device(); // close SPI
    }
    close(v4l2sink);
    return 0;
}
<commit_msg>Removed unneeded memcpy<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>                /* low-level i/o */
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdint.h>

#include "Palettes.h"
#include "SPI.h"
#include "Lepton_I2C.h"

#define PACKET_SIZE 164
#define PACKET_SIZE_UINT16 (PACKET_SIZE/2)
#define PACKETS_PER_FRAME 60
#define FRAME_SIZE_UINT16 (PACKET_SIZE_UINT16*PACKETS_PER_FRAME)
#define FPS 27;

static char const *v4l2dev = "/dev/video1";
static int v4l2sink = -1;
static int width = 80;                //640;    // Default for Flash
static int height = 60;        //480;    // Default for Flash
static char *vidsendbuf = NULL;
static int vidsendsiz = 0;

static int resets = 0;
static uint8_t result[PACKET_SIZE*PACKETS_PER_FRAME];
static uint16_t *frameBuffer;

static void init_device() {
    SpiOpenPort(0);
}

static void grab_frame() {

    resets = 0;
    for (int j = 0; j < PACKETS_PER_FRAME; j++) {
        read(spi_cs0_fd, result + sizeof(uint8_t) * PACKET_SIZE * j, sizeof(uint8_t) * PACKET_SIZE);
        int packetNumber = result[j * PACKET_SIZE + 1];
        if (packetNumber != j) {
            j = -1;
            resets += 1;
            usleep(1000);
            if (resets == 750) {
                SpiClosePort(0);
                usleep(750000);
                SpiOpenPort(0);
            }
        }
    }
    if (resets >= 30) {
        fprintf( stderr, "done reading, resets: \n" );
    }

    frameBuffer = (uint16_t *)result;
    int row, column;
    uint16_t value;
    uint16_t minValue = 65535;
    uint16_t maxValue = 0;

    for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
        if (i % PACKET_SIZE_UINT16 < 2) {
            continue;
        }

        int temp = result[i * 2];
        result[i * 2] = result[i * 2 + 1];
        result[i * 2 + 1] = temp;

        value = frameBuffer[i];
        if (value > maxValue) {
            maxValue = value;
        }
        if (value < minValue) {
            minValue = value;
        }
        column = i % PACKET_SIZE_UINT16 - 2;
        row = i / PACKET_SIZE_UINT16;
    }

    float diff = maxValue - minValue;
    float scale = 255 / diff;
    for (int i = 0; i < FRAME_SIZE_UINT16; i++) {
        if (i % PACKET_SIZE_UINT16 < 2) {
            continue;
        }
        value = (frameBuffer[i] - minValue) * scale;
        const int *colormap = colormap_ironblack;
        column = (i % PACKET_SIZE_UINT16) - 2;
        row = i / PACKET_SIZE_UINT16;

        // Set video buffer pixel to scaled colormap value
        int idx = row * width * 3 + column * 3;
        vidsendbuf[idx + 0] = colormap[3 * value];
        vidsendbuf[idx + 1] = colormap[3 * value + 1];
        vidsendbuf[idx + 2] = colormap[3 * value + 2];
    }

    /*
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    memset( vidsendbuf, 0, 3);
    memcpy( vidsendbuf+3, vidsendbuf, vidsendsiz-3 );
    */
}

static void stop_device() {
    SpiClosePort(0);
}

static void open_vpipe()
{
    v4l2sink = open(v4l2dev, O_WRONLY);
    if (v4l2sink < 0) {
        fprintf(stderr, "Failed to open v4l2sink device. (%s)\n", strerror(errno));
        exit(-2);
    }
    // setup video for proper format
    struct v4l2_format v;
    int t;
    v.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
    t = ioctl(v4l2sink, VIDIOC_G_FMT, &v);
    if( t < 0 )
        exit(t);
    v.fmt.pix.width = width;
    v.fmt.pix.height = height;
    v.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
    vidsendsiz = width * height * 3;
    v.fmt.pix.sizeimage = vidsendsiz;
    t = ioctl(v4l2sink, VIDIOC_S_FMT, &v);
    if( t < 0 )
        exit(t);
    vidsendbuf = (char*)malloc( vidsendsiz );
}

static pthread_t sender;
static sem_t lock1,lock2;
static void *sendvid(void *v)
{
    (void)v;
    for (;;) {
        sem_wait(&lock1);
        if (vidsendsiz != write(v4l2sink, vidsendbuf, vidsendsiz))
            exit(-1);
        sem_post(&lock2);
    }
}

int main(int argc, char **argv)
{
    struct timespec ts;

    if( argc == 2 )
        v4l2dev = argv[1];

    open_vpipe();

    // open and lock response
    if (sem_init(&lock2, 0, 1) == -1)
        exit(-1);
    sem_wait(&lock2);

    if (sem_init(&lock1, 0, 1) == -1)
        exit(-1);
    pthread_create(&sender, NULL, sendvid, NULL);

    for (;;) {
        // wait until a frame can be written
        fprintf( stderr, "Waiting for sink\n" );
        sem_wait(&lock2);
        // setup source
        init_device(); // open and setup SPI
        for (;;) {
            grab_frame();
            // push it out
            sem_post(&lock1);
            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += 2;
            // wait for it to get written (or is blocking)
            if (sem_timedwait(&lock2, &ts))
                break;
        }
        stop_device(); // close SPI
    }
    close(v4l2sink);
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Main.cpp
 *
 * Created on: Dec 31, 2014
 * Author: jrparks
 */
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include "C920Camera.h"

using namespace std;
using namespace cv;

int g_h_max = 197;
int g_h_min = 102;
int g_s_max = 255;
int g_s_min = 72;
int g_v_max = 208;
int g_v_min = 0;
int Brightness = 128,
    Contrast = 128,
    Saturation = 128,
    Sharpness = 128,
    Gain = 20,
    Focus = 20,
    BacklightCompensation = 20,
    WhiteBalanceTemperature = 20;
v4l2::C920Camera camera;
cv::Mat frame;

int main(int argc, char* argv[]) {
   fprintf(stdout, "Preparing to open camera.\n");
   camera.Open("/dev/video1");
   if (!camera.IsOpen()) {
      fprintf(stderr, "Unable to open camera.\n");
      return -1;
   }
   bool batch = false;

   if ((argc > 1) && (strcmp(argv[1], "--batch") == 0))
      batch = true;

   char name[256];
   int index = 0;
   int rc;
   struct stat statbuf;
   do
   {
      sprintf(name, "cap%d.avi", index++);
      rc = stat(name, &statbuf);
   }
   while (rc == 0);
   fprintf (stderr, "Writing to %s\n", name);

   camera.ChangeCaptureSize(v4l2::CAPTURE_SIZE_800x600);
   camera.ChangeCaptureFPS(v4l2::CAPTURE_FPS_30);
   camera.GetBrightness(Brightness);
   camera.GetContrast(Contrast);
   camera.GetSaturation(Saturation);
   camera.GetSharpness(Sharpness);
   camera.GetGain(Gain);
   camera.GetBacklightCompensation(BacklightCompensation);
   camera.GetWhiteBalanceTemperature(WhiteBalanceTemperature);
   ++WhiteBalanceTemperature;
#if 0
   camera.GetFocus(Focus);
   ++Focus;
#endif
   cv::namedWindow("Adjustments", CV_WINDOW_NORMAL);
   cv::createTrackbar("Brightness", "Adjustments", &Brightness, 255);
   cv::createTrackbar("Contrast", "Adjustments", &Contrast, 255);
   cv::createTrackbar("Saturation", "Adjustments", &Saturation, 255);
   cv::createTrackbar("Sharpness", "Adjustments", &Sharpness, 255);
   cv::createTrackbar("Gain", "Adjustments", &Gain, 255);
   cv::createTrackbar("Backlight Compensation", "Adjustments", &BacklightCompensation, 1);
   // Off by one to account for -1 being auto.
   cv::createTrackbar("White Balance Temperature", "Adjustments", &WhiteBalanceTemperature, 6501);
   cv::createTrackbar("Focus", "Adjustments", &Focus, 256);
   cv::createTrackbar("Auto Exposure", "Adjustments", &AutoExposure, 3);

   camera.GrabFrame();
   camera.RetrieveMat(frame);
   VideoWriter outputVideo(name, CV_FOURCC('M','J','P','G'), 30, Size(frame.cols, frame.rows), true);

   int wait_key = 0;
   while (true) {
      camera.SetBrightness(Brightness);
      camera.SetContrast(Contrast);
      camera.SetSaturation(Saturation);
      camera.SetSharpness(Sharpness);
      camera.SetGain(Gain);
      camera.SetBacklightCompensation(BacklightCompensation);
      --WhiteBalanceTemperature;
      camera.SetWhiteBalanceTemperature(WhiteBalanceTemperature);
      ++WhiteBalanceTemperature;
      --Focus;
      camera.SetFocus(Focus);
      ++Focus;
      camera.SetAutoExposure(AutoExposure)
      if (camera.GrabFrame() && camera.RetrieveMat(frame))
      {
	 outputVideo << frame;
	 if (!batch)
	    imshow( "Detect", frame);
		Mat btrack;
	     inRange(frame, Scalar(g_h_min, g_s_min, g_v_min), Scalar(g_h_max, g_s_max, g_v_max), btrack);
		Mat element= getStructuringElement(MORPH_RECT, Size(5, 5), Point(2, 2));
		dilate(btrack, btrack, element);
		imshow("Tracking", btrack);
      } else {
	 fprintf(stderr, "Unable to grab frame from camera.\n");
      }
      if (!batch)
      {
	 wait_key = cv::waitKey(1);
	 if (wait_key == 27 || wait_key == 32)
	    break;
      }
   }
   fprintf(stdout, "Closing camera.\n");
   camera.Close();
}
<commit_msg>Use callbacks for controls rather than setting all the params every frame<commit_after>/*
 * Main.cpp
 *
 * Created on: Dec 31, 2014
 * Author: jrparks
 */
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include "C920Camera.h"

using namespace std;
using namespace cv;

int g_h_max = 197;
int g_h_min = 102;
int g_s_max = 255;
int g_s_min = 72;
int g_v_max = 208;
int g_v_min = 0;
int Brightness = 128,
    Contrast = 128,
    Saturation = 128,
    Sharpness = 128,
    Gain = 20,
    Focus = 20,
    BacklightCompensation = 20,
    WhiteBalanceTemperature = 20,
	AutoExposure = 1;
v4l2::C920Camera camera(0);

void brightnessCallback(int value, void *data)
{
	Brightness = value;
	camera.SetBrightness(value);
}
void contrastCallback(int value, void *data)
{
	Contrast = value;
	camera.SetContrast(value);
}
void saturationCallback(int value, void *data)
{
	Saturation = value;
	camera.SetSaturation(value);
}
void sharpnessCallback(int value, void *data)
{
	Sharpness = value;
	camera.SetSharpness(value);
}
void gainCallback(int value, void *data)
{
	Gain = value;
	camera.SetGain(value);
}
void autoExposureCallback(int value, void *data)
{
	AutoExposure = value;
	camera.SetAutoExposure(value);
}
void backlightCompensationCallback(int value, void *data)
{
	BacklightCompensation = value;
	camera.SetBacklightCompensation(value);
}
void whiteBalanceTemperatureCallback(int value, void *data)
{
	WhiteBalanceTemperature = value;
	// Off by one to account for -1 being auto.
	camera.SetWhiteBalanceTemperature(value-1);
}
void focusCallback(int value, void *data)
{
	Focus = value;
	// Off by one to account for -1 being auto.
	camera.SetFocus(value-1);
}

int main(int argc, char* argv[]) {
	if (!camera.IsOpen()) {
		fprintf(stderr, "Unable to open camera.\n");
		return -1;
	}
	bool batch = false;

	if ((argc > 1) && (strcmp(argv[1], "--batch") == 0))
		batch = true;

	char name[PATH_MAX];
	int index = 0;
	int rc;
	struct stat statbuf;
	do
	{
		sprintf(name, "cap%d.avi", index++);
		rc = stat(name, &statbuf);
	}
	while (rc == 0);
	fprintf (stderr, "Writing to %s\n", name);

	camera.ChangeCaptureSize(v4l2::CAPTURE_SIZE_800x600);
	camera.ChangeCaptureFPS(v4l2::CAPTURE_FPS_30);
	camera.GetBrightness(Brightness);
	camera.GetContrast(Contrast);
	camera.GetSaturation(Saturation);
	camera.GetSharpness(Sharpness);
	camera.GetGain(Gain);
	camera.GetBacklightCompensation(BacklightCompensation);
	camera.GetWhiteBalanceTemperature(WhiteBalanceTemperature);
	++WhiteBalanceTemperature; // Off by 1 since -1 is auto

	// Set auto-focus off on startup
	focusCallback(20, NULL);
	autoExposureCallback(1, NULL);

	cv::namedWindow("Adjustments", CV_WINDOW_NORMAL);
	cv::createTrackbar("Brightness", "Adjustments", &Brightness, 255, brightnessCallback);
	cv::createTrackbar("Contrast", "Adjustments", &Contrast, 255, contrastCallback);
	cv::createTrackbar("Saturation", "Adjustments", &Saturation, 255, saturationCallback);
	cv::createTrackbar("Sharpness", "Adjustments", &Sharpness, 255, sharpnessCallback);
	cv::createTrackbar("Gain", "Adjustments", &Gain, 255, gainCallback);
	cv::createTrackbar("Backlight Compensation", "Adjustments", &BacklightCompensation, 1, backlightCompensationCallback);
	// Off by one to account for -1 being auto.
	cv::createTrackbar("White Balance Temperature", "Adjustments", &WhiteBalanceTemperature, 6501, whiteBalanceTemperatureCallback);
	cv::createTrackbar("Focus", "Adjustments", &Focus, 256, focusCallback);
	cv::createTrackbar("Auto Exposure", "Adjustments", &AutoExposure, 3, autoExposureCallback);

	cv::Mat frame;
	camera.GrabFrame();
	camera.RetrieveMat(frame);
	VideoWriter outputVideo(name, CV_FOURCC('M','J','P','G'), 30, Size(frame.cols, frame.rows), true);

	while (true)
	{
		if (camera.GrabFrame() && camera.RetrieveMat(frame))
		{
			outputVideo << frame;
			if (!batch)
			{
				imshow( "Detect", frame);
				Mat btrack;
				inRange(frame, Scalar(g_h_min, g_s_min, g_v_min), Scalar(g_h_max, g_s_max, g_v_max), btrack);
				Mat element = getStructuringElement(MORPH_RECT, Size(5, 5), Point(2, 2));
				dilate(btrack, btrack, element);
				imshow("Tracking", btrack);
			}
		}
		else
		{
			fprintf(stderr, "Unable to grab frame from camera.\n");
			break;
		}
		if (!batch)
		{
			int wait_key = cv::waitKey(5);
			if (wait_key == 27 || wait_key == 32)
				break;
		}
	}
	fprintf(stdout, "Closing camera.\n");
	camera.Close();
}
<|endoftext|>


<commit_before>/*

  Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4

  Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>

*/

/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#include "QSvgRendererSlots.h"

QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent)
{
}

QSvgRendererSlots::~QSvgRendererSlots()
{
}
void QSvgRendererSlots::repaintNeeded()
{
  QObject *object = qobject_cast<QObject *>(sender());
  PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" );
  if( cb )
  {
    PHB_ITEM psender = Signals_return_qobject ( (QObject *) object, "QSVGRENDERER" );
    hb_vmEvalBlockV( (PHB_ITEM) cb, 1, psender );
    hb_itemRelease( psender );
  }
}

void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot )
{
  QSvgRenderer * obj = (QSvgRenderer *) hb_itemGetPtr( hb_objSendMsg( hb_stackSelfItem(), "POINTER", 0 ) );

  if( obj )
  {
    QSvgRendererSlots * s = QCoreApplication::instance()->findChild<QSvgRendererSlots *>();

    if( s == NULL )
    {
      s = new QSvgRendererSlots();
      s->moveToThread( QCoreApplication::instance()->thread() );
      s->setParent( QCoreApplication::instance() );
    }

    hb_retl( Signals_connection_disconnection( s, signal, slot ) );
  }
  else
  {
    hb_retl( false );
  }
}
<commit_msg>source/QtSvg: updated<commit_after>/*

  Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4

  Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>

*/

/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#include "QSvgRendererSlots.h"

QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent)
{
}

QSvgRendererSlots::~QSvgRendererSlots()
{
}
void QSvgRendererSlots::repaintNeeded()
{
  QObject *object = qobject_cast<QObject *>(sender());
  PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" );
  if( cb )
  {
    PHB_ITEM psender = Signals_return_qobject ( (QObject *) object, "QSVGRENDERER" );
    hb_vmEvalBlockV( cb, 1, psender );
    hb_itemRelease( psender );
  }
}

void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot )
{
  QSvgRenderer * obj = (QSvgRenderer *) hb_itemGetPtr( hb_objSendMsg( hb_stackSelfItem(), "POINTER", 0 ) );

  if( obj )
  {
    QSvgRendererSlots * s = QCoreApplication::instance()->findChild<QSvgRendererSlots *>();

    if( s == NULL )
    {
      s = new QSvgRendererSlots();
      s->moveToThread( QCoreApplication::instance()->thread() );
      s->setParent( QCoreApplication::instance() );
    }

    hb_retl( Signals_connection_disconnection( s, signal, slot ) );
  }
  else
  {
    hb_retl( false );
  }
}
<|endoftext|>


<commit_before>/**
 * \file
 * \brief Semaphore class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-11-18
 */

#ifndef INCLUDE_DISTORTOS_SEMAPHORE_HPP_
#define INCLUDE_DISTORTOS_SEMAPHORE_HPP_

#include "distortos/scheduler/ThreadControlBlockList.hpp"

namespace distortos
{

/**
 * \brief Semaphore is the basic synchronization primitive
 *
 * Similar to POSIX semaphores - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16
 */

class Semaphore
{
public:

	/**
	 * \brief Semaphore constructor
	 *
	 * Similar to sem_init() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html#
	 *
	 * \param [in] value is the initial value of the semaphore
	 */

	Semaphore(int value);

	/**
	 * \brief Semaphore destructor
	 *
	 * Similar to sem_destroy() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_destroy.html#
	 *
	 * It is safe to destroy a semaphore upon which no threads are currently blocked. The effect of destroying a
	 * semaphore upon which other threads are currently blocked is system error.
	 */

	~Semaphore();

	/**
	 * \brief Gets current value of semaphore.
	 *
	 * Similar to sem_getvalue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_getvalue.html#
	 *
	 * \return current value of semaphore, positive value if semaphore is not locked, negative value or zero otherwise;
	 * negative value represents the number of threads waiting on this semaphore
	 */

	int getValue() const
	{
		return value_;
	}

	/**
	 * \brief Unlocks the semaphore.
	 *
	 * Similar to sem_post() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_post.html#
	 *
	 * This function shall unlock the semaphore by performing a semaphore unlock operation. If the semaphore value
	 * resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become
	 * unlocked; the semaphore value is simply incremented. Otherwise one of the threads blocked waiting for the
	 * semaphore shall be allowed to return successfully from its call to lock() - the highest priority waiting thread
	 * shall be unblocked, and if there is more than one highest priority thread blocked waiting for the semaphore, then
	 * the highest priority thread that has been waiting the longest shall be unblocked.
	 */

	void post();

	/**
	 * \brief Tries to lock the semaphore.
	 *
	 * Similar to sem_trywait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
	 *
	 * This function shall lock the semaphore only if the semaphore is currently not locked; that is, if the semaphore
	 * value is currently positive. Otherwise, it shall not lock the semaphore. Upon successful return, the state of the
	 * semaphore shall be locked and shall remain locked until unlock() function is executed.
	 *
	 * \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
	 * - EAGAIN - semaphore was already locked, so it cannot be immediately locked by the tryWait() operation,
	 * - EDEADLK - a deadlock condition was detected,
	 * - EINTR - a signal interrupted this function;
	 */

	int tryWait();

	/**
	 * \brief Locks the semaphore.
	 *
	 * Similar to sem_wait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
	 *
	 * This function shall lock the semaphore by performing a semaphore lock operation on that semaphore. If the
	 * semaphore value is currently zero, then the calling thread shall not return from the call to lock() until it
	 * either locks the semaphore or the call is interrupted by a signal. Upon successful return, the state of the
	 * semaphore shall be locked and shall remain locked until unlock() function is executed.
	 *
	 * \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
	 * - EDEADLK - a deadlock condition was detected,
	 * - EINTR - a signal interrupted this function;
	 */

	int wait();

private:

	/// ThreadControlBlock objects blocked on this semaphore
	scheduler::ThreadControlBlockList blockedList_;

	/// internal value of the semaphore
	int value_;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SEMAPHORE_HPP_
<commit_msg>Semaphore: make constructor explicit<commit_after>/**
 * \file
 * \brief Semaphore class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-11-18
 */

#ifndef INCLUDE_DISTORTOS_SEMAPHORE_HPP_
#define INCLUDE_DISTORTOS_SEMAPHORE_HPP_

#include "distortos/scheduler/ThreadControlBlockList.hpp"

namespace distortos
{

/**
 * \brief Semaphore is the basic synchronization primitive
 *
 * Similar to POSIX semaphores - http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16
 */

class Semaphore
{
public:

	/**
	 * \brief Semaphore constructor
	 *
	 * Similar to sem_init() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html#
	 *
	 * \param [in] value is the initial value of the semaphore
	 */

	explicit Semaphore(int value);

	/**
	 * \brief Semaphore destructor
	 *
	 * Similar to sem_destroy() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_destroy.html#
	 *
	 * It is safe to destroy a semaphore upon which no threads are currently blocked. The effect of destroying a
	 * semaphore upon which other threads are currently blocked is system error.
	 */

	~Semaphore();

	/**
	 * \brief Gets current value of semaphore.
	 *
	 * Similar to sem_getvalue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_getvalue.html#
	 *
	 * \return current value of semaphore, positive value if semaphore is not locked, negative value or zero otherwise;
	 * negative value represents the number of threads waiting on this semaphore
	 */

	int getValue() const
	{
		return value_;
	}

	/**
	 * \brief Unlocks the semaphore.
	 *
	 * Similar to sem_post() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_post.html#
	 *
	 * This function shall unlock the semaphore by performing a semaphore unlock operation. If the semaphore value
	 * resulting from this operation is positive, then no threads were blocked waiting for the semaphore to become
	 * unlocked; the semaphore value is simply incremented. Otherwise one of the threads blocked waiting for the
	 * semaphore shall be allowed to return successfully from its call to lock() - the highest priority waiting thread
	 * shall be unblocked, and if there is more than one highest priority thread blocked waiting for the semaphore, then
	 * the highest priority thread that has been waiting the longest shall be unblocked.
	 */

	void post();

	/**
	 * \brief Tries to lock the semaphore.
	 *
	 * Similar to sem_trywait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
	 *
	 * This function shall lock the semaphore only if the semaphore is currently not locked; that is, if the semaphore
	 * value is currently positive. Otherwise, it shall not lock the semaphore. Upon successful return, the state of the
	 * semaphore shall be locked and shall remain locked until unlock() function is executed.
	 *
	 * \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
	 * - EAGAIN - semaphore was already locked, so it cannot be immediately locked by the tryWait() operation,
	 * - EDEADLK - a deadlock condition was detected,
	 * - EINTR - a signal interrupted this function;
	 */

	int tryWait();

	/**
	 * \brief Locks the semaphore.
	 *
	 * Similar to sem_wait() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_trywait.html#
	 *
	 * This function shall lock the semaphore by performing a semaphore lock operation on that semaphore. If the
	 * semaphore value is currently zero, then the calling thread shall not return from the call to lock() until it
	 * either locks the semaphore or the call is interrupted by a signal. Upon successful return, the state of the
	 * semaphore shall be locked and shall remain locked until unlock() function is executed.
	 *
	 * \return zero if the calling process successfully performed the semaphore lock operation, error code otherwise:
	 * - EDEADLK - a deadlock condition was detected,
	 * - EINTR - a signal interrupted this function;
	 */

	int wait();

private:

	/// ThreadControlBlock objects blocked on this semaphore
	scheduler::ThreadControlBlockList blockedList_;

	/// internal value of the semaphore
	int value_;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SEMAPHORE_HPP_
<|endoftext|>


<commit_before>#ifndef __NBA_CONFIG_HH__
#define __NBA_CONFIG_HH__

#include <unordered_map>
#include <vector>
#include <string>

#define NBA_MAX_NODES               (2)
#define NBA_MAX_CORES               (64)
#define NBA_MAX_PORTS               (16)
#define NBA_MAX_QUEUES_PER_PORT     (128)
#define NBA_MAX_COPROCESSORS        (2)     // Max number of coprocessor devices
#define NBA_MAX_PROCESSOR_TYPES     (2)     // Max number of device types (current: CPU and GPU)

#define NBA_BATCHING_TRADITIONAL    (0)
#define NBA_BATCHING_CONTINUOUS     (1)
#define NBA_BATCHING_BITVECTOR      (2)
#define NBA_BATCHING_LINKEDLIST     (3)
#define NBA_BATCHING_SCHEME         NBA_BATCHING_LINKEDLIST

#define NBA_MAX_PACKET_SIZE         (2048)
#ifdef NBA_NO_HUGE
  #define NBA_MAX_IO_BATCH_SIZE      (4u)
  #define NBA_MAX_COMP_BATCH_SIZE    (4u)
#else
  #if NBA_BATCHING_SCHEME == NBA_BATCHING_BITVECTOR
    #define NBA_MAX_IO_BATCH_SIZE    (64u)
    #define NBA_MAX_COMP_BATCH_SIZE  (64u)
  #else
    #define NBA_MAX_IO_BATCH_SIZE    (256u)
    #define NBA_MAX_COMP_BATCH_SIZE  (256u)
  #endif
#endif
#define NBA_MAX_COMP_PREPKTQ_LENGTH (256u)
#if defined(NBA_PMD_MLX4) || defined(NBA_PMD_MLNX_UIO)
#define NBA_MAX_IO_DESC_PER_HWRXQ      (8192)
#define NBA_MAX_IO_DESC_PER_HWTXQ      (8192)
#else
#define NBA_MAX_IO_DESC_PER_HWRXQ      (1024)
#define NBA_MAX_IO_DESC_PER_HWTXQ      (1024)
#endif

#define NBA_MAX_COPROC_PPDEPTH      (64u)
#define NBA_MAX_COPROC_INPUTQ_LENGTH       (64)
#define NBA_MAX_COPROC_COMPLETIONQ_LENGTH  (64)
#define NBA_MAX_COPROC_CTX_PER_COMPTHREAD   (1)

#define NBA_MAX_TASKPOOL_SIZE       (2048u)
#define NBA_MAX_BATCHPOOL_SIZE      (2048u)

#define NBA_MAX_ANNOTATION_SET_SIZE         (7)
#define NBA_MAX_NODELOCALSTORAGE_ENTRIES    (16)
#define NBA_MAX_KERNEL_OVERLAP      (8)
#define NBA_MAX_DATABLOCKS          (12)    // If too large (e.g., 64), batch_pool can not be allocated.

#define NBA_OQ                      (true)  // Use output-queuing semantics when possible.
#undef NBA_CPU_MICROBENCH                  // Enable support for PAPI library for microbenchmarks.

/* If you change below, update HANDLE_ALL_PORTS macro in lib/element.hh as well!! */
#define NBA_MAX_ELEM_NEXTS (4)

namespace nba {

enum io_thread_mode {
    IO_NORMAL = 0,
    IO_ECHOBACK = 1,
    IO_RR = 2,
    IO_RXONLY = 3,
    IO_EMUL = 4,
};

enum queue_template {
    SWRXQ = 0,
    TASKINQ = 1,
    TASKOUTQ = 2,
};

struct hwrxq {
    int ifindex;
    int qidx;
};

struct io_thread_conf {
    int core_id;
    std::vector<struct hwrxq> attached_rxqs;
    int mode;
    int swrxq_idx;
    void *priv;
};

struct comp_thread_conf {
    int core_id;
    int swrxq_idx;
    int taskinq_idx;
    int taskoutq_idx;
    void *priv;
};

struct coproc_thread_conf {
    int core_id;
    int device_id;
    int taskinq_idx;
    int taskoutq_idx;
    void *priv;
};

struct queue_conf {
    int node_id;
    enum queue_template template_;
    bool mp_enq;
    bool mc_deq;
    void *priv;
};

extern std::unordered_map<std::string, long> system_params;
extern std::vector<struct io_thread_conf> io_thread_confs;
extern std::vector<struct comp_thread_conf> comp_thread_confs;
extern std::vector<struct coproc_thread_conf> coproc_thread_confs;
extern std::vector<struct queue_conf> queue_confs;
/* queue_idx_map is used to find the appropriate queue instance by
 * the initialization code of io/comp/coproc threads. */
extern std::unordered_map<void*, int> queue_idx_map;
extern bool dummy_device;
extern bool emulate_io;
extern int emulated_packet_size;
extern int emulated_ip_version;
extern int emulated_num_fixed_flows;
extern size_t num_emulated_ifaces;

bool load_config(const char* pyfilename);
int get_ht_degree(void);

}

#undef HAVE_PSIO

/* For microbenchmarks (see lib/io.cc) */
//#define TEST_MINIMAL_L2FWD
//#define TEST_RXONLY

/* Inserts forced sleep when there is no packets received,
 * to reduce PCIe traffic.  The performance may increase or decrease
 * depending on the system configuration.
 * (see lib/io.cc)
 */
//#define NBA_SLEEPY_IO

#endif

// vim: ts=8 sts=4 sw=4 et
<commit_msg>Change the default batching scheme to bitvector.<commit_after>#ifndef __NBA_CONFIG_HH__
#define __NBA_CONFIG_HH__

#include <unordered_map>
#include <vector>
#include <string>

#define NBA_MAX_NODES               (2)
#define NBA_MAX_CORES               (64)
#define NBA_MAX_PORTS               (16)
#define NBA_MAX_QUEUES_PER_PORT     (128)
#define NBA_MAX_COPROCESSORS        (2)     // Max number of coprocessor devices
#define NBA_MAX_PROCESSOR_TYPES     (2)     // Max number of device types (current: CPU and GPU)

#define NBA_BATCHING_TRADITIONAL    (0)
#define NBA_BATCHING_CONTINUOUS     (1)
#define NBA_BATCHING_BITVECTOR      (2)
#define NBA_BATCHING_LINKEDLIST     (3)
#define NBA_BATCHING_SCHEME         NBA_BATCHING_BITVECTOR

#define NBA_MAX_PACKET_SIZE         (2048)
#ifdef NBA_NO_HUGE
  #define NBA_MAX_IO_BATCH_SIZE      (4u)
  #define NBA_MAX_COMP_BATCH_SIZE    (4u)
#else
  #if NBA_BATCHING_SCHEME == NBA_BATCHING_BITVECTOR
    #define NBA_MAX_IO_BATCH_SIZE    (64u)
    #define NBA_MAX_COMP_BATCH_SIZE  (64u)
  #else
    #define NBA_MAX_IO_BATCH_SIZE    (256u)
    #define NBA_MAX_COMP_BATCH_SIZE  (256u)
  #endif
#endif
#define NBA_MAX_COMP_PREPKTQ_LENGTH (256u)
#if defined(NBA_PMD_MLX4) || defined(NBA_PMD_MLNX_UIO)
#define NBA_MAX_IO_DESC_PER_HWRXQ      (8192)
#define NBA_MAX_IO_DESC_PER_HWTXQ      (8192)
#else
#define NBA_MAX_IO_DESC_PER_HWRXQ      (1024)
#define NBA_MAX_IO_DESC_PER_HWTXQ      (1024)
#endif

#define NBA_MAX_COPROC_PPDEPTH      (64u)
#define NBA_MAX_COPROC_INPUTQ_LENGTH       (64)
#define NBA_MAX_COPROC_COMPLETIONQ_LENGTH  (64)
#define NBA_MAX_COPROC_CTX_PER_COMPTHREAD   (1)

#define NBA_MAX_TASKPOOL_SIZE       (2048u)
#define NBA_MAX_BATCHPOOL_SIZE      (2048u)

#define NBA_MAX_ANNOTATION_SET_SIZE         (7)
#define NBA_MAX_NODELOCALSTORAGE_ENTRIES    (16)
#define NBA_MAX_KERNEL_OVERLAP      (8)
#define NBA_MAX_DATABLOCKS          (12)    // If too large (e.g., 64), batch_pool can not be allocated.

#define NBA_OQ                      (true)  // Use output-queuing semantics when possible.
#undef NBA_CPU_MICROBENCH                  // Enable support for PAPI library for microbenchmarks.

/* If you change below, update HANDLE_ALL_PORTS macro in lib/element.hh as well!! */
#define NBA_MAX_ELEM_NEXTS (4)

namespace nba {

enum io_thread_mode {
    IO_NORMAL = 0,
    IO_ECHOBACK = 1,
    IO_RR = 2,
    IO_RXONLY = 3,
    IO_EMUL = 4,
};

enum queue_template {
    SWRXQ = 0,
    TASKINQ = 1,
    TASKOUTQ = 2,
};

struct hwrxq {
    int ifindex;
    int qidx;
};

struct io_thread_conf {
    int core_id;
    std::vector<struct hwrxq> attached_rxqs;
    int mode;
    int swrxq_idx;
    void *priv;
};

struct comp_thread_conf {
    int core_id;
    int swrxq_idx;
    int taskinq_idx;
    int taskoutq_idx;
    void *priv;
};

struct coproc_thread_conf {
    int core_id;
    int device_id;
    int taskinq_idx;
    int taskoutq_idx;
    void *priv;
};

struct queue_conf {
    int node_id;
    enum queue_template template_;
    bool mp_enq;
    bool mc_deq;
    void *priv;
};

extern std::unordered_map<std::string, long> system_params;
extern std::vector<struct io_thread_conf> io_thread_confs;
extern std::vector<struct comp_thread_conf> comp_thread_confs;
extern std::vector<struct coproc_thread_conf> coproc_thread_confs;
extern std::vector<struct queue_conf> queue_confs;
/* queue_idx_map is used to find the appropriate queue instance by
 * the initialization code of io/comp/coproc threads. */
extern std::unordered_map<void*, int> queue_idx_map;
extern bool dummy_device;
extern bool emulate_io;
extern int emulated_packet_size;
extern int emulated_ip_version;
extern int emulated_num_fixed_flows;
extern size_t num_emulated_ifaces;

bool load_config(const char* pyfilename);
int get_ht_degree(void);

}

#undef HAVE_PSIO

/* For microbenchmarks (see lib/io.cc) */
//#define TEST_MINIMAL_L2FWD
//#define TEST_RXONLY

/* Inserts forced sleep when there is no packets received,
 * to reduce PCIe traffic.  The performance may increase or decrease
 * depending on the system configuration.
 * (see lib/io.cc)
 */
//#define NBA_SLEEPY_IO

#endif

// vim: ts=8 sts=4 sw=4 et
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/pcl_tests.h>

using namespace pcl;
using namespace pcl::test;

PointCloud<PointXYZ> cloud;
const size_t size = 10 * 480;

TEST (PointCloud, size)
{
  EXPECT_EQ(cloud.points.size (), cloud.size ());
}

TEST (PointCloud, sq_brackets_wrapper)
{
  for (uint32_t i = 0; i < size; ++i)
    EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (),
                       cloud[i].getVector3fMap ());
}

TEST (PointCloud, at)
{
  for (uint32_t i = 0; i < size; ++i)
    EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (),
                       cloud.at (i).getVector3fMap ());
}

TEST (PointCloud, front)
{
  EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (),
                     cloud.front ().getVector3fMap ());
}

TEST (PointCloud, back)
{
  EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (),
                     cloud.back ().getVector3fMap ());
}

TEST (PointCloud, constructor_with_allocation)
{
  PointCloud<PointXYZ> cloud2 (5, 80);
  EXPECT_EQ (cloud2.width, 5);
  EXPECT_EQ (cloud2.height, 80);
  EXPECT_EQ (cloud2.size (), 5*80);
}

TEST (PointCloud, iterators)
{
  EXPECT_EQ_VECTORS (cloud.begin ()->getVector3fMap (),
                     cloud.points.begin ()->getVector3fMap ());
  EXPECT_EQ_VECTORS (cloud.end ()->getVector3fMap (),
                     cloud.points.end ()->getVector3fMap ());
  PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
  PointCloud<PointXYZ>::VectorType::const_iterator pit2 = cloud.points.begin ();
  for (; pit < cloud.end (); ++pit2, ++pit)
    EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}

TEST (PointCloud, insert_range)
{
  PointCloud<PointXYZ> cloud2 (10, 1);
  for (uint32_t i = 0; i < 10; ++i)
    cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2);

  uint32_t old_size = cloud.size ();
  cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ());
  EXPECT_EQ (cloud.width, cloud.size ());
  EXPECT_EQ (cloud.height, 1);
  EXPECT_EQ (cloud.width, old_size + cloud2.size ());
  PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
  PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin ();
  for (; pit2 < cloud2.end (); ++pit2, ++pit)
    EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}

int
main (int argc, char** argv)
{
  cloud.width = 10;
  cloud.height = 480;
  for (uint32_t i = 0; i < size; ++i)
    cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
<commit_msg>nm remove extra line break<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/pcl_tests.h>

using namespace pcl;
using namespace pcl::test;

PointCloud<PointXYZ> cloud;
const size_t size = 10 * 480;

TEST (PointCloud, size)
{
  EXPECT_EQ(cloud.points.size (), cloud.size ());
}

TEST (PointCloud, sq_brackets_wrapper)
{
  for (uint32_t i = 0; i < size; ++i)
    EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (),
                       cloud[i].getVector3fMap ());
}

TEST (PointCloud, at)
{
  for (uint32_t i = 0; i < size; ++i)
    EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (),
                       cloud.at (i).getVector3fMap ());
}

TEST (PointCloud, front)
{
  EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (),
                     cloud.front ().getVector3fMap ());
}

TEST (PointCloud, back)
{
  EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (),
                     cloud.back ().getVector3fMap ());
}

TEST (PointCloud, constructor_with_allocation)
{
  PointCloud<PointXYZ> cloud2 (5, 80);
  EXPECT_EQ (cloud2.width, 5);
  EXPECT_EQ (cloud2.height, 80);
  EXPECT_EQ (cloud2.size (), 5*80);
}

TEST (PointCloud, iterators)
{
  EXPECT_EQ_VECTORS (cloud.begin ()->getVector3fMap (),
                     cloud.points.begin ()->getVector3fMap ());
  EXPECT_EQ_VECTORS (cloud.end ()->getVector3fMap (),
                     cloud.points.end ()->getVector3fMap ());
  PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
  PointCloud<PointXYZ>::VectorType::const_iterator pit2 = cloud.points.begin ();
  for (; pit < cloud.end (); ++pit2, ++pit)
    EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}

TEST (PointCloud, insert_range)
{
  PointCloud<PointXYZ> cloud2 (10, 1);
  for (uint32_t i = 0; i < 10; ++i)
    cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2);

  uint32_t old_size = cloud.size ();
  cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ());
  EXPECT_EQ (cloud.width, cloud.size ());
  EXPECT_EQ (cloud.height, 1);
  EXPECT_EQ (cloud.width, old_size + cloud2.size ());
  PointCloud<PointXYZ>::const_iterator pit = cloud.begin ();
  PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin ();
  for (; pit2 < cloud2.end (); ++pit2, ++pit)
    EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ());
}

int
main (int argc, char** argv)
{
  cloud.width = 10;
  cloud.height = 480;
  for (uint32_t i = 0; i < size; ++i)
    cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2));

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
<|endoftext|>


<commit_before>#pragma once

#include <cstring>
#include <sys/mman.h>

#include "vfs/platform.hpp"

namespace vfs {

    //----------------------------------------------------------------------------------------------
    using file_view_impl = class posix_file_view;
    //----------------------------------------------------------------------------------------------

    //----------------------------------------------------------------------------------------------
    class posix_file_view
    {
	protected:
		//------------------------------------------------------------------------------------------
        posix_file_view(file_sptr spFile, int64_t viewSize)
            : spFile_(std::move(spFile))
            , name_(spFile_->fileName())
            //, fileMappingHandle_(nullptr)
            , pData_(nullptr)
            , pCursor_(nullptr)
            , mappedTotalSize_(viewSize)
        {
			vfs_check(spFile_->isValid());
            map(viewSize, false);
        }

        //------------------------------------------------------------------------------------------
        posix_file_view(const path &name, int64_t size, bool openExisting)
            : name_(name)
            //, fileMappingHandle_(nullptr)
            , pData_(nullptr)
            , pCursor_(nullptr)
            , mappedTotalSize_(size)
        {
            map(size, openExisting);
        }

		//------------------------------------------------------------------------------------------
        ~posix_file_view()
        {
            flush();
            unmap();

            /*
            if (spFile_ == nullptr)
            {
                CloseHandle(fileMappingHandle_);
            }
            */
        }

		//------------------------------------------------------------------------------------------
        bool map(int64_t viewSize, bool openExisting)
        {
            const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;

            if (spFile_)
            {
                if (!spFile_->createMapping(viewSize))
                {
                    return false;
                }

                //fileMappingHandle_  = spFile_->nativeFileMappingHandle();
                const auto currentFileSize = spFile_->size();
                fileTotalSize_ = viewSize == 0 ? currentFileSize : viewSize;

                if (currentFileSize < viewSize)
                {
                    spFile_->resize(viewSize);
                }
            }
            else
            {
                vfs_check(false);
                /*
                if (openExisting)
                {
                    fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());
                }
                else
                {
                    fileMappingHandle_ = CreateFileMapping
                    (
                        INVALID_HANDLE_VALUE,
                        nullptr,
                        PAGE_READWRITE,
                        DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),
                        name_.c_str()
                    );
                }

                if (fileMappingHandle_ == nullptr)
                {
                    const auto errorCode = GetLastError();
                    vfs_errorf("%sFileMapping(%ws) failed with error: %s", openExisting ? "Open" : "Create", name_.c_str(), get_last_error_as_string(errorCode).c_str());
                    return false;
                }

                fileTotalSize_ = viewSize;
                */
            }

            const auto fileMapAccess = (
                (access == file_access::read_only)
                ? PROT_READ
                : ((access == file_access::write_only)
                    ? PROT_WRITE
                    : PROT_READ | PROT_WRITE
                )
            );

            pData_ = reinterpret_cast<uint8_t*>(mmap(nullptr, fileTotalSize_, fileMapAccess, MAP_PRIVATE, spFile_->nativeHandle(), 0));
            pCursor_ = pData_;

            if (pData_ == MAP_FAILED)
            {
                vfs_errorf("mmap(%s) failed with error: %s", name_.c_str(), get_last_error_as_string(errno).c_str());
                return false;
            }

            return true;
        }

		//------------------------------------------------------------------------------------------
        bool unmap()
        {
            if (pData_ && munmap(pData_, fileTotalSize_) == -1)
            {
                return false;
            }

            return true;
        }

		//------------------------------------------------------------------------------------------
        bool flush()
        {
            /*
            if (!FlushViewOfFile(pData_, 0))
            {
                return false;
            }
            */
            return true;
        }

		//------------------------------------------------------------------------------------------
        int64_t read(uint8_t *dst, int64_t sizeInBytes)
        {
            if (canMoveCursor(sizeInBytes))
            {
                memcpy(dst, pCursor_, sizeInBytes);
                pCursor_ += sizeInBytes;
                return sizeInBytes;
            }
            return 0;
        }

		//------------------------------------------------------------------------------------------
        int64_t write(const uint8_t *src, int64_t sizeInBytes)
        {
            if (canMoveCursor(sizeInBytes))
            {
                memcpy(pCursor_, src, sizeInBytes);
                pCursor_ += sizeInBytes;
                return sizeInBytes;
            }
            return 0;
        }

		//------------------------------------------------------------------------------------------
        bool isValid() const
        {
            return pData_ != nullptr;
        }

		//------------------------------------------------------------------------------------------
        int64_t totalSize() const
        {
            return fileTotalSize_;
        }

		//------------------------------------------------------------------------------------------
        bool canMoveCursor(int64_t offsetInBytes) const
        {
            return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;
        }

		//------------------------------------------------------------------------------------------
        template<typename T = uint8_t>
        T* data()
        {
            return reinterpret_cast<T*>(pData_);
        }

		//------------------------------------------------------------------------------------------
        uint8_t* data()
        {
            return data<>();
        }

		//------------------------------------------------------------------------------------------
        template<typename T = uint8_t>
        T* cursor()
        {
            return reinterpret_cast<T*>(pCursor_);
        }

		//------------------------------------------------------------------------------------------
        bool skip(int64_t offsetInBytes)
        {
            if (canMoveCursor(offsetInBytes))
            {
                pCursor_ += offsetInBytes;
                return true;
            }
            return false;
        }

	private:
		//------------------------------------------------------------------------------------------
        file_sptr   spFile_;
        path        name_;
        //HANDLE      fileMappingHandle_;
        uint8_t     *pData_;
        uint8_t     *pCursor_;
        int64_t     fileTotalSize_;
        int64_t     mappedTotalSize_;
    };
    //----------------------------------------------------------------------------------------------

} /*vfs*/
<commit_msg>Fixed file mapping not being flushed when closing the file.<commit_after>#pragma once

#include <cstring>
#include <sys/mman.h>

#include "vfs/platform.hpp"

namespace vfs {

    //----------------------------------------------------------------------------------------------
    using file_view_impl = class posix_file_view;
    //----------------------------------------------------------------------------------------------

    //----------------------------------------------------------------------------------------------
    class posix_file_view
    {
	protected:
		//------------------------------------------------------------------------------------------
        posix_file_view(file_sptr spFile, int64_t viewSize)
            : spFile_(std::move(spFile))
            , name_(spFile_->fileName())
            //, fileMappingHandle_(nullptr)
            , pData_(nullptr)
            , pCursor_(nullptr)
            , mappedTotalSize_(viewSize)
        {
			vfs_check(spFile_->isValid());
            map(viewSize, false);
        }

        //------------------------------------------------------------------------------------------
        posix_file_view(const path &name, int64_t size, bool openExisting)
            : name_(name)
            //, fileMappingHandle_(nullptr)
            , pData_(nullptr)
            , pCursor_(nullptr)
            , mappedTotalSize_(size)
        {
            map(size, openExisting);
        }

		//------------------------------------------------------------------------------------------
        ~posix_file_view()
        {
            flush();
            unmap();

            /*
            if (spFile_ == nullptr)
            {
                CloseHandle(fileMappingHandle_);
            }
            */
        }

		//------------------------------------------------------------------------------------------
        bool map(int64_t viewSize, bool openExisting)
        {
            const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;

            if (spFile_)
            {
                if (!spFile_->createMapping(viewSize))
                {
                    return false;
                }

                //fileMappingHandle_  = spFile_->nativeFileMappingHandle();
                const auto currentFileSize = spFile_->size();
                fileTotalSize_ = viewSize == 0 ? currentFileSize : viewSize;

                if (currentFileSize < viewSize)
                {
                    spFile_->resize(viewSize);
                }
            }
            else
            {
                vfs_check(false);
                /*
                if (openExisting)
                {
                    fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());
                }
                else
                {
                    fileMappingHandle_ = CreateFileMapping
                    (
                        INVALID_HANDLE_VALUE,
                        nullptr,
                        PAGE_READWRITE,
                        DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),
                        name_.c_str()
                    );
                }

                if (fileMappingHandle_ == nullptr)
                {
                    const auto errorCode = GetLastError();
                    vfs_errorf("%sFileMapping(%ws) failed with error: %s", openExisting ? "Open" : "Create", name_.c_str(), get_last_error_as_string(errorCode).c_str());
                    return false;
                }

                fileTotalSize_ = viewSize;
                */
            }

            const auto fileMapAccess = (
                (access == file_access::read_only)
                ? PROT_READ
                : ((access == file_access::write_only)
                    ? PROT_WRITE
                    : PROT_READ | PROT_WRITE
                )
            );

            pData_ = reinterpret_cast<uint8_t*>(mmap(nullptr, fileTotalSize_, fileMapAccess, MAP_SHARED, spFile_->nativeHandle(), 0));
            pCursor_ = pData_;

            if (pData_ == MAP_FAILED)
            {
                vfs_errorf("mmap(%s) failed with error: %s", name_.c_str(), get_last_error_as_string(errno).c_str());
                return false;
            }

            return true;
        }

		//------------------------------------------------------------------------------------------
        bool unmap()
        {
            if (pData_ && munmap(pData_, fileTotalSize_) == -1)
            {
                return false;
            }

            return true;
        }

		//------------------------------------------------------------------------------------------
        bool flush()
        {
            /*
            if (!FlushViewOfFile(pData_, 0))
            {
                return false;
            }
            */
            return true;
        }

		//------------------------------------------------------------------------------------------
        int64_t read(uint8_t *dst, int64_t sizeInBytes)
        {
            if (canMoveCursor(sizeInBytes))
            {
                memcpy(dst, pCursor_, sizeInBytes);
                pCursor_ += sizeInBytes;
                return sizeInBytes;
            }
            return 0;
        }

		//------------------------------------------------------------------------------------------
        int64_t write(const uint8_t *src, int64_t sizeInBytes)
        {
            if (canMoveCursor(sizeInBytes))
            {
                memcpy(pCursor_, src, sizeInBytes);
                pCursor_ += sizeInBytes;
                return sizeInBytes;
            }
            return 0;
        }

		//------------------------------------------------------------------------------------------
        bool isValid() const
        {
            return pData_ != nullptr;
        }

		//------------------------------------------------------------------------------------------
        int64_t totalSize() const
        {
            return fileTotalSize_;
        }

		//------------------------------------------------------------------------------------------
        bool canMoveCursor(int64_t offsetInBytes) const
        {
            return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;
        }

		//------------------------------------------------------------------------------------------
        template<typename T = uint8_t>
        T* data()
        {
            return reinterpret_cast<T*>(pData_);
        }

		//------------------------------------------------------------------------------------------
        uint8_t* data()
        {
            return data<>();
        }

		//------------------------------------------------------------------------------------------
        template<typename T = uint8_t>
        T* cursor()
        {
            return reinterpret_cast<T*>(pCursor_);
        }

		//------------------------------------------------------------------------------------------
        bool skip(int64_t offsetInBytes)
        {
            if (canMoveCursor(offsetInBytes))
            {
                pCursor_ += offsetInBytes;
                return true;
            }
            return false;
        }

	private:
		//------------------------------------------------------------------------------------------
        file_sptr   spFile_;
        path        name_;
        //HANDLE      fileMappingHandle_;
        uint8_t     *pData_;
        uint8_t     *pCursor_;
        int64_t     fileTotalSize_;
        int64_t     mappedTotalSize_;
    };
    //----------------------------------------------------------------------------------------------

} /*vfs*/
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include <boost/python.hpp>

#include "IECore/MeshPrimitiveShrinkWrapOp.h"
#include "IECore/Parameter.h"
#include "IECore/Object.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"

using namespace boost;
using namespace boost::python;

namespace IECore
{

void bindMeshPrimitiveShrinkWrapOp()
{

	typedef class_< MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPtr, boost::noncopyable, bases<MeshPrimitiveOp> > MeshPrimitiveShrinkWrapOpPyClass;
	MeshPrimitiveShrinkWrapOpPyClass( "MeshPrimitiveShrinkWrapOp", no_init )
		.def( init< >() )
		.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( MeshPrimitiveShrinkWrapOp )
	;

	INTRUSIVE_PTR_PATCH( MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPyClass );
	implicitly_convertible<MeshPrimitiveShrinkWrapOpPtr, MeshPrimitiveOpPtr>();

}

} // namespace IECore
<commit_msg>Bound enum<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include <boost/python.hpp>

#include "IECore/MeshPrimitiveShrinkWrapOp.h"
#include "IECore/Parameter.h"
#include "IECore/Object.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"

using namespace boost;
using namespace boost::python;

namespace IECore
{

void bindMeshPrimitiveShrinkWrapOp()
{

	typedef class_< MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPtr, boost::noncopyable, bases<MeshPrimitiveOp> > MeshPrimitiveShrinkWrapOpPyClass;
	scope opScope = MeshPrimitiveShrinkWrapOpPyClass( "MeshPrimitiveShrinkWrapOp", no_init )
		.def( init< >() )
		.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( MeshPrimitiveShrinkWrapOp )
	;

	enum_< MeshPrimitiveShrinkWrapOp::Method >( "Method" )
		.value( "Both", MeshPrimitiveShrinkWrapOp::Both )
		.value( "Inside", MeshPrimitiveShrinkWrapOp::Inside )
		.value( "Outside", MeshPrimitiveShrinkWrapOp::Outside )
	;

	INTRUSIVE_PTR_PATCH( MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPyClass );
	implicitly_convertible<MeshPrimitiveShrinkWrapOpPtr, MeshPrimitiveOpPtr>();

}

} // namespace IECore
<|endoftext|>


<commit_before>#ifndef MATH_HPP
#define MATH_HPP

#include <algorithm>
#include <cmath>
#include <math.h>

#define PI 3.14159265358979323846f
#define TAU 6.28318530717958647692f
#define KAPPA90 0.5522847493f

// KAPPA90 = (4/3 * (sqrt(2) - 1))
// https://de.wikipedia.org/wiki/Datei:Circle-cbezier-method2.svg

#define OE_FLOAT_INFINITY std::numeric_limits<float>::infinity()

#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(0[arr]))

namespace OrbitEngine { namespace Math {

	inline double deg2rad(double deg)
	{
		return deg * PI / 180.f;
	}

	inline double rad2deg(double rad)
	{
		return rad * 180.f / PI;
	}

	inline unsigned int nextPowerOfTwo(unsigned int x)
	{
		x--;
		x |= x >> 1;
		x |= x >> 2;
		x |= x >> 4;
		x |= x >> 8;
		x |= x >> 16;
		x++;
		return x;
	}

	template<typename T>
	inline T approximatelyEqual(T a, T b, T epsilon)
	{
		return std::abs(a - b) <= ((std::abs(a) < std::abs(b) ? std::abs(b) : std::abs(a)) * epsilon);
	}

	template<typename T>
	inline T lerp(T v0, T v1, float t) {
		return (1.f - t) * v0 + t * v1;
	}

	template<typename T>
	inline T clamp(T input, T min_, T max_) {
		return (std::max)(min_, (std::min)(input, max_));
	}

	template<typename T>
	inline T sign(T input)
	{
		return input >= (T)0 ? (T)1 : (T)-1;
	};

	template<typename A, typename B>
	A castMinMax(B in)
	{
		// only integer types

		A retVal = 0;

		if (in > 0)
			retVal = static_cast<A>(in & std::numeric_limits<A>::max());
		else if (in < 0)
			retVal = static_cast<A>(in | std::numeric_limits<A>::min());

		return retVal;
	}
} }

#endif<commit_msg>isPowerOfTwo<commit_after>#ifndef MATH_HPP
#define MATH_HPP

#include <algorithm>
#include <cmath>
#include <math.h>

#define PI 3.14159265358979323846f
#define TAU 6.28318530717958647692f
#define KAPPA90 0.5522847493f

// KAPPA90 = (4/3 * (sqrt(2) - 1))
// https://de.wikipedia.org/wiki/Datei:Circle-cbezier-method2.svg

#define OE_FLOAT_INFINITY std::numeric_limits<float>::infinity()

#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(0[arr]))

namespace OrbitEngine { namespace Math {

	inline double deg2rad(double deg)
	{
		return deg * PI / 180.f;
	}

	inline double rad2deg(double rad)
	{
		return rad * 180.f / PI;
	}

	inline unsigned int nextPowerOfTwo(unsigned int x)
	{
		x--;
		x |= x >> 1;
		x |= x >> 2;
		x |= x >> 4;
		x |= x >> 8;
		x |= x >> 16;
		x++;
		return x;
	}

	inline bool isPowerOfTwo(unsigned int x) {
		return x == 0 || (x & (x - 1)) == 0;
	}

	template<typename T>
	inline T approximatelyEqual(T a, T b, T epsilon)
	{
		return std::abs(a - b) <= ((std::abs(a) < std::abs(b) ? std::abs(b) : std::abs(a)) * epsilon);
	}

	template<typename T>
	inline T lerp(T v0, T v1, float t) {
		return (1.f - t) * v0 + t * v1;
	}

	template<typename T>
	inline T clamp(T input, T min_, T max_) {
		return (std::max)(min_, (std::min)(input, max_));
	}

	template<typename T>
	inline T sign(T input)
	{
		return input >= (T)0 ? (T)1 : (T)-1;
	};

	template<typename A, typename B>
	A castMinMax(B in)
	{
		// only integer types

		A retVal = 0;

		if (in > 0)
			retVal = static_cast<A>(in & std::numeric_limits<A>::max());
		else if (in < 0)
			retVal = static_cast<A>(in | std::numeric_limits<A>::min());

		return retVal;
	}
} }

#endif<|endoftext|>