1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
|
/*
* $Id: KX_KetsjiEngine.cpp 14444 2008-04-16 22:40:48Z hos $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
* The engine ties all game modules together.
*/
#ifdef WIN32
#pragma warning (disable : 4786)
#endif //WIN32
#include <iostream>
#include "KX_KetsjiEngine.h"
#include "ListValue.h"
#include "IntValue.h"
#include "VectorValue.h"
#include "BoolValue.h"
#include "FloatValue.h"
#define KX_NUM_ITERATIONS 4
#include "RAS_BucketManager.h"
#include "RAS_Rect.h"
#include "RAS_IRasterizer.h"
#include "RAS_IRenderTools.h"
#include "RAS_ICanvas.h"
#include "STR_String.h"
#include "MT_Vector3.h"
#include "MT_Transform.h"
#include "SCA_IInputDevice.h"
#include "KX_Scene.h"
#include "MT_CmMatrix4x4.h"
#include "KX_Camera.h"
#include "KX_PythonInit.h"
#include "KX_PyConstraintBinding.h"
#include "PHY_IPhysicsEnvironment.h"
#include "SumoPhysicsEnvironment.h"
#include "SND_Scene.h"
#include "SND_IAudioDevice.h"
#include "NG_NetworkScene.h"
#include "NG_NetworkDeviceInterface.h"
#include "KX_WorldInfo.h"
#include "KX_ISceneConverter.h"
#include "KX_TimeCategoryLogger.h"
#include "RAS_FramingManager.h"
// If define: little test for Nzc: guarded drawing. If the canvas is
// not valid, skip rendering this frame.
//#define NZC_GUARDED_OUTPUT
#define DEFAULT_LOGIC_TIC_RATE 60.0
#define DEFAULT_PHYSICS_TIC_RATE 60.0
const char KX_KetsjiEngine::m_profileLabels[tc_numCategories][15] = {
"Physics:", // tc_physics
"Logic", // tc_logic
"Network:", // tc_network
"Scenegraph:", // tc_scenegraph
"Sound:", // tc_sound
"Rasterizer:", // tc_rasterizer
"Services:", // tc_services
"Overhead:", // tc_overhead
"Outside:" // tc_outside
};
double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE;
double KX_KetsjiEngine::m_suspendedtime = 0.0;
double KX_KetsjiEngine::m_suspendeddelta = 0.0;
/**
* Constructor of the Ketsji Engine
*/
KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system)
: m_canvas(NULL),
m_rasterizer(NULL),
m_kxsystem(system),
m_rendertools(NULL),
m_sceneconverter(NULL),
m_networkdevice(NULL),
m_audiodevice(NULL),
m_pythondictionary(NULL),
m_keyboarddevice(NULL),
m_mousedevice(NULL),
m_propertiesPresent(false),
m_bInitialized(false),
m_activecam(0),
m_bFixedTime(false),
m_game2ipo(false),
m_firstframe(true),
m_frameTime(0.f),
m_clockTime(0.f),
m_previousClockTime(0.f),
m_exitcode(KX_EXIT_REQUEST_NO_REQUEST),
m_exitstring(""),
m_drawingmode(5),
m_cameraZoom(1.0),
m_overrideCam(false),
m_overrideCamUseOrtho(false),
m_stereo(false),
m_curreye(0),
m_logger(NULL),
// Set up timing info display variables
m_show_framerate(false),
m_show_profile(false),
m_showProperties(false),
m_showBackground(false),
m_show_debug_properties(false),
// Default behavior is to hide the cursor every frame.
m_hideCursor(false),
m_overrideFrameColor(false),
m_overrideFrameColorR(0.0),
m_overrideFrameColorG(0.0),
m_overrideFrameColorB(0.0)
{
// Initialize the time logger
m_logger = new KX_TimeCategoryLogger (25);
for (int i = tc_first; i < tc_numCategories; i++)
m_logger->AddCategory((KX_TimeCategory)i);
}
/**
* Destructor of the Ketsji Engine, release all memory
*/
KX_KetsjiEngine::~KX_KetsjiEngine()
{
delete m_logger;
}
void KX_KetsjiEngine::SetKeyboardDevice(SCA_IInputDevice* keyboarddevice)
{
MT_assert(keyboarddevice);
m_keyboarddevice = keyboarddevice;
}
void KX_KetsjiEngine::SetMouseDevice(SCA_IInputDevice* mousedevice)
{
MT_assert(mousedevice);
m_mousedevice = mousedevice;
}
void KX_KetsjiEngine::SetNetworkDevice(NG_NetworkDeviceInterface* networkdevice)
{
MT_assert(networkdevice);
m_networkdevice = networkdevice;
}
void KX_KetsjiEngine::SetAudioDevice(SND_IAudioDevice* audiodevice)
{
MT_assert(audiodevice);
m_audiodevice = audiodevice;
}
void KX_KetsjiEngine::SetCanvas(RAS_ICanvas* canvas)
{
MT_assert(canvas);
m_canvas = canvas;
}
void KX_KetsjiEngine::SetRenderTools(RAS_IRenderTools* rendertools)
{
MT_assert(rendertools);
m_rendertools = rendertools;
}
void KX_KetsjiEngine::SetRasterizer(RAS_IRasterizer* rasterizer)
{
MT_assert(rasterizer);
m_rasterizer = rasterizer;
}
void KX_KetsjiEngine::SetPythonDictionary(PyObject* pythondictionary)
{
MT_assert(pythondictionary);
m_pythondictionary = pythondictionary;
}
void KX_KetsjiEngine::SetSceneConverter(KX_ISceneConverter* sceneconverter)
{
MT_assert(sceneconverter);
m_sceneconverter = sceneconverter;
}
/**
* Ketsji Init(), Initializes datastructures and converts data from
* Blender into Ketsji native (realtime) format also sets up the
* graphics context
*/
void KX_KetsjiEngine::StartEngine(bool clearIpo)
{
m_clockTime = m_kxsystem->GetTimeInSeconds();
m_frameTime = m_kxsystem->GetTimeInSeconds();
m_previousClockTime = m_kxsystem->GetTimeInSeconds();
m_firstframe = true;
m_bInitialized = true;
m_ticrate = DEFAULT_LOGIC_TIC_RATE;
if (m_game2ipo)
{
m_sceneconverter->ResetPhysicsObjectsAnimationIpo(clearIpo);
m_sceneconverter->WritePhysicsObjectToAnimationIpo(m_currentFrame);
}
}
bool KX_KetsjiEngine::BeginFrame()
{
bool result = false;
RAS_Rect vp;
KX_Scene* firstscene = *m_scenes.begin();
const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
// set the area used for rendering
m_rasterizer->SetRenderArea();
RAS_FramingManager::ComputeViewport(framesettings, m_canvas->GetDisplayArea(), vp);
if (m_canvas->BeginDraw())
{
result = true;
m_canvas->SetViewPort(vp.GetLeft(), vp.GetBottom(), vp.GetRight(), vp.GetTop());
SetBackGround( firstscene->GetWorldInfo() );
m_rasterizer->BeginFrame( m_drawingmode , m_kxsystem->GetTimeInSeconds());
m_rendertools->BeginFrame( m_rasterizer);
}
return result;
}
void KX_KetsjiEngine::EndFrame()
{
// Show profiling info
m_logger->StartLog(tc_overhead, m_kxsystem->GetTimeInSeconds(), true);
if (m_show_framerate || m_show_profile || (m_show_debug_properties && m_propertiesPresent))
{
RenderDebugProperties();
}
// Go to next profiling measurement, time spend after this call is shown in the next frame.
m_logger->NextMeasurement(m_kxsystem->GetTimeInSeconds());
m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
m_rasterizer->EndFrame();
// swap backbuffer (drawing into this buffer) <-> front/visible buffer
m_rasterizer->SwapBuffers();
m_rendertools->EndFrame(m_rasterizer);
m_canvas->EndDraw();
}
//#include "PIL_time.h"
//#include "LinearMath/btQuickprof.h"
bool KX_KetsjiEngine::NextFrame()
{
// static hidden::Clock sClock;
m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(),true);
//float dt = sClock.getTimeMicroseconds() * 0.000001f;
//sClock.reset();
if (m_bFixedTime)
m_clockTime += 1./m_ticrate;
else
{
// m_clockTime += dt;
m_clockTime = m_kxsystem->GetTimeInSeconds();
}
double deltatime = m_clockTime - m_frameTime;
if (deltatime<0.f)
{
printf("problem with clock\n");
deltatime = 0.f;
m_clockTime = 0.f;
m_frameTime = 0.f;
}
// Compute the number of logic frames to do each update (fixed tic bricks)
int frames =int(deltatime*m_ticrate);
// if (frames>1)
// printf("****************************************");
// printf("dt = %f, deltatime = %f, frames = %d\n",dt, deltatime,frames);
// if (!frames)
// PIL_sleep_ms(1);
KX_SceneList::iterator sceneit;
int frameOut = 5;
if (frames>frameOut)
{
// printf("framedOut: %d\n",frames);
m_frameTime+=(frames-frameOut)*(1.0/m_ticrate);
frames = frameOut;
}
bool doRender = frames>0;
while (frames)
{
m_frameTime += 1.0/m_ticrate;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit)
// for each scene, call the proceed functions
{
KX_Scene* scene = *sceneit;
/* Suspension holds the physics and logic processing for an
* entire scene. Objects can be suspended individually, and
* the settings for that preceed the logic and physics
* update. */
m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
m_sceneconverter->resetNoneDynamicObjectToIpo();//this is for none dynamic objects with ipo
scene->UpdateObjectActivity();
if (!scene->IsSuspended())
{
// if the scene was suspended recalcutlate the delta tu "curtime"
m_suspendedtime = scene->getSuspendedTime();
if (scene->getSuspendedTime()!=0.0)
scene->setSuspendedDelta(scene->getSuspendedDelta()+m_clockTime-scene->getSuspendedTime());
m_suspendeddelta = scene->getSuspendedDelta();
m_logger->StartLog(tc_network, m_kxsystem->GetTimeInSeconds(), true);
scene->GetNetworkScene()->proceed(m_frameTime);
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_frameTime);
m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
// set Python hooks for each scene
PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
PHY_SetActiveScene(scene);
scene->GetPhysicsEnvironment()->endFrame();
// Update scenegraph after physics step. This maps physics calculations
// into node positions.
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_frameTime);
// Process sensors, and controllers
m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
scene->LogicBeginFrame(m_frameTime);
// Scenegraph needs to be updated again, because Logic Controllers
// can affect the local matrices.
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_frameTime);
// Process actuators
// Do some cleanup work for this logic frame
m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
scene->LogicUpdateFrame(m_frameTime, true);
scene->LogicEndFrame();
// Actuators can affect the scenegraph
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_frameTime);
m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
scene->GetPhysicsEnvironment()->beginFrame();
// Perform physics calculations on the scene. This can involve
// many iterations of the physics solver.
scene->GetPhysicsEnvironment()->proceedDeltaTime(m_frameTime,1.0/m_ticrate);//m_deltatimerealDeltaTime);
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_frameTime);
if (m_game2ipo)
{
m_sceneconverter->WritePhysicsObjectToAnimationIpo(++m_currentFrame);
}
scene->setSuspendedTime(0.0);
} // suspended
else
if(scene->getSuspendedTime()==0.0)
scene->setSuspendedTime(m_clockTime);
DoSound(scene);
m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true);
}
// update system devices
m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
if (m_keyboarddevice)
m_keyboarddevice->NextFrame();
if (m_mousedevice)
m_mousedevice->NextFrame();
if (m_networkdevice)
m_networkdevice->NextFrame();
if (m_audiodevice)
m_audiodevice->NextFrame();
// scene management
ProcessScheduledScenes();
frames--;
}
bool bUseAsyncLogicBricks= false;//true;
if (bUseAsyncLogicBricks)
{
// Logic update sub frame: this will let some logic bricks run at the
// full frame rate.
for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit)
// for each scene, call the proceed functions
{
KX_Scene* scene = *sceneit;
if (!scene->IsSuspended())
{
// if the scene was suspended recalcutlate the delta tu "curtime"
m_suspendedtime = scene->getSuspendedTime();
if (scene->getSuspendedTime()!=0.0)
scene->setSuspendedDelta(scene->getSuspendedDelta()+m_clockTime-scene->getSuspendedTime());
m_suspendeddelta = scene->getSuspendedDelta();
// set Python hooks for each scene
PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment());
PHY_SetActiveScene(scene);
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_clockTime);
// Perform physics calculations on the scene. This can involve
// many iterations of the physics solver.
m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true);
scene->GetPhysicsEnvironment()->proceedDeltaTime(m_clockTime,0.f);
// Update scenegraph after physics step. This maps physics calculations
// into node positions.
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_clockTime);
// Do some cleanup work for this logic frame
m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true);
scene->LogicUpdateFrame(m_clockTime, false);
// Actuators can affect the scenegraph
m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true);
scene->UpdateParents(m_clockTime);
scene->setSuspendedTime(0.0);
} // suspended
else
if(scene->getSuspendedTime()==0.0)
scene->setSuspendedTime(m_clockTime);
DoSound(scene);
m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true);
}
}
m_previousClockTime = m_clockTime;
// Start logging time spend outside main loop
m_logger->StartLog(tc_outside, m_kxsystem->GetTimeInSeconds(), true);
return doRender;
}
void KX_KetsjiEngine::Render()
{
KX_Scene* firstscene = *m_scenes.begin();
const RAS_FrameSettings &framesettings = firstscene->GetFramingType();
m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
// hiding mouse cursor each frame
// (came back when going out of focus and then back in again)
if (m_hideCursor)
m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
// clear the entire game screen with the border color
// only once per frame
m_canvas->BeginDraw();
if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED) {
m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
if (m_overrideFrameColor)
{
// Do not use the framing bar color set in the Blender scenes
m_canvas->ClearColor(
m_overrideFrameColorR,
m_overrideFrameColorG,
m_overrideFrameColorB,
1.0
);
}
else
{
// Use the framing bar color set in the Blender scenes
m_canvas->ClearColor(
framesettings.BarRed(),
framesettings.BarGreen(),
framesettings.BarBlue(),
1.0
);
}
// clear the -whole- viewport
m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
}
m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE);
// BeginFrame() sets the actual drawing area. You can use a part of the window
if (!BeginFrame())
return;
KX_SceneList::iterator sceneit;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
// for each scene, call the proceed functions
{
KX_Scene* scene = *sceneit;
KX_Camera* cam = scene->GetActiveCamera();
// pass the scene's worldsettings to the rasterizer
SetWorldSettings(scene->GetWorldInfo());
// Avoid drawing the scene with the active camera twice when it's viewport is enabled
if(cam && !cam->GetViewport())
{
if (scene->IsClearingZBuffer())
m_rasterizer->ClearDepthBuffer();
m_rendertools->SetAuxilaryClientInfo(scene);
//Initialize scene viewport.
SetupRenderFrame(scene, cam);
// do the rendering
RenderFrame(scene, cam);
}
list<class KX_Camera*>* cameras = scene->GetCameras();
// Draw the scene once for each camera with an enabled viewport
list<KX_Camera*>::iterator it = cameras->begin();
while(it != cameras->end())
{
if((*it)->GetViewport())
{
if (scene->IsClearingZBuffer())
m_rasterizer->ClearDepthBuffer();
m_rendertools->SetAuxilaryClientInfo(scene);
//Initialize scene viewport.
SetupRenderFrame(scene, (*it));
// do the rendering
RenderFrame(scene, (*it));
}
it++;
}
}
// only one place that checks for stereo
if(m_rasterizer->Stereo())
{
m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_RIGHTEYE);
if (!BeginFrame())
return;
KX_SceneList::iterator sceneit;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
// for each scene, call the proceed functions
{
KX_Scene* scene = *sceneit;
KX_Camera* cam = scene->GetActiveCamera();
// pass the scene's worldsettings to the rasterizer
SetWorldSettings(scene->GetWorldInfo());
if (scene->IsClearingZBuffer())
m_rasterizer->ClearDepthBuffer();
//pass the scene, for picking and raycasting (shadows)
m_rendertools->SetAuxilaryClientInfo(scene);
//Initialize scene viewport.
//SetupRenderFrame(scene);
SetupRenderFrame(scene, cam);
// do the rendering
//RenderFrame(scene);
RenderFrame(scene, cam);
}
} // if(m_rasterizer->Stereo())
EndFrame();
}
void KX_KetsjiEngine::RequestExit(int exitrequestmode)
{
m_exitcode = exitrequestmode;
}
void KX_KetsjiEngine::SetNameNextGame(const STR_String& nextgame)
{
m_exitstring = nextgame;
}
int KX_KetsjiEngine::GetExitCode()
{
// if a gameactuator has set an exitcode or if there are no scenes left
if (!m_exitcode)
{
if (m_scenes.begin()==m_scenes.end())
m_exitcode = KX_EXIT_REQUEST_NO_SCENES_LEFT;
}
return m_exitcode;
}
const STR_String& KX_KetsjiEngine::GetExitString()
{
return m_exitstring;
}
void KX_KetsjiEngine::DoSound(KX_Scene* scene)
{
m_logger->StartLog(tc_sound, m_kxsystem->GetTimeInSeconds(), true);
KX_Camera* cam = scene->GetActiveCamera();
if (!cam)
return;
MT_Point3 listenerposition = cam->NodeGetWorldPosition();
MT_Vector3 listenervelocity = cam->GetLinearVelocity();
MT_Matrix3x3 listenerorientation = cam->NodeGetWorldOrientation();
SND_Scene* soundscene = scene->GetSoundScene();
soundscene->SetListenerTransform(
listenerposition,
listenervelocity,
listenerorientation);
soundscene->Proceed();
}
void KX_KetsjiEngine::SetBackGround(KX_WorldInfo* wi)
{
if (wi->hasWorld())
{
if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED)
{
m_rasterizer->SetBackColor(
wi->getBackColorRed(),
wi->getBackColorGreen(),
wi->getBackColorBlue(),
0.0
);
}
}
}
void KX_KetsjiEngine::SetWorldSettings(KX_WorldInfo* wi)
{
if (wi->hasWorld())
{
// ...
m_rasterizer->SetAmbientColor(
wi->getAmbientColorRed(),
wi->getAmbientColorGreen(),
wi->getAmbientColorBlue()
);
if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED)
{
if (wi->hasMist())
{
m_rasterizer->SetFog(
wi->getMistStart(),
wi->getMistDistance(),
wi->getMistColorRed(),
wi->getMistColorGreen(),
wi->getMistColorBlue()
);
}
else
{
m_rasterizer->DisableFog();
}
}
}
}
void KX_KetsjiEngine::SetDrawType(int drawingmode)
{
m_drawingmode = drawingmode;
}
void KX_KetsjiEngine::EnableCameraOverride(const STR_String& forscene)
{
m_overrideCam = true;
m_overrideSceneName = forscene;
}
void KX_KetsjiEngine::SetCameraZoom(float camzoom)
{
m_cameraZoom = camzoom;
}
void KX_KetsjiEngine::SetCameraOverrideUseOrtho(bool useOrtho)
{
m_overrideCamUseOrtho = useOrtho;
}
void KX_KetsjiEngine::SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat)
{
m_overrideCamProjMat = mat;
}
void KX_KetsjiEngine::SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat)
{
m_overrideCamViewMat = mat;
}
void KX_KetsjiEngine::SetupRenderFrame(KX_Scene *scene, KX_Camera* cam)
{
// In this function we make sure the rasterizer settings are upto
// date. We compute the viewport so that logic
// using this information is upto date.
// Note we postpone computation of the projection matrix
// so that we are using the latest camera position.
RAS_Rect viewport;
if (!cam)
return;
if (cam->GetViewport()) {
viewport.SetLeft(cam->GetViewportLeft());
viewport.SetBottom(cam->GetViewportBottom());
viewport.SetRight(cam->GetViewportRight());
viewport.SetTop(cam->GetViewportTop());
}
else if ( m_overrideCam || (scene->GetName() != m_overrideSceneName) || m_overrideCamUseOrtho ) {
RAS_FramingManager::ComputeViewport(
scene->GetFramingType(),
m_canvas->GetDisplayArea(),
viewport
);
} else {
viewport.SetLeft(0);
viewport.SetBottom(0);
viewport.SetRight(int(m_canvas->GetWidth()));
viewport.SetTop(int(m_canvas->GetHeight()));
}
// store the computed viewport in the scene
scene->SetSceneViewport(viewport);
// set the viewport for this frame and scene
m_canvas->SetViewPort(
viewport.GetLeft(),
viewport.GetBottom(),
viewport.GetRight(),
viewport.GetTop()
);
}
// update graphics
void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam)
{
float left, right, bottom, top, nearfrust, farfrust;
const float ortho = 100.0;
// KX_Camera* cam = scene->GetActiveCamera();
if (!cam)
return;
// see KX_BlenderMaterial::Activate
//m_rasterizer->SetAmbient();
m_rasterizer->DisplayFog();
if (m_overrideCam && (scene->GetName() == m_overrideSceneName) && m_overrideCamUseOrtho) {
MT_CmMatrix4x4 projmat = m_overrideCamProjMat;
m_rasterizer->SetProjectionMatrix(projmat);
} else if (cam->hasValidProjectionMatrix() && !cam->GetViewport() )
{
m_rasterizer->SetProjectionMatrix(cam->GetProjectionMatrix());
} else
{
RAS_FrameFrustum frustum;
float lens = cam->GetLens();
nearfrust = cam->GetCameraNear();
farfrust = cam->GetCameraFar();
if (!cam->GetCameraData()->m_perspective)
{
lens *= ortho;
nearfrust = (nearfrust + 1.0)*ortho;
farfrust *= ortho;
}
RAS_FramingManager::ComputeFrustum(
scene->GetFramingType(),
m_canvas->GetDisplayArea(),
scene->GetSceneViewport(),
lens,
nearfrust,
farfrust,
frustum
);
left = frustum.x1 * m_cameraZoom;
right = frustum.x2 * m_cameraZoom;
bottom = frustum.y1 * m_cameraZoom;
top = frustum.y2 * m_cameraZoom;
nearfrust = frustum.camnear;
farfrust = frustum.camfar;
MT_Matrix4x4 projmat = m_rasterizer->GetFrustumMatrix(
left, right, bottom, top, nearfrust, farfrust);
cam->SetProjectionMatrix(projmat);
// Otherwise the projection matrix for each eye will be the same...
if (m_rasterizer->Stereo())
cam->InvalidateProjectionMatrix();
}
MT_Transform camtrans(cam->GetWorldToCamera());
if (!cam->GetCameraData()->m_perspective)
camtrans.getOrigin()[2] *= ortho;
MT_Matrix4x4 viewmat(camtrans);
m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldPosition(),
cam->GetCameraLocation(), cam->GetCameraOrientation());
cam->SetModelviewMatrix(viewmat);
scene->UpdateMeshTransformations();
// The following actually reschedules all vertices to be
// redrawn. There is a cache between the actual rescheduling
// and this call though. Visibility is imparted when this call
// runs through the individual objects.
scene->CalculateVisibleMeshes(m_rasterizer,cam);
scene->RenderBuckets(camtrans, m_rasterizer, m_rendertools);
PostRenderFrame();
}
void KX_KetsjiEngine::PostRenderFrame()
{
m_rendertools->PushMatrix();
m_rendertools->Render2DFilters(m_canvas);
m_rendertools->MotionBlur(m_rasterizer);
m_rendertools->PopMatrix();
}
void KX_KetsjiEngine::StopEngine()
{
if (m_bInitialized)
{
if (m_game2ipo)
{
// printf("TestHandlesPhysicsObjectToAnimationIpo\n");
m_sceneconverter->TestHandlesPhysicsObjectToAnimationIpo();
}
KX_SceneList::iterator sceneit;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
{
KX_Scene* scene = *sceneit;
m_sceneconverter->RemoveScene(scene);
}
m_scenes.clear();
// cleanup all the stuff
m_rasterizer->Exit();
}
}
// Scene Management is able to switch between scenes
// and have several scene's running in parallel
void KX_KetsjiEngine::AddScene(KX_Scene* scene)
{
m_scenes.push_back(scene);
PostProcessScene(scene);
SceneListsChanged();
}
void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene)
{
bool override_camera = (m_overrideCam && (scene->GetName() == m_overrideSceneName));
// if there is no activecamera, or the camera is being
// overridden we need to construct a temporarily camera
if (!scene->GetActiveCamera() || override_camera)
{
KX_Camera* activecam = NULL;
RAS_CameraData camdata = RAS_CameraData();
activecam = new KX_Camera(scene,KX_Scene::m_callbacks,camdata, false);
activecam->SetName("__default__cam__");
// set transformation
if (override_camera) {
const MT_CmMatrix4x4& cammatdata = m_overrideCamViewMat;
MT_Transform trans = MT_Transform(cammatdata.getPointer());
MT_Transform camtrans;
camtrans.invert(trans);
activecam->NodeSetLocalPosition(camtrans.getOrigin());
activecam->NodeSetLocalOrientation(camtrans.getBasis());
activecam->NodeUpdateGS(0,true);
} else {
activecam->NodeSetLocalPosition(MT_Point3(0.0, 0.0, 0.0));
activecam->NodeSetLocalOrientation(MT_Vector3(0.0, 0.0, 0.0));
activecam->NodeUpdateGS(0,true);
}
scene->AddCamera(activecam);
scene->SetActiveCamera(activecam);
scene->GetObjectList()->Add(activecam->AddRef());
scene->GetRootParentList()->Add(activecam->AddRef());
//done with activecam
activecam->Release();
}
scene->UpdateParents(0.0);
}
void KX_KetsjiEngine::RenderDebugProperties()
{
STR_String debugtxt;
int xcoord = 10; // mmmm, these constants were taken from blender source
int ycoord = 14; // to 'mimic' behaviour
float tottime = m_logger->GetAverage();
if (tottime < 1e-6f) {
tottime = 1e-6f;
}
// Set viewport to entire canvas
RAS_Rect viewport;
m_canvas->SetViewPort(0, 0, int(m_canvas->GetWidth()), int(m_canvas->GetHeight()));
/* Framerate display */
if (m_show_framerate) {
debugtxt.Format("swap : %.3f (%.3f frames per second)", tottime, 1.0/tottime);
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
xcoord,
ycoord,
m_canvas->GetWidth() /* RdV, TODO ?? */,
m_canvas->GetHeight() /* RdV, TODO ?? */);
ycoord += 14;
}
/* Profile and framerate display */
if (m_show_profile)
{
for (int j = tc_first; j < tc_numCategories; j++)
{
debugtxt.Format(m_profileLabels[j]);
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
xcoord,ycoord,
m_canvas->GetWidth(),
m_canvas->GetHeight());
double time = m_logger->GetAverage((KX_TimeCategory)j);
debugtxt.Format("%2.2f %%", time/tottime * 100.f);
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
xcoord + 60 ,ycoord,
m_canvas->GetWidth(),
m_canvas->GetHeight());
ycoord += 14;
}
}
/* Property display*/
if (m_show_debug_properties && m_propertiesPresent)
{
KX_SceneList::iterator sceneit;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
{
KX_Scene* scene = *sceneit;
/* the 'normal' debug props */
vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
for (vector<SCA_DebugProp*>::iterator it = debugproplist.begin();
!(it==debugproplist.end());it++)
{
CValue* propobj = (*it)->m_obj;
STR_String objname = propobj->GetName();
STR_String propname = (*it)->m_name;
CValue* propval = propobj->GetProperty(propname);
if (propval)
{
STR_String text = propval->GetText();
debugtxt = objname + "." + propname + " = " + text;
m_rendertools->RenderText2D(RAS_IRenderTools::RAS_TEXT_PADDED,
debugtxt.Ptr(),
xcoord,
ycoord,
m_canvas->GetWidth(),
m_canvas->GetHeight());
ycoord += 14;
}
}
}
}
}
KX_SceneList* KX_KetsjiEngine::CurrentScenes()
{
return &m_scenes;
}
KX_Scene* KX_KetsjiEngine::FindScene(const STR_String& scenename)
{
KX_SceneList::iterator sceneit = m_scenes.begin();
// bit risky :) better to split the second clause
while ( (sceneit != m_scenes.end())
&& ((*sceneit)->GetName() != scenename))
{
sceneit++;
}
return ((sceneit == m_scenes.end()) ? NULL : *sceneit);
}
void KX_KetsjiEngine::ConvertAndAddScene(const STR_String& scenename,bool overlay)
{
// only add scene when it doesn't exist!
if (FindScene(scenename))
{
STR_String tmpname = scenename;
printf("warning: scene %s already exists, not added!\n",tmpname.Ptr());
}
else
{
if (overlay)
{
m_addingOverlayScenes.insert(scenename);
}
else
{
m_addingBackgroundScenes.insert(scenename);
}
}
}
void KX_KetsjiEngine::RemoveScene(const STR_String& scenename)
{
if (FindScene(scenename))
{
m_removingScenes.insert(scenename);
}
else
{
// STR_String tmpname = scenename;
std::cout << "warning: scene " << scenename << " does not exist, not removed!" << std::endl;
}
}
void KX_KetsjiEngine::RemoveScheduledScenes()
{
if (m_removingScenes.size())
{
set<STR_String>::iterator scenenameit;
for (scenenameit=m_removingScenes.begin();scenenameit != m_removingScenes.end();scenenameit++)
{
STR_String scenename = *scenenameit;
KX_SceneList::iterator sceneit;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
{
KX_Scene* scene = *sceneit;
if (scene->GetName()==scenename)
{
m_sceneconverter->RemoveScene(scene);
m_scenes.erase(sceneit);
break;
}
}
}
m_removingScenes.clear();
}
}
KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename)
{
KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice,
m_mousedevice,
m_networkdevice,
m_audiodevice,
scenename);
m_sceneconverter->ConvertScene(scenename,
tmpscene,
m_pythondictionary,
m_keyboarddevice,
m_rendertools,
m_canvas);
return tmpscene;
}
void KX_KetsjiEngine::AddScheduledScenes()
{
set<STR_String>::iterator scenenameit;
if (m_addingOverlayScenes.size())
{
for (scenenameit = m_addingOverlayScenes.begin();
scenenameit != m_addingOverlayScenes.end();
scenenameit++)
{
STR_String scenename = *scenenameit;
KX_Scene* tmpscene = CreateScene(scenename);
m_scenes.push_back(tmpscene);
PostProcessScene(tmpscene);
}
m_addingOverlayScenes.clear();
}
if (m_addingBackgroundScenes.size())
{
for (scenenameit = m_addingBackgroundScenes.begin();
scenenameit != m_addingBackgroundScenes.end();
scenenameit++)
{
STR_String scenename = *scenenameit;
KX_Scene* tmpscene = CreateScene(scenename);
m_scenes.insert(m_scenes.begin(),tmpscene);
PostProcessScene(tmpscene);
}
m_addingBackgroundScenes.clear();
}
}
void KX_KetsjiEngine::ReplaceScene(const STR_String& oldscene,const STR_String& newscene)
{
m_replace_scenes.insert(std::make_pair(oldscene,newscene));
}
// replace scene is not the same as removing and adding because the
// scene must be in exact the same place (to maintain drawingorder)
// (nzc) - should that not be done with a scene-display list? It seems
// stupid to rely on the mem allocation order...
void KX_KetsjiEngine::ReplaceScheduledScenes()
{
if (m_replace_scenes.size())
{
set<pair<STR_String,STR_String> >::iterator scenenameit;
for (scenenameit = m_replace_scenes.begin();
scenenameit != m_replace_scenes.end();
scenenameit++)
{
STR_String oldscenename = (*scenenameit).first;
STR_String newscenename = (*scenenameit).second;
int i=0;
/* Scenes are not supposed to be included twice... I think */
KX_SceneList::iterator sceneit;
for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++)
{
KX_Scene* scene = *sceneit;
if (scene->GetName() == oldscenename)
{
m_sceneconverter->RemoveScene(scene);
KX_Scene* tmpscene = CreateScene(newscenename);
m_scenes[i]=tmpscene;
PostProcessScene(tmpscene);
}
i++;
}
}
m_replace_scenes.clear();
}
}
void KX_KetsjiEngine::SuspendScene(const STR_String& scenename)
{
KX_Scene* scene = FindScene(scenename);
if (scene) scene->Suspend();
}
void KX_KetsjiEngine::ResumeScene(const STR_String& scenename)
{
KX_Scene* scene = FindScene(scenename);
if (scene) scene->Resume();
}
void KX_KetsjiEngine::SetUseFixedTime(bool bUseFixedTime)
{
m_bFixedTime = bUseFixedTime;
}
void KX_KetsjiEngine::SetGame2IpoMode(bool game2ipo,int startFrame)
{
m_game2ipo = game2ipo;
if (game2ipo)
{
//when recording physics keyframes, always run at a fixed framerate
m_bFixedTime = true;
}
m_currentFrame = startFrame;
}
bool KX_KetsjiEngine::GetUseFixedTime(void) const
{
return m_bFixedTime;
}
double KX_KetsjiEngine::GetSuspendedDelta()
{
return m_suspendeddelta;
}
double KX_KetsjiEngine::GetTicRate()
{
return m_ticrate;
}
void KX_KetsjiEngine::SetTicRate(double ticrate)
{
m_ticrate = ticrate;
}
void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties)
{
m_show_framerate = frameRate;
m_show_profile = profile;
m_show_debug_properties = properties;
}
void KX_KetsjiEngine::GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const
{
frameRate = m_show_framerate;
profile = m_show_profile;
properties = m_show_debug_properties;
}
void KX_KetsjiEngine::ProcessScheduledScenes(void)
{
// Check whether there will be changes to the list of scenes
if (m_addingOverlayScenes.size() ||
m_addingBackgroundScenes.size() ||
m_replace_scenes.size() ||
m_removingScenes.size()) {
// Change the scene list
ReplaceScheduledScenes();
RemoveScheduledScenes();
AddScheduledScenes();
// Notify
SceneListsChanged();
}
}
void KX_KetsjiEngine::SceneListsChanged(void)
{
m_propertiesPresent = false;
KX_SceneList::iterator sceneit = m_scenes.begin();
while ((sceneit != m_scenes.end()) && (!m_propertiesPresent))
{
KX_Scene* scene = *sceneit;
vector<SCA_DebugProp*>& debugproplist = scene->GetDebugProperties();
m_propertiesPresent = !debugproplist.empty();
sceneit++;
}
}
void KX_KetsjiEngine::SetHideCursor(bool hideCursor)
{
m_hideCursor = hideCursor;
}
bool KX_KetsjiEngine::GetHideCursor(void) const
{
return m_hideCursor;
}
void KX_KetsjiEngine::SetUseOverrideFrameColor(bool overrideFrameColor)
{
m_overrideFrameColor = overrideFrameColor;
}
bool KX_KetsjiEngine::GetUseOverrideFrameColor(void) const
{
return m_overrideFrameColor;
}
void KX_KetsjiEngine::SetOverrideFrameColor(float r, float g, float b)
{
m_overrideFrameColorR = r;
m_overrideFrameColorG = g;
m_overrideFrameColorB = b;
}
void KX_KetsjiEngine::GetOverrideFrameColor(float& r, float& g, float& b) const
{
r = m_overrideFrameColorR;
g = m_overrideFrameColorG;
b = m_overrideFrameColorB;
}
|