/* * private functions * */ void mode_bounce::configure_pointer(mode_bounce_pointer *pPointer, size_t pSize) { pPointer->size = pSize; pPointer->position = -1.0f; pPointer->increasing = -1.0f; pPointer->rotationPtr = randomf(0.0f, 359.0f); pPointer->speed = randomf(0.3f, 3.0f); pPointer->colorSpeed = randomf(20.0f, 50.0f); pPointer->acceleration = 0.0f; pPointer->colorAcceleration = 0.0f; pPointer->color = hue_float_to_rgb(pPointer->rotationPtr); pPointer->nextColor = hue_float_to_rgb(pPointer->rotationPtr); }
/* ---------------------------------------------------------------------------- * Emits the particles, regardless of the timer. * manager: The particle manager to place these particles on. */ void particle_generator::emit(particle_manager &manager) { size_t final_nr = max( 0, (int) number + randomi((int) (0 - number_deviation), (int) number_deviation) ); for(size_t p = 0; p < final_nr; ++p) { particle new_p = base_particle; new_p.duration = max( 0.0f, new_p.duration + randomf(-duration_deviation, duration_deviation) ); new_p.time = new_p.duration; new_p.friction += randomf(-friction_deviation, friction_deviation); new_p.gravity += randomf(-gravity_deviation, gravity_deviation); new_p.x += randomf(-x_deviation, x_deviation); new_p.y += randomf(-y_deviation, y_deviation); new_p.size = max( 0.0f, new_p.size + randomf(-size_deviation, size_deviation) ); //For speed, let's decide if we should use //(speed_x and speed_y) or (speed and angle). //We'll use whichever one is not all zeros. if(angle != 0 || speed != 0) { angle_to_coordinates( angle + randomf(-angle_deviation, angle_deviation), speed + randomf(-speed_deviation, speed_deviation), &new_p.speed_x, &new_p.speed_y ); } else { new_p.speed_x += randomf(-speed_x_deviation, speed_x_deviation); new_p.speed_y += randomf(-speed_y_deviation, speed_y_deviation); } manager.add(new_p); } }
BALL() { r = random(20) + 20; x = random(LEN - r * 2) + r; y = random(WID - r * 2) + r; vx = (6 * randomf() + 0.1f) * (random(2) * 2.0 - 1); vy = (6 * randomf() + 0.1f) * (random(2) * 2.0 - 1); color = HSVtoRGB(randomf() * 360.0f, 1.0f, 0.8f); float a = randomf();//随机下每个对象的摩擦系数 fa = 1 / (100.0); goon = 1; }
/* ---------------------------------------------------------------------------- * Gives an Onion some Pikmin, and makes the Onion spew seeds out, ** depending on how many Pikmin there are in the field (don't spew if 100). */ void give_pikmin_to_onion(onion* o, const unsigned amount) { unsigned total_after = pikmin_list.size() + amount; unsigned pikmin_to_spit = amount; unsigned pikmin_to_keep = 0; // Pikmin to keep inside the Onion, without spitting. if(total_after > max_pikmin_in_field) { pikmin_to_keep = total_after - max_pikmin_in_field; pikmin_to_spit = amount - pikmin_to_keep; } for(unsigned p = 0; p < pikmin_to_spit; p++) { float angle = randomf(0, M_PI * 2); float sx = cos(angle) * 60; float sy = sin(angle) * 60; pikmin* new_pikmin = new pikmin(o->x, o->y, o->oni_type->pik_type, 0, ""); new_pikmin->set_state(PIKMIN_STATE_BURIED); new_pikmin->z = 320; new_pikmin->speed_z = 200; new_pikmin->speed_x = sx; new_pikmin->speed_y = sy; create_mob(new_pikmin); } for(unsigned p = 0; p < pikmin_to_keep; p++) { pikmin_in_onions[o->oni_type->pik_type]++; } }
// 主函数 int main( int argc, char* argv[] ) { int i, ms_x = -1024, ms_y = -1024, exitflag = 0; int fps = 60; double dtime; int mode = preinit( argc, argv ); // 记录初始化模式 if ( mode < 0 ) return 0; randomize(); // 初始化随机种子 initgraph( -1, -1 ); // 打开图形窗口,以全屏模式 showmouse( mode ); sc_width = getwidth(); sc_heigh = getheight(); // 初始化所有星星 for ( i = 0; i < g_max; i++ ) { InitStar( i ); star[i].x = randomf(); } // 绘制星空,按任意键或移动鼠标退出 setfont( 12, 6, "宋体" ); setrendermode( RENDER_MANUAL ); dtime = fclock(); while ( kbmsg() ) getkey(); for ( ; !exitflag && is_run() && kbmsg() == 0; delay_fps( fps ) ) { //每秒画120帧,kbhit(1)是获取键盘任意键的消息,详见pdf // 如果有鼠标消息 while ( mousemsg() ) { mouse_msg msg = getmouse(); if ( ms_x <= -1024 ) { ms_x = msg.x; ms_y = msg.y; } // 处理鼠标,移动超出范围就退出 if ( mode == 0 ) { // 仅全屏模式才处理鼠标 int x = msg.x, y = msg.y; x -= ms_x; y -= ms_y; if ( x * x + y * y > 400 ) exitflag = 1; } } // 显示星星 double dt = 1.0 / fps; //fclock() - dtime; dtime += dt; for ( int i = 0; i < g_max; i++ ) { MoveStar( i, dt ); } // 显示FPS { char str[60]; sprintf( str, "%8.2f FPS", getfps()); outtextxy( 0, 0, str ); //显示fps } } closegraph(); // 关闭图形窗口 return 0; }
// 初始化星星 void InitStar( int i ) { double speed = 0.006; star[i].x = 0; star[i].y = random( sc_heigh ); star[i].step = randomf() * speed * 0.9 + speed * 0.1; star[i].color = ( int )( star[i].step * 255 / speed + 0.5 ); // 速度越快,颜色越亮 if ( star[i].color > 255 ) { star[i].color = 255; } star[i].color = RGB( star[i].color, star[i].color, star[i].color ); }
TapNoteScore GetTapNoteScore() { float fRand = randomf(0,1); float fCumulativePercent = 0; for( int i=0; i<=TNS_MARVELOUS; i++ ) { fCumulativePercent += fPercent[i]; if( fRand <= fCumulativePercent+1e-4 ) /* rounding error */ return (TapNoteScore)i; } ASSERT(0); // the fCumulativePercents must sum to 1.0, so we should never get here! return TNS_MARVELOUS; }
void Inventory::Update( float fDelta ) { if( m_pPlayerState->m_bAttackEndedThisUpdate ) m_soundItemEnding.Play(false); // TODO: remove use of PlayerNumber PlayerNumber pn = m_pPlayerState->m_PlayerNumber; // check to see if they deserve a new item if( STATSMAN->m_CurStageStats.m_player[pn].m_iCurCombo != m_iLastSeenCombo ) { unsigned int iOldCombo = m_iLastSeenCombo; m_iLastSeenCombo = STATSMAN->m_CurStageStats.m_player[pn].m_iCurCombo; unsigned int iNewCombo = m_iLastSeenCombo; #define CROSSED(i) (iOldCombo<i)&&(iNewCombo>=i) #define BROKE_ABOVE(i) (iNewCombo<iOldCombo)&&(iOldCombo>=i) for( unsigned i=0; i<g_Items.size(); i++ ) { bool bEarnedThisItem = false; if( PREFSMAN->m_bBreakComboToGetItem ) bEarnedThisItem = BROKE_ABOVE(g_Items[i].iCombo); else bEarnedThisItem = CROSSED(g_Items[i].iCombo); if( bEarnedThisItem ) { AwardItem( i ); break; } } } Song &song = *GAMESTATE->m_pCurSong; // use items if this player is CPU-controlled if( m_pPlayerState->m_PlayerController != PC_HUMAN && GAMESTATE->m_Position.m_fSongBeat < song.GetLastBeat() ) { // every 1 seconds, try to use an item int iLastSecond = (int)(RageTimer::GetTimeSinceStartFast() - fDelta); int iThisSecond = (int)RageTimer::GetTimeSinceStartFast(); if( iLastSecond != iThisSecond ) { for( int s=0; s<NUM_INVENTORY_SLOTS; s++ ) if( !m_pPlayerState->m_Inventory[s].IsBlank() ) if( randomf(0,1) < ITEM_USE_PROBABILITY ) UseItem( s ); } } }
void initpolys(struct polys* p, int npoly, int npoint) //初始化多边形队列组 { int i,j; p->n_poly = npoly; j = 0; p->p[j].n_point = npoint; for (i=0; i<npoint; ++i) { p->p[j].p[i].x = random(width); p->p[j].p[i].y = random(height); p->p[j].p[i].dx = (randomf() * 2 + 1); p->p[j].p[i].dy = (randomf() * 2 + 1); p->p[j].p[i].color = 0; p->p[j].p[i].prevcolor = 0; p->p[j].p[i].nextcolor = hsv2rgb((float)random(360), 1.0f, 0.5f); p->p[j].p[i].chtime = 1000; p->p[j].p[i].nowtime = 0; p->p[j].p[i].nextcolortime = 1000; } for (j=1; j<npoly; ++j) { p->p[j] = p->p[j-1]; } }
/* ---------------------------------------------------------------------------- * Ticks some logic specific to Pikmin. */ void pikmin::tick_class_specifics() { //Carrying object. if(carrying_mob) { if(!carrying_mob->carry_info) { fsm.run_event(MOB_EVENT_FOCUSED_MOB_UNCARRIABLE); } } //Is it dead? if(health <= 0) { dead = true; } if(dead) { to_delete = true; pikmin_fsm::notify_leader_release(this, NULL, NULL); particle par( PARTICLE_TYPE_PIKMIN_SPIRIT, pos, LARGE_FLOAT, pik_type->radius * 2, 2.0f ); par.bitmap = bmp_pikmin_spirit; par.speed.x = randomf(-20, 20); par.speed.y = randomf(-70, -30); par.friction = 0.8; par.gravity = -0.2; par.color = pik_type->main_color; particles.add(par); sfx_pikmin_dying.play(0.03, false); } //Tick the timer for the "missed" attack animation. missed_attack_timer.tick(delta_t); }
void mode_bounce::pointer_tasks(mode_bounce_pointer *pPointer, float pStep) { pPointer->position = pPointer->position + pStep * pPointer->increasing * (pPointer->speed + pPointer->acceleration); if(pPointer->position < 0.0f) pPointer->position = 0.0f; if(pPointer->position > 1.0f) pPointer->position = 1.0f; if(pPointer->position == 0.0f || pPointer->position == 1.0f) { pPointer->increasing = pPointer->increasing * -1.0f; pPointer->color = pPointer->nextColor; //pPointer->rotationPtr = pPointer->rotationPtr - (pPointer->colorSpeed + pPointer->colorAcceleration); pPointer->rotationPtr = pPointer->rotationPtr+ randomf(40.0f,319.9f); if(pPointer->rotationPtr > 359.0f) pPointer->rotationPtr = pPointer->rotationPtr - 359.0f; pPointer->nextColor = hue_float_to_rgb(pPointer->rotationPtr); } if(pPointer->acceleration > 0.0) pPointer->acceleration = pPointer->acceleration - 1.0f; if(pPointer->colorAcceleration > 0.0) pPointer->colorAcceleration = pPointer->colorAcceleration - 0.5f; }
/* ---------------------------------------------------------------------------- * Spews out the converted seeds. */ void converter::spew() { size_t total_to_spit = amount_in_buffer * con_type->pikmin_per_conversion; for(size_t s = 0; s < total_to_spit; ++s) { if(pikmin_list.size() == max_pikmin_in_field) break; float horizontal_strength = CONVERTER_SPEW_H_SPEED + randomf( -CONVERTER_SPEW_H_SPEED_DEVIATION, CONVERTER_SPEW_H_SPEED_DEVIATION ); spew_pikmin_seed( pos, z + CONVERTER_NEW_SEED_Z_OFFSET, current_type, next_spew_angle, horizontal_strength, CONVERTER_SPEW_V_SPEED ); next_spew_angle += CONVERTER_SPEW_ANGLE_SHIFT; next_spew_angle = normalize_angle(next_spew_angle); } amount_in_buffer = 0; }
void Actor::BeginDraw() // set the world matrix and calculate actor properties { DISPLAY->PushMatrix(); // we're actually going to do some drawing in this function // // set temporary drawing properties based on Effects // if( m_Effect == no_effect ) { m_pTempState = &m_current; } else { m_pTempState = &m_tempState; m_tempState = m_current; /* EffectPeriodSeconds is the total time of the effect (including delay). * m_fEffectDelay is the amount of time to stick on 0%. Offset shifts the * entire thing forwards. For example, if m_fEffectPeriodSeconds is 1, * the effect can happen from .40 to .55 by setting offset to .40 and * delay to .85. */ const float fTotalPeriod = m_fEffectPeriodSeconds + m_fEffectDelay; CHECKPOINT_M( ssprintf("%f = %f + %f", fTotalPeriod, m_fEffectPeriodSeconds, m_fEffectDelay) ); const float fSecsIntoPeriod = fmodfp( m_fSecsIntoEffect+m_fEffectOffset, fTotalPeriod ); CHECKPOINT_M( ssprintf("%f = fmodfp(%f + %f, %f)", fSecsIntoPeriod, m_fSecsIntoEffect, m_fEffectOffset, fTotalPeriod) ); float fPercentThroughEffect = SCALE( fSecsIntoPeriod, 0, m_fEffectPeriodSeconds, 0, 1 ); CHECKPOINT_M( ssprintf("%f = SCALE(%f, 0, %f, 0, 1)", fPercentThroughEffect, fSecsIntoPeriod, m_fEffectPeriodSeconds) ); fPercentThroughEffect = clamp( fPercentThroughEffect, 0, 1 ); ASSERT_M( fPercentThroughEffect >= 0 && fPercentThroughEffect <= 1, ssprintf("%f", fPercentThroughEffect) ); bool bBlinkOn = fPercentThroughEffect > 0.5f; float fPercentBetweenColors = sinf( (fPercentThroughEffect + 0.25f) * 2 * PI ) / 2 + 0.5f; ASSERT_M( fPercentBetweenColors >= 0 && fPercentBetweenColors <= 1, ssprintf("%f, %f", fPercentBetweenColors, fPercentThroughEffect) ); float fOriginalAlpha = m_tempState.diffuse[0].a; int i; switch( m_Effect ) { case diffuse_blink: /* XXX: Should diffuse_blink and diffuse_shift multiply the tempState color? * (That would have the same effect with 1,1,1,1, and allow tweening the diffuse * while blinking and shifting.) */ for(i=0; i<4; i++) m_tempState.diffuse[i] = bBlinkOn ? m_effectColor1 : m_effectColor2; break; case diffuse_shift: for(i=0; i<4; i++) m_tempState.diffuse[i] = m_effectColor1*fPercentBetweenColors + m_effectColor2*(1.0f-fPercentBetweenColors); break; case glow_blink: m_tempState.glow = bBlinkOn ? m_effectColor1 : m_effectColor2; m_tempState.glow.a *= fOriginalAlpha; // don't glow if the Actor is transparent! break; case glow_shift: m_tempState.glow = m_effectColor1*fPercentBetweenColors + m_effectColor2*(1.0f-fPercentBetweenColors); m_tempState.glow.a *= fOriginalAlpha; // don't glow if the Actor is transparent! break; case rainbow: m_tempState.diffuse[0] = RageColor( cosf( fPercentBetweenColors*2*PI ) * 0.5f + 0.5f, cosf( fPercentBetweenColors*2*PI + PI * 2.0f / 3.0f ) * 0.5f + 0.5f, cosf( fPercentBetweenColors*2*PI + PI * 4.0f / 3.0f) * 0.5f + 0.5f, fOriginalAlpha ); for( i=1; i<4; i++ ) m_tempState.diffuse[i] = m_tempState.diffuse[0]; break; case wag: m_tempState.rotation += m_vEffectMagnitude * sinf( fPercentThroughEffect * 2.0f * PI ); break; case spin: // nothing needs to be here break; case vibrate: m_tempState.pos.x += m_vEffectMagnitude.x * randomf(-1.0f, 1.0f) * GetZoom(); m_tempState.pos.y += m_vEffectMagnitude.y * randomf(-1.0f, 1.0f) * GetZoom(); m_tempState.pos.z += m_vEffectMagnitude.z * randomf(-1.0f, 1.0f) * GetZoom(); break; case bounce: { float fPercentOffset = sinf( fPercentThroughEffect*PI ); m_tempState.pos += m_vEffectMagnitude * fPercentOffset; m_tempState.pos.x = roundf( m_tempState.pos.x ); m_tempState.pos.y = roundf( m_tempState.pos.y ); m_tempState.pos.z = roundf( m_tempState.pos.z ); } break; case bob: { float fPercentOffset = sinf( fPercentThroughEffect*PI*2 ); m_tempState.pos += m_vEffectMagnitude * fPercentOffset; m_tempState.pos.x = roundf( m_tempState.pos.x ); m_tempState.pos.y = roundf( m_tempState.pos.y ); m_tempState.pos.z = roundf( m_tempState.pos.z ); } break; case pulse: { float fMinZoom = m_vEffectMagnitude[0]; float fMaxZoom = m_vEffectMagnitude[1]; float fPercentOffset = sinf( fPercentThroughEffect*PI ); float fZoom = SCALE( fPercentOffset, 0.f, 1.f, fMinZoom, fMaxZoom ); m_tempState.scale *= fZoom; } break; default: ASSERT(0); // invalid Effect } } DISPLAY->Translate( m_pTempState->pos.x, m_pTempState->pos.y, m_pTempState->pos.z ); DISPLAY->Scale( m_pTempState->scale.x * m_baseScale.x, m_pTempState->scale.y * m_baseScale.y, m_pTempState->scale.z * m_baseScale.z ); /* The only time rotation and quat should normally be used simultaneously * is for m_baseRotation. */ if( m_pTempState->rotation.x + m_baseRotation.x != 0 ) DISPLAY->RotateX( m_pTempState->rotation.x + m_baseRotation.x ); if( m_pTempState->rotation.y + m_baseRotation.y != 0 ) DISPLAY->RotateY( m_pTempState->rotation.y + m_baseRotation.y ); if( m_pTempState->rotation.z + m_baseRotation.z != 0 ) DISPLAY->RotateZ( m_pTempState->rotation.z + m_baseRotation.z ); if( m_pTempState->quat.x != 0 || m_pTempState->quat.y != 0 || m_pTempState->quat.z != 0 || m_pTempState->quat.w != 1 ) { RageMatrix mat; RageMatrixFromQuat( &mat, m_pTempState->quat ); DISPLAY->MultMatrix(mat); } }
void ScreenJukebox::SetSong() { ThemeMetric<bool> ALLOW_ADVANCED_MODIFIERS(m_sName,"AllowAdvancedModifiers"); vector<Song*> vSongs; /* Check to see if there is a theme course. If there is a course that has * the exact same name as the theme, then we pick a song from this course. */ Course *pCourse = SONGMAN->GetCourseFromName( THEME->GetCurThemeName() ); if( pCourse != NULL ) for ( unsigned i = 0; i < pCourse->m_vEntries.size(); i++ ) if( pCourse->m_vEntries[i].IsFixedSong() ) vSongs.push_back( pCourse->m_vEntries[i].songID.ToSong() ); if ( vSongs.size() == 0 ) vSongs = SONGMAN->GetSongs( GAMESTATE->m_sPreferredSongGroup ); // Still nothing? if( vSongs.size() == 0 ) return; // Calculate what difficulties to show vector<Difficulty> vDifficultiesToShow; if( m_bDemonstration ) { // HACK: This belongs in ScreenDemonstration. ThemeMetricDifficultiesToShow DIFFICULTIES_TO_SHOW_HERE(m_sName,"DifficultiesToShow"); vDifficultiesToShow = DIFFICULTIES_TO_SHOW_HERE.GetValue(); } else { if( GAMESTATE->m_PreferredDifficulty[PLAYER_1] != Difficulty_Invalid ) { vDifficultiesToShow.push_back( GAMESTATE->m_PreferredDifficulty[PLAYER_1] ); } else { FOREACH_ENUM( Difficulty, dc ) vDifficultiesToShow.push_back( dc ); } } ASSERT( !vDifficultiesToShow.empty() ); // Search for a Song and Steps to play during the demo. for( int i=0; i<1000; i++ ) { Song* pSong = vSongs[RandomInt(vSongs.size())]; ASSERT( pSong != NULL ); if( !pSong->HasMusic() ) continue; // skip if( !pSong->NormallyDisplayed() ) continue; if( !pSong->ShowInDemonstrationAndRanking() ) continue; // skip Difficulty dc = vDifficultiesToShow[ RandomInt(vDifficultiesToShow.size()) ]; Steps* pSteps = SongUtil::GetStepsByDifficulty( pSong, GAMESTATE->GetCurrentStyle()->m_StepsType, dc ); if( pSteps == NULL ) continue; // skip if( !PREFSMAN->m_bAutogenSteps && pSteps->IsAutogen()) continue; // skip // Found something we can use! GAMESTATE->m_pCurSong.Set( pSong ); // We just changed the song. Reset the original sync data. AdjustSync::ResetOriginalSyncData(); FOREACH_PlayerNumber( p ) GAMESTATE->m_pCurSteps[p].Set( pSteps ); bool bShowModifiers = randomf(0,1) <= SHOW_COURSE_MODIFIERS_PROBABILITY; if( bShowModifiers ) { /* If we have a modifier course containing this song, apply its * modifiers. Only check fixed course entries. */ vector<Course*> apCourses; SONGMAN->GetAllCourses( apCourses, false ); vector<const CourseEntry *> apOptions; vector<Course*> apPossibleCourses; for( unsigned j = 0; j < apCourses.size(); ++j ) { Course *lCourse = apCourses[j]; const CourseEntry *pEntry = lCourse->FindFixedSong( pSong ); if( pEntry == NULL || pEntry->attacks.size() == 0 ) continue; if( !ALLOW_ADVANCED_MODIFIERS ) { // There are some confusing mods that we don't want to show in demonstration. bool bModsAreOkToShow = true; AttackArray aAttacks = pEntry->attacks; if( !pEntry->sModifiers.empty() ) aAttacks.push_back( Attack::FromGlobalCourseModifier( pEntry->sModifiers ) ); FOREACH_CONST( Attack, aAttacks, a ) { RString s = a->sModifiers; s.MakeLower(); // todo: allow themers to modify this list? -aj if( s.find("dark") != string::npos || s.find("stealth") != string::npos ) { bModsAreOkToShow = false; break; } } if( !bModsAreOkToShow ) continue; // skip } apOptions.push_back( pEntry ); apPossibleCourses.push_back( pCourse ); } if( !apOptions.empty() ) { int iIndex = RandomInt( apOptions.size() ); m_pCourseEntry = apOptions[iIndex]; Course *lCourse = apPossibleCourses[iIndex]; PlayMode pm = CourseTypeToPlayMode( lCourse->GetCourseType() ); GAMESTATE->m_PlayMode.Set( pm ); GAMESTATE->m_pCurCourse.Set( lCourse ); FOREACH_PlayerNumber( p ) { GAMESTATE->m_pCurTrail[p].Set( lCourse->GetTrail( GAMESTATE->GetCurrentStyle()->m_StepsType ) ); ASSERT( GAMESTATE->m_pCurTrail[p] != NULL ); } }
///////////////////////////////////////////////// // 主函数 ///////////////////////////////////////////////// int main(int argc, char* argv[]) { // 初始化绘图窗口及颜色 setinitmode(0x005, 0, 0); if (argc < 2) { MessageBoxW(NULL, L"本屏幕保护程序无配置", L"JuliaSet", MB_OK); return 0; } else if (stricmp(argv[1], "/p") == 0) { HWND hwnd; sscanf(argv[2], "%d", &hwnd); attachHWND(hwnd); setinitmode(0x107, 0, 0); } else if (stricmp(argv[1], "/s")) { MessageBoxW(NULL, L"本屏幕保护程序无配置", L"JuliaSet", MB_OK); return 0; } //initgraph(320, 240); initgraph(-1, -1); randomize(); showmouse(0); FlushMouseMsgBuffer(); while(kbhit()) getch(); //InitColor(); InitLog(); g_w = getwidth(NULL); g_h = getheight(NULL); g_st = (state*)malloc(g_w * g_h * sizeof(state)); COMPLEX c = {0.262, 0.002}, z = {0, 0}; double r = 1.5, d = g_w / (double)g_h, rotate = 0, sr = sin(rotate), cr = cos(rotate); init_st(g_w, g_h); int n_update = 0; double ftime = fclock(); { double dc = 64, dca = 128, db = 16; col_r = randomf() * dc + db; col_g = randomf() * dc + db; col_b = randomf() * dc + db; col_ar = randomf() * dca; col_ag = randomf() * dca; col_ab = randomf() * dca; rotate = randomf() * 360; sr = sin(rotate), cr = cos(rotate); } setrendermode(RENDER_MANUAL); for (int loop = 1; kbmouhit() == 0; ++loop) { int ret; if (loop <= 4) { ret = JDraw(c, z.re - r * d, z.im - r, z.re + r * d, z.im + r, sr, cr); if (loop == 4) { g_udlist.swap(); for(int y=0; y<g_h; y++) { for(int x=0; x<g_w; x++) { if (g_st[y * g_w + x].ed == 0) { g_udlist.push(x, y); } } } g_udlist.swap(); } } else { static int t = 0; ret = JDrawA(c, z.re - r * d, z.im - r, z.re + r * d, z.im + r); if (clock() - t > 30) { delay(1); t = clock(); } } if (g_updatepoint == 0) { n_update++; } else { n_update = 0; } if (0) { char str[500]; sprintf(str, "%d %d %f %f", g_w, g_h, r, d); outtextxy(0, 0, str); } if (ret == 0 || n_update > 8 || loop > 1000) { loop = 0; if (g_mi[0][0] == 0) { delay(1); memset(pMap, 0, BF_W * BF_H * sizeof(state)); g_udlist.clear(); for (int i = 0; i < BF_W; ++i) { addpoint(i, 0); addpoint(i, BF_H - 1); } for (int i = 0; i < 4; ) { if (MDraw(-1.9, -1.2, 0.5, 1.2) == 0) { ++i; } else { i = 0; } if (kbmouhit()) return 0; } } double dc = 64, dca = 128, db = 16; col_r = randomf() * dc + db; col_g = randomf() * dc + db; col_b = randomf() * dc + db; col_ar = randomf() * dca; col_ag = randomf() * dca; col_ab = randomf() * dca; rotate = randomf() * 360; sr = sin(rotate), cr = cos(rotate); do { c.re = randomf() * 2.4 - 1.9; c.im = randomf() * 2.4 - 1.2; int ir = (int)((c.re - (-1.9)) / (0.5 - (-1.9)) * BF_W); int im = (int)((c.im - (-1.2)) / (1.2 - (-1.2)) * BF_H); if (g_mi[im][ir] >= 16) { break; } } while (1); init_st(g_w, g_h); n_update = 0; if (fclock() - ftime < 3) { delay_ms((int)((3 - (fclock() - ftime)) * 1000)); } else { delay(1); } ftime = fclock(); } } closegraph(); return 0; }
int main(){ int i, j, k, test, mode, mode1; double zA[1+Q][1+m], zB[1+Q][1+m], zavg[1+m]; double movesize, gradsize, dlnLsize, maxsize, temp; double crit_move, crit_grad, crit_dlnL, x[1+m]; double mlnlold, dmlnLold[1+m], H[1+m][1+m], K[1+m], S[1+m][1+m]; double rc, a[1+m], aold[1+m], alpha0[1+m]; double mlnl, dmlnL[1+m], alnLmax[1+m+1+1]; FILE *convergence; getdata(zA, zB); for(j=0;j<=m;j=j+1){ zavg[j] = 0.0; } for(i=1;i<=zA[0][0];i=i+1){ for(j=1;j<=m;j=j+1){ zavg[j] = zavg[j] + zA[i][j]; } } for(j=1;j<=m;j=j+1){ zavg[j] = zavg[j]/((double)zA[0][0]); alpha0[j] = 0.0; } crit_move = 0.001; crit_grad = 0.01; crit_dlnL = 0.0001; maxsize = 0.1; /***** SCREEN FOR STARTING VALUES *****/ if(m == 1){ printf("\n GET INITIAL VALUES BY RANDOM NUMBERS"); for(i=1;i<=16;i=i+1){ a[1] = randomf(-2.0, 2.0); a[0] = -a[1]*zavg[j]; mlnl = mlnL(a, zA, zB); if( mlnl < mlnL(alpha0, zA, zB) ){ for(j=0;j<=1;j=j+1){ alpha0[j] = a[j]; printf("\n improvement %lf a: %.3f %.3f", mlnl, a[0], a[1]); } } } }else{ printf("\n GET INITIAL VALUES FROM BEST SUB-MODEL"); convergence = fopen("initial.txt", "r"); for(i=0;i<=m;i=i+1){ fscanf(convergence, "%lf", &temp); alpha0[i] = temp; } fclose(convergence); } printf("\n initial a: "); for(j=0;j<=m;j=j+1){ a[j] = alpha0[j]; printf(" %.3f ", a[j]); for(k=0;k<=m;k=k+1){ H[j][k] = 0.0; } H[j][j] = 1.0 + randomf(0.0, 0.1); } convergence = fopen("convergence.txt", "w"); test = 0; for(i=1;test==0;i=i+1){ if(i != 1){ mlnlold = mlnl; for(j=0;j<=m;j=j+1){ dmlnLold[j] = dmlnL[j]; } } mlnl = grad(a, zA, zB, dmlnL); printf("\n dmlnL = %f %f", dmlnL[0], dmlnL[1]); if(i!=1){ BFGS_update(x, dmlnL, dmlnLold, H); } diagonalize(H, S, K); dlnLsize = dmlnL - dmlnLold; gradsize = sqrt(dot(dmlnL, dmlnL)); fprintf(convergence,"\n %d %f %f", i, gradsize, mlnl); printf("\n\n gradients: %d mlnL: %f gradsize: %f", i, mlnl, gradsize); fflush(convergence); fflush(stdout); for(j=0;j<=m;j=j+1){ x[j] = 0.0; for(k=0;k<=m;k=k+1){ x[j] = x[j] - (dot(S[k],dmlnL)/K[k])*S[k][j]; } } movesize = sqrt(dot(x,x)); printf("\n RAW MOVESIZE/(B): %f", movesize); if(movesize > maxsize){ for(j=0;j<=m;j=j+1){ x[j] = x[j]*maxsize/movesize; } } printf("\n NEW MOVESIZE/(B): %f ALPHA: ", sqrt(dot(x,x))); for(j=0;j<=m;j=j+1){ aold[j] = a[j]; a[j] = a[j] + x[j]; printf(" %.3f", a[j]); } printf("\n CONVERGENCE TESTING"); printf("\n movesize:tolerance %f::%f", movesize, crit_move); printf("\n gradsize:tolerance %f::%f", gradsize, crit_grad); printf("\n deltaE:|tolerance| %f::%f", dlnLsize, crit_dlnL); if(movesize < crit_move && gradsize < crit_grad){ test = 1; } if(movesize < crit_move && fabs(dlnLsize) < crit_dlnL){ test = 1; } if(fabs(dlnLsize) < crit_dlnL && gradsize < crit_grad){ test = 1; } if(test == 1){ printf("\n CONVERGED "); for(j=0;j<=m;j=j+1){ alnLmax[j] = a[j]; } alnLmax[m+1] = -mlnl; } } fclose(convergence); convergence = fopen("answer.txt", "w"); fprintf(convergence, "%f ", alnLmax[m+1]); for(j=0;j<=m;j=j+1){ fprintf(convergence, "%f ", alnLmax[j]); } fclose(convergence); printf("\n"); return 0; }
// FX void NG_FXUpdate(void) { int32_t i, delta; int32_t t = V3X.Time.ms; SGEffect *p; for (p=g_SGGame.pExpl, i=g_SGGame.numEffects;i!=0;p++, i--) { if (!p->Dispo) { int alpha = 255; if (p->FxCode>=0) { if (p->PlaySample) { p->TagFx = NG_Audio3DPlay(p->FxCode, p->pos, NULL); p->PlaySample = 0; } else { if ((p->TagFx)&&(!NG_Audio3DUpdate(p->pos, NULL, p->TagFx, p->FxCode))) p->TagFx=0; } } delta = (t - p->LastFrame) / ( 1 + p->Sprite->speed); if (p->useKeep) p->OVI->state|=V3XSTATE_MATRIXUPDATE; if ((p->type==FX_DEBRIS)||(p->type==FX_SMOKE)) { float scale = randomf(p->type==FX_DEBRIS ? 3+4 : 2+8); V3XVector_PolarSet(p->pos, &p->cent, (V3XSCALAR)p->angle.x, (int32_t)p->angle.y, (int32_t)p->angle.z); p->angle.x+= (int)(g_cTimer.fCounter * scale); p->OVI->state|=V3XSTATE_MATRIXUPDATE; if (p->type == FX_DEBRIS) alpha = 255; else alpha = 128; } if (delta) { p->Step[1]=p->Step[0]; p->Step[0]+=delta; p->LastFrame = t; if (p->Step[0]>=p->Sprite->maxItem-1) { p->Nloop--; if (p->Nloop==0) { p->Dispo = 1; p->fce.visible = 0; } else { p->Step[0]%=p->Sprite->maxItem; p->PlaySample = 1; } } // Fade out (on last frame) if (p->Nloop == 1) { unsigned a = p->Step[0] > p->FadeStart ? alpha - ((alpha*(p->Step[0] - p->FadeStart)) / (p->Sprite->maxItem - p->FadeStart)) : alpha; RGB_Set(p->material.diffuse, a, a, a); } } if ((!p->Dispo)&&(p->type==FX_FINISH)&&(p->OVI->state&V3XSTATE_HIDDEN)) { p->Dispo = 1; p->fce.visible = 0; } if (!p->Dispo) { int j; for (j=0;j<2;j++) { if (V3XVector_TransformProject_pts(p->pos, &p->pos2D[j])) { V3XSCALAR sx = V3X.ViewPort.Focal / p->pos2D[j].z; p->size2D[j].y = p->Size * sx; p->size2D[j].x = p->size2D[j].y * V3X.ViewPort.Ratio; p->pos2D[j].z = -p->pos2D[j].z; if (j == 0) p->fce.visible = 1; } else { if (j == 0) p->fce.visible = 0; } } p->pos2D[1] = p->pos2D[0]; } } } }
//自定义函数,用来返回一个0 - m之间的浮点数 float myrand(float m) { // randomf() 返回一个 0 到 1 之间的随机浮点数 return (float)(randomf() * m); }
void BGAnimationLayer::LoadFromAniLayerFile( const RString& sPath ) { /* Generic BGAs are new. Animation directories with no INI are old and obsolete. * Don't combine them. */ RString lcPath = sPath; lcPath.MakeLower(); if( lcPath.find("usesongbg") != RString::npos ) { const Song* pSong = GAMESTATE->m_pCurSong; RString sSongBGPath; if( pSong && pSong->HasBackground() ) sSongBGPath = pSong->GetBackgroundPath(); else sSongBGPath = THEME->GetPathG("Common","fallback background"); Sprite* pSprite = new Sprite; pSprite->Load( Sprite::SongBGTexture(sSongBGPath) ); pSprite->StretchTo( FullScreenRectF ); this->AddChild( pSprite ); return; // this will ignore other effects in the file name } enum Effect { EFFECT_CENTER, EFFECT_STRETCH_STILL, EFFECT_STRETCH_SCROLL_LEFT, EFFECT_STRETCH_SCROLL_RIGHT, EFFECT_STRETCH_SCROLL_UP, EFFECT_STRETCH_SCROLL_DOWN, EFFECT_STRETCH_WATER, EFFECT_STRETCH_BUBBLE, EFFECT_STRETCH_TWIST, EFFECT_STRETCH_SPIN, EFFECT_PARTICLES_SPIRAL_OUT, EFFECT_PARTICLES_SPIRAL_IN, EFFECT_PARTICLES_FLOAT_UP, EFFECT_PARTICLES_FLOAT_DOWN, EFFECT_PARTICLES_FLOAT_LEFT, EFFECT_PARTICLES_FLOAT_RIGHT, EFFECT_PARTICLES_BOUNCE, EFFECT_TILE_STILL, EFFECT_TILE_SCROLL_LEFT, EFFECT_TILE_SCROLL_RIGHT, EFFECT_TILE_SCROLL_UP, EFFECT_TILE_SCROLL_DOWN, EFFECT_TILE_FLIP_X, EFFECT_TILE_FLIP_Y, EFFECT_TILE_PULSE, NUM_EFFECTS, // leave this at the end EFFECT_INVALID }; const RString EFFECT_STRING[NUM_EFFECTS] = { "center", "stretchstill", "stretchscrollleft", "stretchscrollright", "stretchscrollup", "stretchscrolldown", "stretchwater", "stretchbubble", "stretchtwist", "stretchspin", "particlesspiralout", "particlesspiralin", "particlesfloatup", "particlesfloatdown", "particlesfloatleft", "particlesfloatright", "particlesbounce", "tilestill", "tilescrollleft", "tilescrollright", "tilescrollup", "tilescrolldown", "tileflipx", "tileflipy", "tilepulse", }; Effect effect = EFFECT_CENTER; for( int i=0; i<NUM_EFFECTS; i++ ) if( lcPath.find(EFFECT_STRING[i]) != string::npos ) effect = (Effect)i; switch( effect ) { case EFFECT_CENTER: { m_Type = TYPE_SPRITE; Sprite* pSprite = new Sprite; this->AddChild( pSprite ); pSprite->Load( sPath ); pSprite->SetXY( SCREEN_CENTER_X, SCREEN_CENTER_Y ); } break; case EFFECT_STRETCH_STILL: case EFFECT_STRETCH_SCROLL_LEFT: case EFFECT_STRETCH_SCROLL_RIGHT: case EFFECT_STRETCH_SCROLL_UP: case EFFECT_STRETCH_SCROLL_DOWN: case EFFECT_STRETCH_WATER: case EFFECT_STRETCH_BUBBLE: case EFFECT_STRETCH_TWIST: { m_Type = TYPE_SPRITE; Sprite* pSprite = new Sprite; this->AddChild( pSprite ); RageTextureID ID(sPath); ID.bStretch = true; pSprite->Load( Sprite::SongBGTexture(ID) ); pSprite->StretchTo( FullScreenRectF ); pSprite->SetCustomTextureRect( RectF(0,0,1,1) ); switch( effect ) { case EFFECT_STRETCH_SCROLL_LEFT: m_fTexCoordVelocityX = +0.5f; m_fTexCoordVelocityY = 0; break; case EFFECT_STRETCH_SCROLL_RIGHT: m_fTexCoordVelocityX = -0.5f; m_fTexCoordVelocityY = 0; break; case EFFECT_STRETCH_SCROLL_UP: m_fTexCoordVelocityX = 0; m_fTexCoordVelocityY = +0.5f; break; case EFFECT_STRETCH_SCROLL_DOWN: m_fTexCoordVelocityX = 0; m_fTexCoordVelocityY = -0.5f; break; default: break; } } break; case EFFECT_STRETCH_SPIN: { m_Type = TYPE_SPRITE; Sprite* pSprite = new Sprite; this->AddChild( pSprite ); pSprite->Load( Sprite::SongBGTexture(sPath) ); const RectF StretchedFullScreenRectF( FullScreenRectF.left-200, FullScreenRectF.top-200, FullScreenRectF.right+200, FullScreenRectF.bottom+200 ); pSprite->ScaleToCover( StretchedFullScreenRectF ); pSprite->SetEffectSpin( RageVector3(0,0,60) ); } break; case EFFECT_PARTICLES_SPIRAL_OUT: case EFFECT_PARTICLES_SPIRAL_IN: case EFFECT_PARTICLES_FLOAT_UP: case EFFECT_PARTICLES_FLOAT_DOWN: case EFFECT_PARTICLES_FLOAT_LEFT: case EFFECT_PARTICLES_FLOAT_RIGHT: case EFFECT_PARTICLES_BOUNCE: { m_Type = TYPE_PARTICLES; Sprite s; s.Load( sPath ); int iSpriteArea = int( s.GetUnzoomedWidth()*s.GetUnzoomedHeight() ); const int iMaxArea = int(SCREEN_WIDTH*SCREEN_HEIGHT); int iNumParticles = iMaxArea / iSpriteArea; iNumParticles = min( iNumParticles, MAX_SPRITES ); for( int i=0; i<iNumParticles; i++ ) { Sprite* pSprite = new Sprite; this->AddChild( pSprite ); pSprite->Load( sPath ); pSprite->SetZoom( 0.7f + 0.6f*i/(float)iNumParticles ); switch( effect ) { case EFFECT_PARTICLES_BOUNCE: pSprite->SetX( randomf( GetGuardRailLeft(pSprite), GetGuardRailRight(pSprite) ) ); pSprite->SetY( randomf( GetGuardRailTop(pSprite), GetGuardRailBottom(pSprite) ) ); break; default: pSprite->SetX( randomf( GetOffScreenLeft(pSprite), GetOffScreenRight(pSprite) ) ); pSprite->SetY( randomf( GetOffScreenTop(pSprite), GetOffScreenBottom(pSprite) ) ); break; } switch( effect ) { case EFFECT_PARTICLES_FLOAT_UP: case EFFECT_PARTICLES_SPIRAL_OUT: m_vParticleVelocity.push_back( RageVector3( 0, -PARTICLE_SPEED*pSprite->GetZoom(), 0 ) ); break; case EFFECT_PARTICLES_FLOAT_DOWN: case EFFECT_PARTICLES_SPIRAL_IN: m_vParticleVelocity.push_back( RageVector3( 0, PARTICLE_SPEED*pSprite->GetZoom(), 0 ) ); break; case EFFECT_PARTICLES_FLOAT_LEFT: m_vParticleVelocity.push_back( RageVector3( -PARTICLE_SPEED*pSprite->GetZoom(), 0, 0 ) ); break; case EFFECT_PARTICLES_FLOAT_RIGHT: m_vParticleVelocity.push_back( RageVector3( +PARTICLE_SPEED*pSprite->GetZoom(), 0, 0 ) ); break; case EFFECT_PARTICLES_BOUNCE: m_bParticlesBounce = true; pSprite->SetZoom( 1 ); m_vParticleVelocity.push_back( RageVector3( randomf(), randomf(), 0 ) ); RageVec3Normalize( &m_vParticleVelocity[i], &m_vParticleVelocity[i] ); m_vParticleVelocity[i].x *= PARTICLE_SPEED; m_vParticleVelocity[i].y *= PARTICLE_SPEED; break; default: FAIL_M(ssprintf("Unrecognized layer effect: %i", effect)); } } } break; case EFFECT_TILE_STILL: case EFFECT_TILE_SCROLL_LEFT: case EFFECT_TILE_SCROLL_RIGHT: case EFFECT_TILE_SCROLL_UP: case EFFECT_TILE_SCROLL_DOWN: case EFFECT_TILE_FLIP_X: case EFFECT_TILE_FLIP_Y: case EFFECT_TILE_PULSE: { m_Type = TYPE_TILES; RageTextureID ID(sPath); ID.bStretch = true; Sprite s; s.Load( ID ); m_iNumTilesWide = 2+int(SCREEN_WIDTH /s.GetUnzoomedWidth()); m_iNumTilesWide = min( m_iNumTilesWide, MAX_TILES_WIDE ); m_iNumTilesHigh = 2+int(SCREEN_HEIGHT/s.GetUnzoomedHeight()); m_iNumTilesHigh = min( m_iNumTilesHigh, MAX_TILES_HIGH ); m_fTilesStartX = s.GetUnzoomedWidth() / 2; m_fTilesStartY = s.GetUnzoomedHeight() / 2; m_fTilesSpacingX = s.GetUnzoomedWidth(); m_fTilesSpacingY = s.GetUnzoomedHeight(); for( int x=0; x<m_iNumTilesWide; x++ ) { for( int y=0; y<m_iNumTilesHigh; y++ ) { Sprite* pSprite = new Sprite; this->AddChild( pSprite ); pSprite->Load( ID ); pSprite->SetTextureWrapping( true ); // gets rid of some "cracks" switch( effect ) { case EFFECT_TILE_STILL: break; case EFFECT_TILE_SCROLL_LEFT: m_fTileVelocityX = -PARTICLE_SPEED; break; case EFFECT_TILE_SCROLL_RIGHT: m_fTileVelocityX = +PARTICLE_SPEED; break; case EFFECT_TILE_SCROLL_UP: m_fTileVelocityY = -PARTICLE_SPEED; break; case EFFECT_TILE_SCROLL_DOWN: m_fTileVelocityY = +PARTICLE_SPEED; break; case EFFECT_TILE_FLIP_X: pSprite->SetEffectSpin( RageVector3(180,0,0) ); break; case EFFECT_TILE_FLIP_Y: pSprite->SetEffectSpin( RageVector3(0,180,0) ); break; case EFFECT_TILE_PULSE: pSprite->SetEffectPulse( 1, 0.3f, 1.f ); break; default: FAIL_M(ssprintf("Not a tile effect: %i", effect)); } } } } break; default: FAIL_M(ssprintf("Unrecognized layer effect: %i", effect)); } RString sHint = sPath; sHint.MakeLower(); if( sHint.find("cyclecolor") != RString::npos ) for( unsigned i=0; i<m_SubActors.size(); i++ ) m_SubActors[i]->SetEffectRainbow( 5 ); if( sHint.find("cyclealpha") != RString::npos ) for( unsigned i=0; i<m_SubActors.size(); i++ ) m_SubActors[i]->SetEffectDiffuseShift( 2, RageColor(1,1,1,1), RageColor(1,1,1,0) ); if( sHint.find("startonrandomframe") != RString::npos ) for( unsigned i=0; i<m_SubActors.size(); i++ ) m_SubActors[i]->SetState( RandomInt(m_SubActors[i]->GetNumStates()) ); if( sHint.find("dontanimate") != RString::npos ) for( unsigned i=0; i<m_SubActors.size(); i++ ) m_SubActors[i]->StopAnimating(); if( sHint.find("add") != RString::npos ) for( unsigned i=0; i<m_SubActors.size(); i++ ) m_SubActors[i]->SetBlendMode( BLEND_ADD ); }
static inline bool rnd_choice(float possib) { return randomf() < possib; }
double rand_float(double dv, double db) //返回一个db 到 db+dv之间的随机浮点数 { return randomf()*dv + db; }
static inline float deviation_apply(float val, float dev) { return (2 * dev * randomf() - dev + 1) * val; }
void BGAnimationLayer::LoadFromNode( const XNode* pNode ) { { bool bCond; if( pNode->GetAttrValue("Condition", bCond) && !bCond ) return; } bool bStretch = false; { RString type = "sprite"; pNode->GetAttrValue( "Type", type ); type.MakeLower(); /* The preferred way of stretching a sprite to fit the screen is "Type=sprite" * and "stretch=1". "type=1" is for backwards-compatibility. */ pNode->GetAttrValue( "Stretch", bStretch ); // Check for string match first, then do integer match. // "if(StringType(type)==0)" was matching against all string matches. // -Chris if( type.EqualsNoCase("sprite") ) { m_Type = TYPE_SPRITE; } else if( type.EqualsNoCase("particles") ) { m_Type = TYPE_PARTICLES; } else if( type.EqualsNoCase("tiles") ) { m_Type = TYPE_TILES; } else if( StringToInt(type) == 1 ) { m_Type = TYPE_SPRITE; bStretch = true; } else if( StringToInt(type) == 2 ) { m_Type = TYPE_PARTICLES; } else if( StringToInt(type) == 3 ) { m_Type = TYPE_TILES; } else { m_Type = TYPE_SPRITE; } } pNode->GetAttrValue( "FOV", m_fFOV ); pNode->GetAttrValue( "Lighting", m_bLighting ); pNode->GetAttrValue( "TexCoordVelocityX", m_fTexCoordVelocityX ); pNode->GetAttrValue( "TexCoordVelocityY", m_fTexCoordVelocityY ); // compat: pNode->GetAttrValue( "StretchTexCoordVelocityX", m_fTexCoordVelocityX ); pNode->GetAttrValue( "StretchTexCoordVelocityY", m_fTexCoordVelocityY ); // particle and tile stuff float fZoomMin = 1; float fZoomMax = 1; pNode->GetAttrValue( "ZoomMin", fZoomMin ); pNode->GetAttrValue( "ZoomMax", fZoomMax ); float fVelocityXMin = 10, fVelocityXMax = 10; float fVelocityYMin = 0, fVelocityYMax = 0; float fVelocityZMin = 0, fVelocityZMax = 0; float fOverrideSpeed = 0; // 0 means don't override speed pNode->GetAttrValue( "VelocityXMin", fVelocityXMin ); pNode->GetAttrValue( "VelocityXMax", fVelocityXMax ); pNode->GetAttrValue( "VelocityYMin", fVelocityYMin ); pNode->GetAttrValue( "VelocityYMax", fVelocityYMax ); pNode->GetAttrValue( "VelocityZMin", fVelocityZMin ); pNode->GetAttrValue( "VelocityZMax", fVelocityZMax ); pNode->GetAttrValue( "OverrideSpeed", fOverrideSpeed ); int iNumParticles = 10; pNode->GetAttrValue( "NumParticles", iNumParticles ); pNode->GetAttrValue( "ParticlesBounce", m_bParticlesBounce ); pNode->GetAttrValue( "TilesStartX", m_fTilesStartX ); pNode->GetAttrValue( "TilesStartY", m_fTilesStartY ); pNode->GetAttrValue( "TilesSpacingX", m_fTilesSpacingX ); pNode->GetAttrValue( "TilesSpacingY", m_fTilesSpacingY ); pNode->GetAttrValue( "TileVelocityX", m_fTileVelocityX ); pNode->GetAttrValue( "TileVelocityY", m_fTileVelocityY ); switch( m_Type ) { case TYPE_SPRITE: { Actor* pActor = ActorUtil::LoadFromNode( pNode, this ); this->AddChild( pActor ); if( bStretch ) pActor->StretchTo( FullScreenRectF ); } break; case TYPE_PARTICLES: { RString sFile; ActorUtil::GetAttrPath( pNode, "File", sFile ); FixSlashesInPlace( sFile ); CollapsePath( sFile ); for( int i=0; i<iNumParticles; i++ ) { Actor* pActor = ActorUtil::MakeActor( sFile, this ); if( pActor == NULL ) continue; this->AddChild( pActor ); pActor->SetXY( randomf(float(FullScreenRectF.left),float(FullScreenRectF.right)), randomf(float(FullScreenRectF.top),float(FullScreenRectF.bottom)) ); pActor->SetZoom( randomf(fZoomMin,fZoomMax) ); m_vParticleVelocity.push_back( RageVector3( randomf(fVelocityXMin,fVelocityXMax), randomf(fVelocityYMin,fVelocityYMax), randomf(fVelocityZMin,fVelocityZMax) ) ); if( fOverrideSpeed != 0 ) { RageVec3Normalize( &m_vParticleVelocity[i], &m_vParticleVelocity[i] ); m_vParticleVelocity[i] *= fOverrideSpeed; } } } break; case TYPE_TILES: { RString sFile; ActorUtil::GetAttrPath( pNode, "File", sFile ); FixSlashesInPlace( sFile ); CollapsePath( sFile ); AutoActor s; s.Load( sFile ); if( m_fTilesSpacingX == -1 ) m_fTilesSpacingX = s->GetUnzoomedWidth(); if( m_fTilesSpacingY == -1 ) m_fTilesSpacingY = s->GetUnzoomedHeight(); m_iNumTilesWide = 2+(int)(SCREEN_WIDTH /m_fTilesSpacingX); m_iNumTilesHigh = 2+(int)(SCREEN_HEIGHT/m_fTilesSpacingY); unsigned NumSprites = m_iNumTilesWide * m_iNumTilesHigh; for( unsigned i=0; i<NumSprites; i++ ) { Actor* pSprite = ActorUtil::MakeActor( sFile, this ); if( pSprite == NULL ) continue; this->AddChild( pSprite ); pSprite->SetTextureWrapping( true ); // gets rid of some "cracks" pSprite->SetZoom( randomf(fZoomMin,fZoomMax) ); } } break; default: FAIL_M(ssprintf("Unrecognized layer type: %i", m_Type)); } bool bStartOnRandomFrame = false; pNode->GetAttrValue( "StartOnRandomFrame", bStartOnRandomFrame ); if( bStartOnRandomFrame ) { for( unsigned i=0; i<m_SubActors.size(); i++ ) m_SubActors[i]->SetState( RandomInt(m_SubActors[i]->GetNumStates()) ); } }
void ScreenJukebox::SetSong() { ThemeMetric<bool> ALLOW_ADVANCED_MODIFIERS(m_sName,"AllowAdvancedModifiers"); vector<Song*> vSongs; //Check to see if there is a theme-course //I.E. If there is a course called exactly the theme name, //then we pick a song from this course. Course *pCourse = SONGMAN->GetCourseFromName( THEME->GetCurThemeName() ); if( pCourse != NULL ) for ( unsigned i = 0; i < pCourse->m_entries.size(); i++ ) vSongs.push_back( pCourse->m_entries[i].pSong ); if ( vSongs.size() == 0 ) SONGMAN->GetSongs( vSongs, GAMESTATE->m_sPreferredSongGroup ); // // Calculate what difficulties to show // vector<Difficulty> vDifficultiesToShow; if( m_bDemonstration ) { // HACK: This belongs in ScreenDemonstration ThemeMetricDifficultiesToShow DIFFICULTIES_TO_SHOW_HERE(m_sName,"DifficultiesToShow"); vDifficultiesToShow = DIFFICULTIES_TO_SHOW_HERE.GetValue(); } else { if( GAMESTATE->m_PreferredDifficulty[PLAYER_1] != DIFFICULTY_INVALID ) { vDifficultiesToShow.push_back( GAMESTATE->m_PreferredDifficulty[PLAYER_1] ); } else { FOREACH_Difficulty( dc ) vDifficultiesToShow.push_back( dc ); } } ASSERT( !vDifficultiesToShow.empty() ) // // Search for a Song and Steps to play during the demo // for( int i=0; i<1000; i++ ) { if( vSongs.size() == 0 ) return; Song* pSong = vSongs[rand()%vSongs.size()]; if( !pSong->HasMusic() ) continue; // skip if( UNLOCKMAN->SongIsLocked(pSong) ) continue; if( !pSong->ShowInDemonstrationAndRanking() ) continue; // skip Difficulty dc = vDifficultiesToShow[ rand()%vDifficultiesToShow.size() ]; Steps* pSteps = pSong->GetStepsByDifficulty( GAMESTATE->GetCurrentStyle()->m_StepsType, dc ); if( pSteps == NULL ) continue; // skip if( !PREFSMAN->m_bAutogenSteps && pSteps->IsAutogen()) continue; // skip // Found something we can use! GAMESTATE->m_pCurSong.Set( pSong ); // We just changed the song. Reset the original sync data. GAMESTATE->ResetOriginalSyncData(); FOREACH_PlayerNumber( p ) GAMESTATE->m_pCurSteps[p].Set( pSteps ); bool bShowModifiers = randomf(0,1) <= SHOW_COURSE_MODIFIERS_PROBABILITY; if( bShowModifiers ) { /* If we have a modifier course containing this song, apply its modifiers. Only check * fixed course entries. */ vector<Course*> apCourses; SONGMAN->GetAllCourses( apCourses, false ); vector<const CourseEntry *> apOptions; vector<Course*> apPossibleCourses; for( unsigned i = 0; i < apCourses.size(); ++i ) { Course *pCourse = apCourses[i]; const CourseEntry *pEntry = pCourse->FindFixedSong( pSong ); if( pEntry == NULL || pEntry->attacks.size() == 0 ) continue; if( !ALLOW_ADVANCED_MODIFIERS ) { // There are some confusing mods that we don't want to show in demonstration. bool bModsAreOkToShow = true; AttackArray aAttacks = pEntry->attacks; if( !pEntry->modifiers.empty() ) aAttacks.push_back( Attack::FromGlobalCourseModifier( pEntry->modifiers ) ); FOREACH_CONST( Attack, aAttacks, a ) { CString s = a->sModifiers; s.MakeLower(); if( s.find("dark") != CString::npos || s.find("stealth") != CString::npos ) { bModsAreOkToShow = false; break; } } if( !bModsAreOkToShow ) continue; // skip } apOptions.push_back( pEntry ); apPossibleCourses.push_back( pCourse ); } if( !apOptions.empty() ) { int iIndex = rand()%apOptions.size(); m_pCourseEntry = apOptions[iIndex]; Course *pCourse = apPossibleCourses[iIndex]; GAMESTATE->m_PlayMode = CourseTypeToPlayMode( pCourse->GetCourseType() ); GAMESTATE->m_pCurCourse.Set( pCourse ); FOREACH_PlayerNumber( p ) { GAMESTATE->m_pCurTrail[p].Set( pCourse->GetTrail( GAMESTATE->GetCurrentStyle()->m_StepsType ) ); ASSERT( GAMESTATE->m_pCurTrail[p] ); } }
void ScreenEvaluation::Init() { LOG->Trace( "ScreenEvaluation::Init()" ); // debugging // Only fill StageStats with fake info if we're the InitialScreen // (i.e. StageStats not already filled) if( PREFSMAN->m_sTestInitialScreen.Get() == m_sName ) { PROFILEMAN->LoadFirstAvailableProfile(PLAYER_1); PROFILEMAN->LoadFirstAvailableProfile(PLAYER_2); STATSMAN->m_vPlayedStageStats.clear(); STATSMAN->m_vPlayedStageStats.push_back( StageStats() ); StageStats &ss = STATSMAN->m_vPlayedStageStats.back(); GAMESTATE->m_PlayMode.Set( PLAY_MODE_REGULAR ); GAMESTATE->SetCurrentStyle( GAMEMAN->GameAndStringToStyle(GAMEMAN->GetDefaultGame(),"versus"), PLAYER_INVALID ); ss.m_playMode = GAMESTATE->m_PlayMode; ss.m_Stage = Stage_1st; enum_add( ss.m_Stage, rand()%3 ); ss.m_EarnedExtraStage = (EarnedExtraStage)(rand() % NUM_EarnedExtraStage); GAMESTATE->SetMasterPlayerNumber(PLAYER_1); GAMESTATE->m_pCurSong.Set( SONGMAN->GetRandomSong() ); ss.m_vpPlayedSongs.push_back( GAMESTATE->m_pCurSong ); ss.m_vpPossibleSongs.push_back( GAMESTATE->m_pCurSong ); GAMESTATE->m_pCurCourse.Set( SONGMAN->GetRandomCourse() ); GAMESTATE->m_iCurrentStageIndex = 0; FOREACH_ENUM( PlayerNumber, p ) GAMESTATE->m_iPlayerStageTokens[p] = 1; FOREACH_PlayerNumber( p ) { ss.m_player[p].m_pStyle = GAMESTATE->GetCurrentStyle(p); if( RandomInt(2) ) PO_GROUP_ASSIGN_N( GAMESTATE->m_pPlayerState[p]->m_PlayerOptions, ModsLevel_Stage, m_bTransforms, PlayerOptions::TRANSFORM_ECHO, true ); // show "disqualified" SO_GROUP_ASSIGN( GAMESTATE->m_SongOptions, ModsLevel_Stage, m_fMusicRate, 1.1f ); GAMESTATE->JoinPlayer( p ); GAMESTATE->m_pCurSteps[p].Set( GAMESTATE->m_pCurSong->GetAllSteps()[0] ); if( GAMESTATE->m_pCurCourse ) { vector<Trail*> apTrails; GAMESTATE->m_pCurCourse->GetAllTrails( apTrails ); if( apTrails.size() ) GAMESTATE->m_pCurTrail[p].Set( apTrails[0] ); } ss.m_player[p].m_vpPossibleSteps.push_back( GAMESTATE->m_pCurSteps[PLAYER_1] ); ss.m_player[p].m_iStepsPlayed = 1; PO_GROUP_ASSIGN( GAMESTATE->m_pPlayerState[p]->m_PlayerOptions, ModsLevel_Stage, m_fScrollSpeed, 2.0f ); PO_GROUP_CALL( GAMESTATE->m_pPlayerState[p]->m_PlayerOptions, ModsLevel_Stage, ChooseRandomModifiers ); } for( float f = 0; f < 100.0f; f += 1.0f ) { float fP1 = fmodf(f/100*4+.3f,1); ss.m_player[PLAYER_1].SetLifeRecordAt( fP1, f ); ss.m_player[PLAYER_2].SetLifeRecordAt( 1-fP1, f ); } FOREACH_PlayerNumber( p ) { float fSeconds = GAMESTATE->m_pCurSong->GetStepsSeconds(); ss.m_player[p].m_iActualDancePoints = RandomInt( 3 ); ss.m_player[p].m_iPossibleDancePoints = 2; if( RandomInt(2) ) ss.m_player[p].m_iCurCombo = RandomInt(15000); else ss.m_player[p].m_iCurCombo = 0; ss.m_player[p].UpdateComboList( 0, true ); ss.m_player[p].m_iCurCombo += 50; ss.m_player[p].UpdateComboList( 0.10f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 0; ss.m_player[p].UpdateComboList( 0.15f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 1; ss.m_player[p].UpdateComboList( 0.25f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 50; ss.m_player[p].UpdateComboList( 0.35f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 0; ss.m_player[p].UpdateComboList( 0.45f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 1; ss.m_player[p].UpdateComboList( 0.50f * fSeconds, false ); ss.m_player[p].m_iCurCombo = 100; ss.m_player[p].UpdateComboList( 1.00f * fSeconds, false ); if( RandomInt(5) == 0 ) { ss.m_player[p].m_bFailed = true; } ss.m_player[p].m_iTapNoteScores[TNS_W1] = RandomInt( 3 ); ss.m_player[p].m_iTapNoteScores[TNS_W2] = RandomInt( 3 ); ss.m_player[p].m_iTapNoteScores[TNS_W3] = RandomInt( 3 ); ss.m_player[p].m_iPossibleGradePoints = 4*ScoreKeeperNormal::TapNoteScoreToGradePoints(TNS_W1, false); ss.m_player[p].m_fLifeRemainingSeconds = randomf( 90, 580 ); ss.m_player[p].m_iScore = rand() % (900*1000*1000); ss.m_player[p].m_iPersonalHighScoreIndex = (rand() % 3) - 1; ss.m_player[p].m_iMachineHighScoreIndex = (rand() % 3) - 1; ss.m_player[p].m_PeakComboAward = (PeakComboAward)(rand()%NUM_PeakComboAward); ss.m_player[p].m_StageAward = (StageAward)(rand()%NUM_StageAward); FOREACH_ENUM( RadarCategory, rc ) { switch( rc ) { case RadarCategory_Stream: case RadarCategory_Voltage: case RadarCategory_Air: case RadarCategory_Freeze: case RadarCategory_Chaos: ss.m_player[p].m_radarPossible[rc] = randomf( 0, 1 ); ss.m_player[p].m_radarActual[rc] = randomf( 0, ss.m_player[p].m_radarPossible[rc] ); break; case RadarCategory_TapsAndHolds: case RadarCategory_Jumps: case RadarCategory_Holds: case RadarCategory_Mines: case RadarCategory_Hands: case RadarCategory_Rolls: case RadarCategory_Lifts: case RadarCategory_Fakes: ss.m_player[p].m_radarPossible[rc] = 1 + (rand() % 200); ss.m_player[p].m_radarActual[rc] = rand() % (int)(ss.m_player[p].m_radarPossible[rc]); break; default: break; } ; // filled in by ScreenGameplay on start of notes } } }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line paramters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available"); arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindigs."); int numLimbs = 3; while (arguments.read("--limbs", numLimbs)) {} // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); #if 0 unsigned int pos = viewer.addCameraManipulator(new GliderManipulator()); viewer.selectCameraManipulator(pos); #endif // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. bool helpAll = arguments.read("--help-all"); unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) | ((helpAll || arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) | ((helpAll || arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 ); if (helpType) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } osg::Timer_t start_tick = osg::Timer::instance()->tick(); // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } osg::Timer_t end_tick = osg::Timer::instance()->tick(); std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl; // optimize the scene graph, remove rendundent nodes and state etc. osgUtil::Optimizer optimizer; /// set background color to black viewer.setClearColor(osg::Vec4(0.95,0.95,0.95,1.0) ); scene = new osg::Group; osg::StateSet* rootStateSet = new osg::StateSet; scene->setStateSet(rootStateSet); srand((unsigned)time(0)); // pass the loaded scene graph to the viewer. viewer.setSceneData(scene); bone* rootBone = makeRandomBone(numLimbs,osg::Vec3(0.0,10.0,0.0),15.0f); std::cout << "allBones.size() " << allBones.size() << std::endl; /// duplicate the bones thing all over for (unsigned i = 0; i < 25; i++) { osg::PositionAttitudeTransform* randPlace = new osg::PositionAttitudeTransform; /// just having random positions looks pretty cool randPlace->setPosition(osg::Vec3(randomf(),randomf(),randomf() )*200.0f ); osg::Quat quat = osg::Quat( randomf(0,M_PI), osg::Vec3(1,0,0), randomf(0,M_PI), osg::Vec3(0,1,0), randomf(0,M_PI), osg::Vec3(0,0,1) ); randPlace->setAttitude(quat); randPlace->addChild(rootBone->root); scene->addChild(randPlace); } #ifdef VECS2 for (unsigned i = 0; i < allBones.size(); i++) { scene->addChild(allBones[i]->objposScene); } #endif if (1) { osg::StateSet* ss = scene->getOrCreateStateSet(); osg::Program* BlockyProgram = new osg::Program; BlockyProgram->setName( "blocky" ); osg::Shader* BlockyVertObj = new osg::Shader( osg::Shader::VERTEX ); osg::Shader* BlockyFragObj = new osg::Shader( osg::Shader::FRAGMENT ); BlockyProgram->addShader( BlockyFragObj ); BlockyProgram->addShader( BlockyVertObj ); ss->setAttributeAndModes(BlockyProgram, osg::StateAttribute::ON); BlockyVertObj->loadShaderSourceFromFile("shaders/blocky.vert"); BlockyFragObj->loadShaderSourceFromFile("shaders/blocky.frag"); //for unsigned i = 0 //viewer.getSceneHandlerList()[0]->getSceneView()->setActiveUniforms(osgUtil::SceneView::VIEW_MATRIX_INVERSE_UNIFORM); } // create the windows and run the threads. viewer.realize(); int i = 0; float preIncr = 0.0; while( !viewer.done()) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); usleep(500); preIncr += 0.005; updateBones(preIncr); if (1) { std::stringstream imageName; imageName << "images/image_" << i << ".jpg"; screenCapture(&viewer, imageName.str()); i++; } } // wait for all cull and draw threads to complete before exit. viewer.sync(); // run a clean up frame to delete all OpenGL objects. viewer.cleanup_frame(); // wait for all the clean up frame to complete. viewer.sync(); return 0; }