void c_RescheduleWaitHandle::enterContextImpl(context_idx_t ctx_idx) {
  assert(getState() == STATE_SCHEDULED);

  setContextIdx(ctx_idx);
  getContext()->schedule(this, m_queue, m_priority);
}
PremultipliedImage HeadlessBackend::readStillImage() {
    return static_cast<gl::Context&>(getContext()).readFramebuffer<PremultipliedImage>(size);
}
void c_ExternalThreadEventWaitHandle::registerToContext() {
  AsioContext *ctx = getContext();
  m_ctxVecIndex = ctx->registerTo(ctx->getExternalThreadEvents(), this);
}
Exemple #4
0
void GlobalQueue::specDownloadFromDevice()
{
	getContext()->readBuffer(bundleCounter,  CL_TRUE);
	getContext()->readBuffer(bundleQueue, CL_TRUE);
}
Exemple #5
0
bool KRMaterial::bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const std::vector<KRBone *> &bones, const std::vector<KRMat4> &bind_poses, const KRViewport &viewport, const KRMat4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const KRVector3 &rim_color, float rim_power, float lod_coverage) {
    bool bLightMap = pLightMap && pCamera->settings.bEnableLightMap;
    
    getTextures();
    
    KRVector2 default_scale = KRVector2::One();
    KRVector2 default_offset = KRVector2::Zero();
    
    bool bHasReflection = m_reflectionColor != KRVector3::Zero();
    bool bDiffuseMap = m_pDiffuseMap != NULL && pCamera->settings.bEnableDiffuseMap;
    bool bNormalMap = m_pNormalMap != NULL && pCamera->settings.bEnableNormalMap;
    bool bSpecMap = m_pSpecularMap != NULL && pCamera->settings.bEnableSpecMap;
    bool bReflectionMap = m_pReflectionMap != NULL && pCamera->settings.bEnableReflectionMap && pCamera->settings.bEnableReflection && bHasReflection;
    bool bReflectionCubeMap = m_pReflectionCube != NULL && pCamera->settings.bEnableReflection && bHasReflection;
    bool bAlphaTest = (m_alpha_mode == KRMATERIAL_ALPHA_MODE_TEST) && bDiffuseMap;
    bool bAlphaBlend = (m_alpha_mode == KRMATERIAL_ALPHA_MODE_BLENDONESIDE) || (m_alpha_mode == KRMATERIAL_ALPHA_MODE_BLENDTWOSIDE);
    
    KRShader *pShader = getContext().getShaderManager()->getShader("ObjectShader", pCamera, point_lights, directional_lights, spot_lights, bones.size(), bDiffuseMap, bNormalMap, bSpecMap, bReflectionMap, bReflectionCubeMap, bLightMap, m_diffuseMapScale != default_scale && bDiffuseMap, m_specularMapScale != default_scale && bSpecMap, m_normalMapScale != default_scale && bNormalMap, m_reflectionMapScale != default_scale && bReflectionMap, m_diffuseMapOffset != default_offset && bDiffuseMap, m_specularMapOffset != default_offset && bSpecMap, m_normalMapOffset != default_offset && bNormalMap, m_reflectionMapOffset != default_offset && bReflectionMap, bAlphaTest, bAlphaBlend, renderPass, rim_power != 0.0f);

    
    KRVector4 fade_color;
    if(!getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, matModel, point_lights, directional_lights, spot_lights, 0, renderPass, rim_color, rim_power, fade_color)) {
        return false;
    }
    
    // Bind bones
    if(pShader->m_uniforms[KRShader::KRENGINE_UNIFORM_BONE_TRANSFORMS] != -1) {
        GLfloat bone_mats[256 * 16];
        GLfloat *bone_mat_component = bone_mats;
        for(int bone_index=0; bone_index < bones.size(); bone_index++) {
            KRBone *bone = bones[bone_index];
            
//                KRVector3 initialRotation = bone->getInitialLocalRotation();
//                KRVector3 rotation = bone->getLocalRotation();
//                KRVector3 initialTranslation = bone->getInitialLocalTranslation();
//                KRVector3 translation = bone->getLocalTranslation();
//                KRVector3 initialScale = bone->getInitialLocalScale();
//                KRVector3 scale = bone->getLocalScale();
//                
            //printf("%s - delta rotation: %.4f %.4f %.4f\n", bone->getName().c_str(), (rotation.x - initialRotation.x) * 180.0 / M_PI, (rotation.y - initialRotation.y) * 180.0 / M_PI, (rotation.z - initialRotation.z) * 180.0 / M_PI);
            //printf("%s - delta translation: %.4f %.4f %.4f\n", bone->getName().c_str(), translation.x - initialTranslation.x, translation.y - initialTranslation.y, translation.z - initialTranslation.z);
//                printf("%s - delta scale: %.4f %.4f %.4f\n", bone->getName().c_str(), scale.x - initialScale.x, scale.y - initialScale.y, scale.z - initialScale.z);
            
            KRMat4 skin_bone_bind_pose = bind_poses[bone_index];
            KRMat4 active_mat = bone->getActivePoseMatrix();
            KRMat4 inv_bind_mat = bone->getInverseBindPoseMatrix();
            KRMat4 inv_bind_mat2 = KRMat4::Invert(bind_poses[bone_index]);
            KRMat4 t = (inv_bind_mat * active_mat);
            KRMat4 t2 = inv_bind_mat2 * bone->getModelMatrix();
            for(int i=0; i < 16; i++) {
                *bone_mat_component++ = t[i];
            }
        }
        if(pShader->m_uniforms[KRShader::KRENGINE_UNIFORM_BONE_TRANSFORMS] != -1) {
            glUniformMatrix4fv(pShader->m_uniforms[KRShader::KRENGINE_UNIFORM_BONE_TRANSFORMS], bones.size(), GL_FALSE, bone_mats);
        }
    }

    
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_AMBIENT, m_ambientColor + pCamera->settings.ambient_intensity);
    
    if(renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
        // We pre-multiply the light color with the material color in the forward renderer
        pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_DIFFUSE, KRVector3(m_diffuseColor.x * pCamera->settings.light_intensity.x, m_diffuseColor.y * pCamera->settings.light_intensity.y, m_diffuseColor.z * pCamera->settings.light_intensity.z));
    } else {
        pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_DIFFUSE, m_diffuseColor);
    }
    
    if(renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
        // We pre-multiply the light color with the material color in the forward renderer
        pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_SPECULAR, KRVector3(m_specularColor.x * pCamera->settings.light_intensity.x, m_specularColor.y * pCamera->settings.light_intensity.y, m_specularColor.z * pCamera->settings.light_intensity.z));
    } else {
        pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_SPECULAR, m_specularColor);
    }
    
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_SHININESS, m_ns);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_REFLECTION, m_reflectionColor);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_DIFFUSETEXTURE_SCALE, m_diffuseMapScale);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_SPECULARTEXTURE_SCALE, m_specularMapScale);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_REFLECTIONTEXTURE_SCALE, m_reflectionMapScale);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_NORMALTEXTURE_SCALE, m_normalMapScale);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_DIFFUSETEXTURE_OFFSET, m_diffuseMapOffset);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_SPECULARTEXTURE_OFFSET, m_specularMapOffset);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_REFLECTIONTEXTURE_OFFSET, m_reflectionMapOffset);
    pShader->setUniform(KRShader::KRENGINE_UNIFORM_NORMALTEXTURE_OFFSET, m_normalMapOffset);

    pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_ALPHA, m_tr);
    
    if(bDiffuseMap) {
        m_pContext->getTextureManager()->selectTexture(0, m_pDiffuseMap, lod_coverage, KRTexture::TEXTURE_USAGE_DIFFUSE_MAP);
    }
    
    if(bSpecMap) {
        m_pContext->getTextureManager()->selectTexture(1, m_pSpecularMap, lod_coverage, KRTexture::TEXTURE_USAGE_SPECULAR_MAP);
    }

    if(bNormalMap) {
        m_pContext->getTextureManager()->selectTexture(2, m_pNormalMap, lod_coverage, KRTexture::TEXTURE_USAGE_NORMAL_MAP);
    }
    
    if(bReflectionCubeMap && (renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE || renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT || renderPass == KRNode::RENDER_PASS_DEFERRED_OPAQUE)) {
        m_pContext->getTextureManager()->selectTexture(4, m_pReflectionCube, lod_coverage, KRTexture::TEXTURE_USAGE_REFECTION_CUBE);
    }
    
    if(bReflectionMap && (renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE || renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT || renderPass == KRNode::RENDER_PASS_DEFERRED_OPAQUE)) {
        // GL_TEXTURE7 is used for reading the depth buffer in gBuffer pass 2 and re-used for the reflection map in gBuffer Pass 3 and in forward rendering
        m_pContext->getTextureManager()->selectTexture(7, m_pReflectionMap, lod_coverage, KRTexture::TEXTURE_USAGE_REFLECTION_MAP);
    }

    
    return true;
}
void ParallelCollisionPipeline::doCollisionResponse()
{
    core::objectmodel::BaseContext* scene = getContext();
    simulation::Node* node = dynamic_cast<simulation::Node*>(scene);
    if (node && !node->getLogTime()) node=NULL; // Only use node for time logging
    ctime_t t0 = 0;
    const std::string category = "collision";

    // then we start the creation of contacts
    if (contactManager==NULL) return; // can't go further
    VERBOSE(sout << "Create Contacts "<<contactManager->getName()<<sendl);
    if (node) t0 = node->startTime();
    contactManager->createContacts(narrowPhaseDetection->getDetectionOutputs());
    if (node) t0 = node->endTime(t0, category, contactManager, this);

    // finally we start the creation of collisionGroup

    const sofa::helper::vector<Contact*>& contacts = contactManager->getContacts();

    // First we remove all contacts with non-simulated objects and directly add them
    sofa::helper::vector<Contact*> notStaticContacts;
    long int c=0;
    for (sofa::helper::vector<Contact*>::const_iterator it = contacts.begin(); it!=contacts.end(); it++)
    {
        c+=(long int)*it;
    }
    if(c!=contactSum)
    {
        std::cout << "RESET" << std::endl;
        doRealCollisionReset();
        contactSum=c;
    }
    else
    {
        //std::cerr<<"EQUAL!"<<c<<std::endl;
    }
    for (sofa::helper::vector<Contact*>::const_iterator it = contacts.begin(); it!=contacts.end(); it++)
    {
        Contact* c = *it;
        if (!c->getCollisionModels().first->isSimulated())
        {
            c->createResponse(c->getCollisionModels().second->getContext());
        }
        else if (!c->getCollisionModels().second->isSimulated())
        {
            c->createResponse(c->getCollisionModels().first->getContext());
        }
        else
            notStaticContacts.push_back(c);
    }


    if (groupManager==NULL)
    {
        VERBOSE(sout << "Linking all contacts to Scene"<<sendl);
        for (sofa::helper::vector<Contact*>::const_iterator it = notStaticContacts.begin(); it!=notStaticContacts.end(); it++)
        {
            (*it)->createResponse(scene);
        }
    }
    else
    {
        VERBOSE(sout << "Create Groups "<<groupManager->getName()<<sendl);
        if (node) t0 = node->startTime();
        groupManager->createGroups(scene, notStaticContacts);
        if (node) t0 = node->endTime(t0, category, groupManager, this);
    }
}
LLVM_ATTRIBUTE_NORETURN
void MCWinCOFFStreamer::FatalError(const Twine &Msg) const {
  getContext().FatalError(SMLoc(), Msg);
}
Exemple #8
0
const sf::Sprite& Entity::getSprite()
{
    return getContext().getDrawingContext().getSprite();
}
Exemple #9
0
const Animation& Entity::getAnimation()
{
    return getContext().getAnimationContext().getAnimation();
}
Exemple #10
0
/* process a new piece of sensory experience */
void SkipCTS::update(bit_t b) {

    getContext();

    double alpha = switchRate(m_history.size());
    double log_alpha = fast_log(alpha);
    
    zobhash_t hash = 0;
    int skips_left, last_idx;

    // update nodes from deepest to shallowest
    for (int i=m_depth; i >= 0; i--) {
        
        // update the KT statistics, then the weighted 
        // probability for every node on this level
        const indices_list_t &il = m_indices[i];
        
        for (int j=0; j < il.size(); j++) {

            m_log_skip_preds.clear();

            getContextInfo(hash, il[j]);
            skips_left = m_auxinfo[i][j].skips_left;
            last_idx   = m_auxinfo[i][j].last_idx;

            // update the node
            int n_submodels = numSubmodels(last_idx, skips_left);

            SkipNode &n = getNode(hash, i, n_submodels);
            n.m_buf = n.m_log_prob_weighted;

            // lazy allocation of skipping prior weights
            if (n_submodels > 2 && n.m_log_skip_lik == NULL)
                lazyAllocate(n, n_submodels, skips_left);
    
            // handle the stop case
            double log_est_mul = n.logKTMul(b);
            if (n_submodels == 1) {
                n.updateKT(b, log_est_mul);
                n.m_log_prob_weighted += log_est_mul;
                n.m_buf = log_est_mul;
                continue;
            }
                 
            double log_acc = n.m_log_prob_est + log_est_mul;
            n.updateKT(b, log_est_mul);
                
            // handle the split case
            zobhash_t delta = s_zobtbl[last_idx+1][m_context[last_idx+1]];
            const SkipNode &nn = getNode(hash ^ delta, i+1, numSubmodels(last_idx+1, skips_left));
            double log_split_pred = nn.m_buf;
            log_acc = fast_logadd(log_acc, n.m_log_prob_split + log_split_pred);

            // handle the skipping case
            if (n_submodels > 2) {
                
                // update the skipping models
                for (int k=last_idx+2; k < m_depth; k++) { 
                    
                    zobhash_t h = hash ^ s_zobtbl[k][m_context[k]];
                    SkipNode &sn = getNode(h, i+1, numSubmodels(k, skips_left - 1));
                    
                    double log_skip_pred = sn.m_buf;
                    m_log_skip_preds.push_back(log_skip_pred);
                    int z = k - last_idx - 2;
                    log_acc = fast_logadd(log_acc, n.m_log_skip_lik[z] + log_skip_pred);
                }
            }

            // store the weighted probability
            n.m_log_prob_weighted = log_acc;

            assert(n.m_log_prob_weighted < n.m_buf);
            // Store the *difference* in log probability in m_buf
            n.m_buf = n.m_log_prob_weighted - n.m_buf;

            updatePosteriors(n, n_submodels, alpha, log_alpha, log_est_mul, log_split_pred);
        }
    }

    m_history.push_back(b != 0);
}
Exemple #11
0
const sf::Vector3f& Entity::getPosition()
{
    return getContext().getGeometricalContext().getPosition();
}
Exemple #12
0
/* the probability of seeing a particular symbol next */
double SkipCTS::prob(bit_t b) {

    // We proceed as with update(), except that we keep track of the symbol probability at
    // each node instead of actually updating parameters
    getContext();

    zobhash_t hash = 0;
    int skips_left, last_idx;
    double symbolLogProb = LogOneHalf; 

    // propagate the symbol probability from leaves to root 
    for (int i=m_depth; i >= 0; i--) {
        
        // update the KT statistics, then the weighted 
        // probability for every node on this level
        const indices_list_t &il = m_indices[i];
        
        for (int j=0; j < il.size(); j++) {

            getContextInfo(hash, il[j]);
            skips_left = m_auxinfo[i][j].skips_left;
            last_idx   = m_auxinfo[i][j].last_idx;

            // update the node
            int n_submodels = numSubmodels(last_idx, skips_left);

            SkipNode &n = getNode(hash, i, n_submodels);

            // handle the stop case
            double log_est_mul = n.logKTMul(b);
            if (n_submodels == 1) {
                n.m_buf = symbolLogProb = log_est_mul;
                continue;
            }
                 
            // Here we rely on the property that log_prob_est and the like are unnormalized
            // posteriors. we accumulate the symbol log probability under 'symbolLogProb' 
            symbolLogProb = n.m_log_prob_est + log_est_mul;
 
            // handle the split case
            zobhash_t delta = s_zobtbl[last_idx+1][m_context[last_idx+1]];
            const SkipNode &nn = getNode(hash ^ delta, i+1, numSubmodels(last_idx+1, skips_left));
            // recall that m_buf contains the symbol probability at the child node
            double log_split_pred = nn.m_buf;
            symbolLogProb = fast_logadd(symbolLogProb, n.m_log_prob_split + log_split_pred);

            // handle the skipping case
            if (n_submodels > 2) {
                
                // if we did not yet allocate these models, this node must never have been
                // updated. We assume (perhaps incorrectly) that none of this node's children
                // exist and pretend they return a symbol probability of 0.5 
                if (n.m_log_skip_lik == NULL) {

                    const prior_t &p = SplitSkipPrior[skips_left];
                    symbolLogProb = fast_logadd(symbolLogProb, p.skip + LogOneHalf); 
                }
                
                // mix in the symbol probability from the skipping models
                else for (int k=last_idx+2; k < m_depth; k++) { 
                    
                    zobhash_t h = hash ^ s_zobtbl[k][m_context[k]];
                    SkipNode &sn = getNode(h, i+1, numSubmodels(k, skips_left - 1));
                    
                    double log_skip_pred = sn.m_buf;
                    int z = k - last_idx - 2;
                    symbolLogProb = fast_logadd(symbolLogProb, n.m_log_skip_lik[z] + log_skip_pred);
                }
            }

            // Finally we normalize by the mixture probability at this node
            symbolLogProb -= n.m_log_prob_weighted;
            n.m_buf = symbolLogProb;

            assert(n.m_buf < 0.0);
        }
    }
   
    // our scheme assumes that the last node processed is the root; the variable 'symbolLogProb'
    // contains its symbol probability 
    return fast_exp(symbolLogProb);
}
Exemple #13
0
UnicodeString& RelativeDateFormat::format(  Calendar& cal,
                                UnicodeString& appendTo,
                                FieldPosition& pos) const {
                                
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString relativeDayString;
    UDisplayContext capitalizationContext = getContext(UDISPCTX_TYPE_CAPITALIZATION, status);
    
    // calculate the difference, in days, between 'cal' and now.
    int dayDiff = dayDifference(cal, status);

    // look up string
    int32_t len = 0;
    const UChar *theString = getStringForDay(dayDiff, len, status);
    if(U_SUCCESS(status) && (theString!=NULL)) {
        // found a relative string
        relativeDayString.setTo(theString, len);
    }

    if ( relativeDayString.length() > 0 && !fDatePattern.isEmpty() && 
         (fTimePattern.isEmpty() || fCombinedFormat == NULL || fCombinedHasDateAtStart)) {
#if !UCONFIG_NO_BREAK_ITERATION
        // capitalize relativeDayString according to context for relative, set formatter no context
        if ( u_islower(relativeDayString.char32At(0)) && fCapitalizationBrkIter!= NULL &&
             ( capitalizationContext==UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
               (capitalizationContext==UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU && fCapitalizationOfRelativeUnitsForUIListMenu) ||
               (capitalizationContext==UDISPCTX_CAPITALIZATION_FOR_STANDALONE && fCapitalizationOfRelativeUnitsForStandAlone) ) ) {
            // titlecase first word of relativeDayString
            relativeDayString.toTitle(fCapitalizationBrkIter, fLocale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
        }
#endif
        fDateTimeFormatter->setContext(UDISPCTX_CAPITALIZATION_NONE, status);
    } else {
        // set our context for the formatter
        fDateTimeFormatter->setContext(capitalizationContext, status);
    }

    if (fDatePattern.isEmpty()) {
        fDateTimeFormatter->applyPattern(fTimePattern);
        fDateTimeFormatter->format(cal,appendTo,pos);
    } else if (fTimePattern.isEmpty() || fCombinedFormat == NULL) {
        if (relativeDayString.length() > 0) {
            appendTo.append(relativeDayString);
        } else {
            fDateTimeFormatter->applyPattern(fDatePattern);
            fDateTimeFormatter->format(cal,appendTo,pos);
        }
    } else {
        UnicodeString datePattern;
        if (relativeDayString.length() > 0) {
            // Need to quote the relativeDayString to make it a legal date pattern
            relativeDayString.findAndReplace(UNICODE_STRING("'", 1), UNICODE_STRING("''", 2)); // double any existing APOSTROPHE
            relativeDayString.insert(0, APOSTROPHE); // add APOSTROPHE at beginning...
            relativeDayString.append(APOSTROPHE); // and at end
            datePattern.setTo(relativeDayString);
        } else {
            datePattern.setTo(fDatePattern);
        }
        UnicodeString combinedPattern;
        Formattable timeDatePatterns[] = { fTimePattern, datePattern };
        fCombinedFormat->format(timeDatePatterns, 2, combinedPattern, pos, status); // pos is ignored by this
        fDateTimeFormatter->applyPattern(combinedPattern);
        fDateTimeFormatter->format(cal,appendTo,pos);
    }
    
    return appendTo;
}
void style_paragraph_properties::add_child_element( xml::sax * Reader, const ::std::wstring & Ns, const ::std::wstring & Name)
{
    if (!style_paragraph_properties_content_.add_child_element(Reader, Ns, Name, getContext()))    
         CP_NOT_APPLICABLE_ELM();
}
Exemple #15
0
void c_SleepWaitHandle::unregisterFromContext() {
  AsioContext *ctx = getContext();
  ctx->unregisterFrom(ctx->getSleepEvents(), m_ctxVecIndex);
}
Exemple #16
0
void Entity::interpolate(const float interpolation)
{
    getContext().setInterpolation(interpolation);
}
Mode* ReadCommand::handle_request(User* user) {
    char buffer[1024];
    bzero(buffer, 1024);
    char* token_ptr;
    readline(user->get_socket_fd(), buffer, 1023);
    if (strcmp(buffer, "") == 0) {
        return new ReadCommand(this->getContext());
    }
    std::vector<std::string> command_list;
    token_ptr = strtok(buffer, "|");
    while (token_ptr != NULL) {
        command_list.push_back(std::string(token_ptr));
        token_ptr = strtok(NULL, "|");
    }
    int pipe_channel[2];
    pipe(pipe_channel);
    if (command_list.size() == 1) {
        std::string command = command_list[0];
        if (fork() == 0) {
            dup2(user->get_socket_fd(), STDIN_FILENO);
            dup2(pipe_channel[1], STDOUT_FILENO);
            close(pipe_channel[0]);
            close(this->getContext()->listen_sock_fd);
            execute_command(command);
        } else {
            //restore stdin/stdout
            close(pipe_channel[1]);
            int n;
            while((n = read(pipe_channel[0], buffer, 256)) > 0) {
                send(user->get_socket_fd(), buffer, n, MSG_DONTWAIT);
            }
            close(pipe_channel[0]);
        }
    } else {
        std::vector<int*> pipes;
        for (int i = 0; i < command_list.size() - 1; i++) { // i pipe for 2 commands => n-1 pipes for n commands
            int* _pipe = (int*)malloc(sizeof(int) * 2);
            if (pipe(_pipe) != 0) {
                strerror(errno);
                exit(errno);
            }
            pipes.push_back(_pipe);
        }
        int i = command_list.size() - 1;
        for (auto it = command_list.rbegin(); it != command_list.rend(); it++) {
            if (fork() == 0) { // child process
                close(pipe_channel[0]);
                close(this->getContext()->listen_sock_fd);
                if (i == 0) {
                    int* pipe_out = pipes[i];
                    lanyitin_close(pipe_out[0]);
                    dup2(user->get_socket_fd(), STDIN_FILENO);
                    dup2(pipe_out[1], STDOUT_FILENO);
                } else if (i == command_list.size() - 1) {
                    int* pipe_in = pipes[i - 1];
                    lanyitin_close(pipe_in[1]);
                    dup2(pipe_in[0], STDIN_FILENO);
                    dup2(pipe_channel[1], STDOUT_FILENO);
                } else {
                    int* pipe_in = pipes[i - 1];
                    int* pipe_out = pipes[i];
                    dup2(pipe_in[0], STDIN_FILENO);
                    dup2(pipe_out[1], STDOUT_FILENO);
                    lanyitin_close(pipe_in[1]);
                    lanyitin_close(pipe_out[0]);
                }
                execute_command((*it));
            } else { //parent process
                if (i != command_list.size() -1) {
                    lanyitin_close(pipes[i][0]);
                    lanyitin_close(pipes[i][1]);
                }
                i--;
            }
        }
        close(pipe_channel[1]);
        int n;
        while((n = read(pipe_channel[0], buffer, 256)) > 0) {
            send(user->get_socket_fd(), buffer, n, MSG_DONTWAIT);
        }
        close(pipe_channel[0]);
    }
    return new ShowPrompt(getContext());
}
Exemple #18
0
Entity& Entity::makeDrawable(const std::string& img)
{
    getContext().getDrawingContext().setSprite(Manager<sf::Texture,sf::Sprite,se::xmlTags::IMAGE>::getInstance()->getResource(img));

    return *this;
}
Exemple #19
0
// bootstrap a ciphertext to reduce noise
void FHEPubKey::reCrypt(Ctxt &ctxt)
{
  FHE_TIMER_START;

  // Some sanity checks for dummy ciphertext
  long ptxtSpace = ctxt.getPtxtSpace();
  if (ctxt.isEmpty()) return;
  if (ctxt.parts.size()==1 && ctxt.parts[0].skHandle.isOne()) {
    // Dummy encryption, just ensure that it is reduced mod p
    ZZX poly = to_ZZX(ctxt.parts[0]);
    for (long i=0; i<poly.rep.length(); i++)
      poly[i] = to_ZZ( rem(poly[i],ptxtSpace) );
    poly.normalize();
    ctxt.DummyEncrypt(poly);
    return;
  }

  assert(recryptKeyID>=0); // check that we have bootstrapping data

  long p = getContext().zMStar.getP();
  long r = getContext().alMod.getR();
  long p2r = getContext().alMod.getPPowR();

  // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}.
  long e = getContext().rcData.e;
  long ePrime = getContext().rcData.ePrime;
  long p2ePrime = power_long(p,ePrime);
  long q = power_long(p,e)+1;
  assert(e>=r);

#ifdef DEBUG_PRINTOUT
  cerr << "reCrypt: p="<<p<<", r="<<r<<", e="<<e<<" ePrime="<<ePrime
       << ", q="<<q<<endl;
#endif

  // can only bootstrap ciphertext with plaintext-space dividing p^r
  assert(p2r % ptxtSpace == 0);


#ifdef PRINT_LEVELS
  CheckCtxt(ctxt, "init");
#endif

  FHE_NTIMER_START(AAA_preProcess);

  // Make sure that this ciphertxt is in canonical form
  if (!ctxt.inCanonicalForm()) ctxt.reLinearize();

  // Mod-switch down if needed
  IndexSet s = ctxt.getPrimeSet() / getContext().specialPrimes; // set minus
  if (s.card()>2) { // leave only bottom two primes
    long frst = s.first();
    long scnd = s.next(frst);
    IndexSet s2(frst,scnd);
    s.retain(s2); // retain only first two primes
  }
  ctxt.modDownToSet(s);

  // key-switch to the bootstrapping key
  ctxt.reLinearize(recryptKeyID);

  // "raw mod-switch" to the bootstrapping mosulus q=p^e+1.
  vector<ZZX> zzParts; // the mod-switched parts, in ZZX format
  double noise = ctxt.rawModSwitch(zzParts, q);
  noise = sqrt(noise);

  // Add multiples of p2r and q to make the zzParts divisible by p^{e'}
  long maxU=0;
  for (long i=0; i<(long)zzParts.size(); i++) {
    // make divisible by p^{e'}
    long newMax = makeDivisible(zzParts[i].rep, p2ePrime, p2r, q,
				getContext().rcData.alpha);
    zzParts[i].normalize();   // normalize after working directly on the rep
    if (maxU < newMax)  maxU = newMax;
  }

  // Check that the estimated noise is still low
  if (noise + maxU*p2r*(skHwts[recryptKeyID]+1) > q/2) 
    cerr << " * noise/q after makeDivisible = "
	 << ((noise + maxU*p2r*(skHwts[recryptKeyID]+1))/q) << endl;

  for (long i=0; i<(long)zzParts.size(); i++)
    zzParts[i] /= p2ePrime;   // divide by p^{e'}

  // Multiply the post-processed cipehrtext by the encrypted sKey
#ifdef DEBUG_PRINTOUT
  cerr << "+ Before recryption ";
  decryptAndPrint(cerr, recryptEkey, *dbgKey, *dbgEa, printFlag);
#endif

  double p0size = to_double(coeffsL2Norm(zzParts[0]));
  double p1size = to_double(coeffsL2Norm(zzParts[1]));
  ctxt = recryptEkey;
  ctxt.multByConstant(zzParts[1], p1size*p1size);
  ctxt.addConstant(zzParts[0], p0size*p0size);

#ifdef DEBUG_PRINTOUT
  cerr << "+ Before linearTrans1 ";
  decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag);
#endif
  FHE_NTIMER_STOP(AAA_preProcess);

#ifdef PRINT_LEVELS
  CheckCtxt(ctxt, "after preProcess");
#endif


  // Move the powerful-basis coefficients to the plaintext slots
  FHE_NTIMER_START(AAA_LinearTransform1);
  ctxt.getContext().rcData.firstMap->apply(ctxt);
  FHE_NTIMER_STOP(AAA_LinearTransform1);


#ifdef PRINT_LEVELS
  CheckCtxt(ctxt, "after LinearTransform1");
#endif

#ifdef DEBUG_PRINTOUT
  cerr << "+ After linearTrans1 ";
  decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag);
#endif

  // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots)
  FHE_NTIMER_START(AAA_extractDigitsPacked);
  extractDigitsPacked(ctxt, e-ePrime, r, ePrime,
		      context.rcData.unpackSlotEncoding);
  FHE_NTIMER_STOP(AAA_extractDigitsPacked);


#ifdef PRINT_LEVELS
  CheckCtxt(ctxt, "after extractDigitsPacked");
#endif

#ifdef DEBUG_PRINTOUT
  cerr << "+ Before linearTrans2 ";
  decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag);
#endif

  // Move the slots back to powerful-basis coefficients
  FHE_NTIMER_START(AAA_LinearTransform2);
  ctxt.getContext().rcData.secondMap->apply(ctxt);
  FHE_NTIMER_STOP(AAA_LinearTransform2);


#ifdef PRINT_LEVELS
  CheckCtxt(ctxt, "after linearTransform2");
#endif
}
Exemple #20
0
Entity& Entity::makeSound(const std::string& soundName)
{
    getContext().getSoundContext().setSound(soundName);

    return *this;
}
Exemple #21
0
void GlobalQueue::specUploadToDevice()
{
	getContext()->writeBuffer(bundleCounter, CL_TRUE);
	getContext()->writeBuffer(bundleQueue,  CL_TRUE);
}
Exemple #22
0
Entity& Entity::makePhysic(const std::string& body, b2World& world)
{
    getContext().getPhysicContext().addBodyToWorld(body,world,getPosition().x, getPosition().y);
    return *this;
}
Exemple #23
0
bool GrGpuGL::programUnitTest() {

    GrTextureDesc dummyDesc;
    dummyDesc.fConfig = kSkia8888_PM_GrPixelConfig;
    dummyDesc.fWidth = 34;
    dummyDesc.fHeight = 18;
    SkAutoTUnref<GrTexture> dummyTexture1(this->createTexture(dummyDesc, NULL, 0));
    dummyDesc.fConfig = kAlpha_8_GrPixelConfig;
    dummyDesc.fWidth = 16;
    dummyDesc.fHeight = 22;
    SkAutoTUnref<GrTexture> dummyTexture2(this->createTexture(dummyDesc, NULL, 0));

    // GrGLSLGeneration glslGeneration =
            GrGetGLSLGeneration(this->glBinding(), this->glInterface());
    static const int STAGE_OPTS[] = {
        0,
        StageDesc::kNoPerspective_OptFlagBit,
    };
    static const int IN_CONFIG_FLAGS[] = {
        StageDesc::kNone_InConfigFlag,
        StageDesc::kSmearAlpha_InConfigFlag,
    };

    static const int NUM_TESTS = 512;

    GrRandom random;
    for (int t = 0; t < NUM_TESTS; ++t) {

#if 0
        GrPrintf("\nTest Program %d\n-------------\n", t);
        static const int stop = -1;
        if (t == stop) {
            int breakpointhere = 9;
        }
#endif

        ProgramDesc pdesc;
        pdesc.fVertexLayout = 0;
        pdesc.fEmitsPointSize = random.nextF() > .5f;
        pdesc.fColorInput = random_int(&random, ProgramDesc::kColorInputCnt);
        pdesc.fCoverageInput = random_int(&random, ProgramDesc::kColorInputCnt);

        pdesc.fColorFilterXfermode = random_int(&random, SkXfermode::kCoeffModesCnt);

        pdesc.fFirstCoverageStage = random_int(&random, GrDrawState::kNumStages);

        pdesc.fVertexLayout |= random_bool(&random) ?
                                    GrDrawTarget::kCoverage_VertexLayoutBit :
                                    0;

#if GR_GL_EXPERIMENTAL_GS
        pdesc.fExperimentalGS = this->getCaps().geometryShaderSupport() &&
                                random_bool(&random);
#endif

        bool edgeAA = random_bool(&random);
        if (edgeAA) {
            pdesc.fVertexLayout |= GrDrawTarget::kEdge_VertexLayoutBit;
            if (this->getCaps().shaderDerivativeSupport()) {
                pdesc.fVertexEdgeType = (GrDrawState::VertexEdgeType) random_int(&random, GrDrawState::kVertexEdgeTypeCnt);
            } else {
                pdesc.fVertexEdgeType = GrDrawState::kHairLine_EdgeType;
            }
        } else {
        }

        pdesc.fColorMatrixEnabled = random_bool(&random);

        if (this->getCaps().dualSourceBlendingSupport()) {
            pdesc.fDualSrcOutput = random_int(&random, ProgramDesc::kDualSrcOutputCnt);
        } else {
            pdesc.fDualSrcOutput = ProgramDesc::kNone_DualSrcOutput;
        }

        SkAutoTUnref<const GrCustomStage> customStages[GrDrawState::kNumStages];

        for (int s = 0; s < GrDrawState::kNumStages; ++s) {
            StageDesc& stage = pdesc.fStages[s];
            // enable the stage?
            if (random_bool(&random)) {
                // use separate tex coords?
                if (random_bool(&random)) {
                    int t = random_int(&random, GrDrawState::kMaxTexCoords);
                    pdesc.fVertexLayout |= StageTexCoordVertexLayoutBit(s, t);
                }
                stage.setEnabled(true);
            }
            // use text-formatted verts?
            if (random_bool(&random)) {
                pdesc.fVertexLayout |= kTextFormat_VertexLayoutBit;
            }

            stage.fCustomStageKey = 0;

            stage.fOptFlags |= STAGE_OPTS[random_int(&random, GR_ARRAY_COUNT(STAGE_OPTS))];
            stage.fInConfigFlags = IN_CONFIG_FLAGS[random_int(&random, GR_ARRAY_COUNT(IN_CONFIG_FLAGS))];

            if (stage.isEnabled()) {
                GrTexture* dummyTextures[] = {dummyTexture1.get(), dummyTexture2.get()};
                customStages[s].reset(create_random_effect(&stage,
                                                           &random,
                                                           getContext(),
                                                           dummyTextures));
                if (NULL != customStages[s]) {
                    stage.fCustomStageKey =
                        customStages[s]->getFactory().glStageKey(*customStages[s], this->glCaps());
                }
            }
        }
        GR_STATIC_ASSERT(sizeof(customStages) ==
                         GrDrawState::kNumStages * sizeof(GrCustomStage*));
        const GrCustomStage** stages = reinterpret_cast<const GrCustomStage**>(&customStages);
        SkAutoTUnref<GrGLProgram> program(GrGLProgram::Create(this->glContextInfo(),
                                                              pdesc,
                                                              stages));
        if (NULL == program.get()) {
            return false;
        }
    }
    return true;
}
Exemple #24
0
void Pipeline::computeCollisionResponse()
{
	simulation::tree::GNode* root = dynamic_cast<simulation::tree::GNode*>(getContext());
	if(root == NULL) return;
	doCollisionResponse();
}
gfx::Renderable& HeadlessBackend::getDefaultRenderable() {
    if (!resource) {
        resource = std::make_unique<HeadlessRenderableResource>(static_cast<gl::Context&>(getContext()), size);
    }
    return *this;
}
Exemple #26
0
void AnalysisSolver::factor(const system_type& system) {

    // start at 1 since 0 is current solver
    for( unsigned i = 1, n = solvers.size() ; i < n; ++i ) {
        solvers[i]->factor(system);
    }



    typedef system_type::dmat dmat;

    if( condest.getValue() ) {

        dmat kkt;

        kkt.setZero(system.size(), system.size());

        kkt <<
            dmat(system.H), dmat(-system.J.transpose()),
            dmat(-system.J), dmat(-system.C);

        system_type::vec eigen = kkt.jacobiSvd().singularValues();

        real min = eigen.tail<1>()(0);
        real max = eigen(0);

        if( min < std::numeric_limits<real>::epsilon() ) std::cout << "AnalysisSolver: singular KKT system"<<std::endl;
        else
        {
            const real cond = max/min;
            std::cout << "condition number (KKT system): " << cond << " ("<<max<<"/"<<min<<")"<<std::endl;
            std::cout << "required precision (KKT system):  "<<ceil(log(cond))<<" bits"<<std::endl;
        }


        eigen = dmat(system.H).jacobiSvd().singularValues();

        min = eigen.tail<1>()(0);
        max = eigen(0);

        if( min < std::numeric_limits<real>::epsilon() ) std::cout << "AnalysisSolver: singular implicit system"<<std::endl;
        else
        {
            const real cond = max/min;
            std::cout << "condition number (implicit system): " << cond << " ("<<max<<"/"<<min<<")"<<std::endl;
            std::cout << "required precision (implicit system):  "<<ceil(log(cond))<<" bits"<<std::endl;
        }
    }


     if( eigenvaluesign.getValue() ) {


        Eigen::EigenSolver<dmat> es( dmat(system.H) );
//        Eigen::MatrixXcd D = es.eigenvalues().asDiagonal();
        unsigned positive = 0, negative = 0;
        for( dmat::Index i =0 ; i< es.eigenvalues().rows() ; ++i )
            if( es.eigenvalues()[i].real() < 0 ) negative++;
            else positive++;


        std::cout << "eigenvalues H: neg="<<negative<<" pos="<<positive<<std::endl;
        if( negative )
        {
            getContext()->getRootContext()->setAnimate(false);

            std::cerr<<es.eigenvalues().array().abs().minCoeff()<<std::endl;
            std::cerr<<" $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n";
        }

    }


    // TODO add more as needed
}
  bool AlchemyCreateProfile::loadParams()
  {
    FrameworkOptions& options(getOptions());
    FrameworkOptions::VariablesMap& vm = options.getVariablesMap();

    if (vm.count(s_optionName))
    {
      m_name = vm[s_optionName].as<std::string>();
    }
    else
    {
      getContext() << Context::PRIORITY_error
                   << "Profile name not specified"
                   << Context::endl;
      return false;
    }

    // get training file name
    if (vm.count(s_optionTrain))
    {
      m_trainFile = vm[s_optionTrain].as<std::string>();
    }
    else
    {
      getContext() << Context::PRIORITY_error
                   << "Training file not specified"
                   << Context::endl;
      return false;
    }

    if (!boost::filesystem::exists(
          boost::filesystem::path(m_trainFile, boost::filesystem::native)))
    {
      getContext() << Context::PRIORITY_error
                   << "Training file '" << m_trainFile << "' does not exist"
                   << Context::endl;
      return false;
    }

    // get profile file name
    if (vm.count(s_optionProfile))
    {
      m_profileFile = vm[s_optionProfile].as<std::string>();
    }
    else
    {
      getContext() << Context::PRIORITY_error
                   << "Profile file not specified"
                   << Context::endl;
      return false;
    }

    // get number of layers
    if (vm.count(s_optionLayers))
    {
      m_numLayers = vm[s_optionLayers].as<int>();
    }

    // get number of units
    if (vm.count(s_optionUnits))
    {
      m_numUnits = vm[s_optionUnits].as<int>();
    }

    // get number of days
    if (vm.count(s_optionDays))
    {
      m_numDays = vm[s_optionDays].as<int>();
    }
    else
    {
      getContext() << Context::PRIORITY_error
                   << "Number of days wasn't specified"
                   << Context::endl;
      return false;
    }

    if (m_numDays <= 0)
    {
      getContext() << Context::PRIORITY_error
                   << "Invalid number of days specified (must be > 0)"
                   << Context::endl;
      return false;
    }

    return true;
  }
Exemple #28
0
void c_SleepWaitHandle::registerToContext() {
  AsioContext *ctx = getContext();
  m_ctxVecIndex = ctx->registerTo(ctx->getSleepEvents(), this);
}
void c_ExternalThreadEventWaitHandle::unregisterFromContext() {
  AsioContext *ctx = getContext();
  ctx->unregisterFrom(ctx->getExternalThreadEvents(), m_ctxVecIndex);
}
Exemple #30
0
void OutputDeviceNode::deviceParamsDidChange()
{
	getContext()->initializeAllNodes();

	getContext()->setEnabled( mWasEnabledBeforeParamsChange );
}