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
#include "fsCNative3dScene.h"

#include "src/fsCRenderTexture.h"

#if defined fs3d

#include <2d/Layer.h>
#include <2d/Light.h>
#include <3d/Mesh.h>
#include <3d/MeshRenderer.h>
#include <base/Director.h>
#include <renderer/Renderer.h>
#include <cmath>
#include <string_view>

#include <fsCore/src/fsCAppSettings.h>
#include <fsCore/src/fsNMaths.h>
#include <fsCore/fsPoint.h>
#include <fsAppCore/src/fsCAppCoreMain.h>

#include <fsAppCore/fsIDisplay.h>
#include <fsRenderer/impl/axmol/fsCScene.h>
#include <fsRenderer/impl/axmol/fsCDisplay.h>
#include <fsRenderer/impl/axmol/fsNAxmolRenderView.h>


#include <fs3d/fsC3dSprite.h>
#include <fs3d/fsC3dCamera.h>
#include <fs3d/impl/axmol/fsC3dModelData.h>
#include <fs3d/impl/axmol/fsC3dLight.h>

namespace
{
struct fsSViewportState
{
	ax::Viewport logical;
	// Camera viewport in the coordinate space expected by the active target:
	// logical for an RTT/mobile target, framebuffer pixels for direct desktop.
	ax::Viewport camera;
	bool fixedAspectActive = false;
};

ax::Mat4 matrixIdentityGet()
{
#ifdef AXMOL_V3
	return ax::Mat4::identity();
#else
	return ax::Mat4::IDENTITY;
#endif
}

bool desktopFixedAspectGet()
{
#if defined(fsDesktop)
	return fsIDisplay::fixedAspectGet();
#else
	return false;
#endif
}

bool helperPathNameGet(std::string_view pName)
{
	return pName.size() >= 4 && pName.substr(pName.size() - 4) == "Path";
}

void helperPathVisibilityApplyRecursive(ax::Node* pNode)
{
	if (!pNode)
	{
		return;
	}

	if (auto* meshRenderer = dynamic_cast<ax::MeshRenderer*>(pNode))
	{
		for (auto* mesh : meshRenderer->getMeshes())
		{
			if (!helperPathNameGet(mesh->getName()))
			{
				continue;
			}

			mesh->setVisible(false);
		}
	}

	for (auto* child : pNode->getChildren())
	{
		helperPathVisibilityApplyRecursive(child);
	}
}

fsSViewportState viewportStateGet()
{
	fsF32 visibleCanvasW = static_cast<fsF32>(fsIDisplay::instanceGet()->visibleCanvasWidthGet());
	fsF32 visibleCanvasH = static_cast<fsF32>(fsIDisplay::instanceGet()->visibleCanvasHeightGet());
	auto* const renderView = ax::Director::getInstance()->getRenderView();
	if ((visibleCanvasW <= 0.0f || visibleCanvasH <= 0.0f) && renderView)
	{
		const ax::Vec2 renderViewVisibleSize = renderView->getVisibleSize();
		if (visibleCanvasW <= 0.0f)
		{
			visibleCanvasW = renderViewVisibleSize.width;
		}
		if (visibleCanvasH <= 0.0f)
		{
			visibleCanvasH = renderViewVisibleSize.height;
		}
	}
	if ((visibleCanvasW <= 0.0f || visibleCanvasH <= 0.0f) && renderView)
	{
		const ax::Vec2 renderViewDesignSize = renderView->getDesignResolutionSize();
		if (visibleCanvasW <= 0.0f)
		{
			visibleCanvasW = renderViewDesignSize.width;
		}
		if (visibleCanvasH <= 0.0f)
		{
			visibleCanvasH = renderViewDesignSize.height;
		}
	}
	if (visibleCanvasW <= 0.0f)
	{
		visibleCanvasW = static_cast<fsF32>(fsIDisplay::instanceGet()->designCanvasWidthGet());
	}
	if (visibleCanvasH <= 0.0f)
	{
		visibleCanvasH = static_cast<fsF32>(fsIDisplay::instanceGet()->designCanvasHeightGet());
	}

	fsSViewportState viewportState;
	viewportState.logical.x = 0;
	viewportState.logical.y = 0;
	viewportState.logical.width = static_cast<int>(visibleCanvasW);
	viewportState.logical.height = static_cast<int>(visibleCanvasH);

	// Fission decides any letterbox/pillarbox in visible-canvas space. Conversion
	// into the active render target's coordinate space happens once, below.

#if defined(fsDesktop)
	if (desktopFixedAspectGet())
	{
		const fsF32 designW = static_cast<fsF32>(fsIDisplay::instanceGet()->designCanvasWidthGet());
		const fsF32 designH = static_cast<fsF32>(fsIDisplay::instanceGet()->designCanvasHeightGet());
		if (designW > 0.0f && designH > 0.0f)
		{
			const auto fit = fsNAxmolRenderView::aspectFitRectGet(designW / designH, visibleCanvasW, visibleCanvasH);
			viewportState.logical.x = static_cast<int>(fit.x);
			viewportState.logical.y = static_cast<int>(fit.y);
			viewportState.logical.width = static_cast<int>(fit.w);
			viewportState.logical.height = static_cast<int>(fit.h);
		}
	}
#endif

	const fsF32 epsilon = 0.01f;
	viewportState.fixedAspectActive = desktopFixedAspectGet()<--- Condition 'desktopFixedAspectGet()' is always false<--- Calling function 'desktopFixedAspectGet' returns 0
		&& (fsNMaths::fabsF32(viewportState.logical.x) > epsilon
			|| fsNMaths::fabsF32(viewportState.logical.y) > epsilon
			|| fsNMaths::fabsF32(viewportState.logical.width - visibleCanvasW) > epsilon
			|| fsNMaths::fabsF32(viewportState.logical.height - visibleCanvasH) > epsilon);

	viewportState.camera = viewportState.logical;

	// The screen render texture is created in visible-canvas (logical) units and
	// is scaled to the framebuffer when its sprite is presented. Mobile render
	// views also expect this logical viewport. A direct desktop render does not
	// get that final texture scaling step, so its camera viewport must be mapped
	// to framebuffer pixels here (including Retina/render scaling).
#if defined(fsScreenTextureEffect) || !defined(fsDesktop)
	return viewportState;
#else
	if (!renderView)
	{
		return viewportState;
	}

	const ax::Rect& viewportRect = fsNAxmolRenderView::viewportRectGet(renderView);
	fsF32 pixelScaleX = 1.0f;
	fsF32 pixelScaleY = 1.0f;
	fsNAxmolRenderView::pixelScaleGet(renderView, pixelScaleX, pixelScaleY);
	viewportState.camera.x = static_cast<int>(viewportState.logical.x * pixelScaleX + viewportRect.origin.x);
	viewportState.camera.y = static_cast<int>(viewportState.logical.y * pixelScaleY + viewportRect.origin.y);
	viewportState.camera.width = static_cast<int>(viewportState.logical.width * pixelScaleX);
	viewportState.camera.height = static_cast<int>(viewportState.logical.height * pixelScaleY);
	return viewportState;
#endif
}

}


void fsCNative3dScene::pick(const fsPoint& pScreenPos, fsI3dScene::fsTPickCallback pPickCallback)
{
#ifdef AXMOL_V3
	ax::Ray ray = mWorldCamera->screenToRay(ax::Vec2(pScreenPos.x, pScreenPos.y));
#else
	ax::Vec3 nearP(pScreenPos.x, pScreenPos.y, -1.0f);
	ax::Vec3 farP(pScreenPos.x, pScreenPos.y, 1.0f);
	// convert screen touch location to the world location on near and far plane
	auto size = ax::Director::getInstance()->getWinSize();
	mWorldCamera->unprojectGL(size, &nearP, &nearP);
 	mWorldCamera->unprojectGL(size, &farP, &farP);
	ax::Vec3 dir = farP - nearP;
	dir.normalize();

	ax::Ray ray;
	ray._origin = nearP;
	ray._direction = dir;
#endif

	std::for_each(std::begin(mDynamicModels), std::end(mDynamicModels), 
		[&](fsC3dSprite* sprt3d) 
		{
			auto model = static_cast<fsC3dModelData*>(sprt3d->mModelData.get())->mModel;
			if (ray.intersects(model->getAABBRecursively()))
			{
				pPickCallback(sprt3d);
			}
		});
}

fsBool fsCNative3dScene::worldModelGet(ax::MeshRenderer* pModel) const
{
	return worldModelGet(static_cast<ax::Node*>(pModel));
}

fsBool fsCNative3dScene::worldModelGet(ax::Node* pNode) const
{
	if (!pNode)
	{
		return false;
	}

	const auto& name = pNode->getName();
	if (std::string_view::npos != name.find("camera_") || std::string_view::npos != name.find("light_"))
	{
		return true;
	}

	return std::end(pNode->getChildren()) != std::find_if(
		std::begin(pNode->getChildren()),
		std::end(pNode->getChildren()),
		[this](ax::Node* child)
		{
			return worldModelGet(child);
		});
}

void fsCNative3dScene::spriteRemove(fsC3dSprite* const p3dSprite)
{
	auto model = static_cast<fsC3dModelData*>(p3dSprite->mModelData.get())->mModel;
	if (dynamic_cast<ax::MeshRenderer*>(model))
	{
		mDynamicModels.erase(std::remove(std::begin(mDynamicModels), std::end(mDynamicModels), p3dSprite), mDynamicModels.end());
	}
	// Models are parented to mSceneRoot so they inherit Fission's scene transform.
	// Removing from mScene would leave the old model attached across levels.
	if (auto* parent = model->getParent())
	{
		parent->removeChild(model);
	}
}

void fsCNative3dScene::nodeProcess(ax::Node* const pNode)
{
	if (std::string_view::npos != pNode->getName().find("camera_"))
	{
		if (mExplicitCameraSet)
		{
			return;
		}

		fsStr fov = pNode->getName().data();
		fov.erase(0, fov.find("_") + 1);
		fsVec3d params = { fov.chomp("_").toF32(),fov.chomp("_").toF32(), fov.chomp("_").toF32() };
		cameraCreate(params.x, params.y, params.z);

		ax::Vec3 worldPos;
		const auto worldTransform = pNode->getNodeToWorldTransform();
		worldTransform.getTranslation(&worldPos);
		mWorldCamera->setPosition3D(worldPos);
		cameraBaseStore(worldTransform, worldPos);
		mWorldCamera->lookAt(worldPos + mCameraBaseForward * 100.0f, mCameraBaseUp);
	}
	else if (std::string_view::npos != pNode->getName().find("light_"))
	{
		fsStr rgb = pNode->getName().data();
		rgb.erase(0, rgb.find("_") + 1);
		rgb.erase(0, rgb.find("_") + 1);
		const fsSColour lightCol{ rgb.chomp("_").toF32() / 255.0f, rgb.chomp("_").toF32() / 255.0f, rgb.chomp("_").toF32() / 255.0f, 1.0f };

		if (std::string_view::npos != pNode->getName().find("_ambient"))
		{
			mLights.push_back(fsC3dLight::create(lightCol));
		}
		else if (std::string_view::npos != pNode->getName().find("_direct"))
		{
			fsVec3d dir{ -pNode->getRotation3D().x, -pNode->getRotation3D().x, -pNode->getRotation3D().z };
			mLights.push_back(fsC3dLight::create(lightCol, dir));
		}
		ligthtAdd(mLights.back().get());
	}
}

void fsCNative3dScene::nodeProcessRecursive(ax::Node* const pNode)
{
	if (!pNode)
	{
		return;
	}

	nodeProcess(pNode);
	std::for_each(std::begin(pNode->getChildren()), std::end(pNode->getChildren()), [&](ax::Node* child)
	{
		nodeProcessRecursive(child);
	});
}

void fsCNative3dScene::spriteAdd(fsC3dSprite* const p3dSprite)
{
	auto model = static_cast<fsC3dModelData*>(p3dSprite->mModelData.get())->mModel;
	model->setCameraMask(static_cast<fsS32>(eSCENE_FLAG::DYNAMIC_MODELS));

	if (worldModelGet(model))
	{
		model->setCameraMask(static_cast<fsS32>(eSCENE_FLAG::WORLD_MODELS));
		helperPathVisibilityApplyRecursive(model);
		nodeProcessRecursive(model);
		mSceneRoot->addChild(model);
		model->onEnter();
	}
	else
	{
		if (auto sprt = dynamic_cast<ax::MeshRenderer*>(model))
		{
			if (!sprt->getName().empty())
			{
				sprt->setLightMask(static_cast<fsS32>(eSCENE_FLAG::DYNAMIC_MODELS));
				mDynamicModels.push_back(p3dSprite);
			}
		}
        mSceneRoot->addChild(model);
		model->onEnter();
	}
}

void fsCNative3dScene::ligthtAdd(fsI3dLight* const pLight)<--- The member function 'fsCNative3dScene::ligthtAdd' can be static.
{
	// You would think to add the light to our current scene, but during the CCSprite3D::draw it gets the current scene
	// from the director to get the lights so...
	//mScene->addChild(light);

	auto light = static_cast<ax::BaseLight*>(pLight->implGet());
	light->setLightFlag(static_cast<ax::LightFlag>(eSCENE_FLAG::DYNAMIC_MODELS));
	ax::Director::getInstance()->getRunningScene()->addChild(light);
}

void fsCNative3dScene::ligthtRemove(fsI3dLight* const pLight)<--- The member function 'fsCNative3dScene::ligthtRemove' can be static.
{
	if (ax::Director::getInstance()->getRunningScene())
	{
		if (auto light = static_cast<ax::BaseLight*>(pLight->implGet()))
		{
			ax::Director::getInstance()->getRunningScene()->removeChild(light);
		}
	}
}

fsF32 fsCNative3dScene::fovCalculate(fsF32 pFOV) const<--- The member function 'fsCNative3dScene::fovCalculate' can be static.
{
	// Calculate the fov from the supplied blender fov - HFOV => VFOV ?
	// https://blender.stackexchange.com/questions/23431/how-to-set-camera-horizontal-and-vertical-fov
	const fsF32 displayWidth = fsIDisplay::instanceGet()->designCanvasWidthGet();
	const fsF32 displayHeight = fsIDisplay::instanceGet()->designCanvasHeightGet();
	fsF32 scaleY = 1.0f;
	if (fsIDisplay::fixedAspectGet())
	{
		if (displayWidth / displayHeight < 16.0f / 9.0f)
		{
			scaleY = displayWidth * 9.0f / 16.0f /
			         static_cast<fsF32>(fsIDisplay::instanceGet()->designCanvasHeightGet());
		}
	}

	return 2 * fsNMaths::atanF32((displayHeight * 0.5f / scaleY)
                / (displayWidth * 0.5 / fsNMaths::tanF32(pFOV * fsNMaths::fsPI / 180.0f / 2.0f))) 
                * 180.0f / fsNMaths::fsPI;
}

fsF32 fsCNative3dScene::effectiveFovGet() const
{
	fsF32 effectiveFov = mCameraFov;
	if (mZoomScale > 0.0001f)
	{
		effectiveFov = 2.0f * fsNMaths::atanF32(
			fsNMaths::tanF32(mCameraFov * fsNMaths::fsPI / 180.0f / 2.0f) / mZoomScale)
			* 180.0f / fsNMaths::fsPI;
		if (effectiveFov < 1.0f)
		{
			effectiveFov = 1.0f;
		}
		else if (effectiveFov > 179.0f)
		{
			effectiveFov = 179.0f;
		}
	}

	return effectiveFov;
}

void fsCNative3dScene::cameraCreate(fsF32 pFOV, fsF32 pNearClip, fsF32 pFarClip)
{
	if (!mWorldCamera)
	{
		const fsF32 displayWidth = fsIDisplay::instanceGet()->designCanvasWidthGet();
		const fsF32 displayHeight = fsIDisplay::instanceGet()->designCanvasHeightGet();

		if (displayWidth / displayHeight - 1.33f < 0.1f)
		{
			pFOV = 46.8f;
		}

		mCameraFov = fovCalculate(pFOV);
		mCameraNear = pNearClip;
		mCameraFar = pFarClip;

		mWorldCamera = ax::Camera::createPerspective(mCameraFov,
			(fsF32)displayWidth / displayHeight,
			pNearClip, pFarClip);
		
		mWorldCamera->retain();
		mWorldCamera->setCameraFlag(static_cast<ax::CameraFlag>(eSCENE_FLAG::ALL_MODELS));
		mScene->addChild(mWorldCamera);
		// mWorldCamera->setDepth(1);
		// mWorldCamera->setGlobalZOrder(1);
	}
}

void fsCNative3dScene::cameraSet(fsC3dCamera* const pCamera)
{
	if (!pCamera)
	{
		return;
	}

	cameraCreate(pCamera->mFOV, pCamera->mClipNear, pCamera->mClipFar);
	mExplicitCameraSet = true;
	mWorldCamera->setPosition3D(axmol::Vec3(pCamera->mCameraPos.x, pCamera->mCameraPos.y, pCamera->mCameraPos.z));
	if (pCamera->mLookAtTargeting)
	{
		mWorldCamera->lookAt(axmol::Vec3(pCamera->mTargetting.x, pCamera->mTargetting.y, pCamera->mTargetting.z), axmol::Vec3::UNIT_Y);
	}
	else
	{
		mWorldCamera->setRotation3D(axmol::Vec3(pCamera->mTargetting.x, pCamera->mTargetting.y, pCamera->mTargetting.z));
	}
	cameraBaseStore(mWorldCamera->getNodeToWorldTransform(), mWorldCamera->getPosition3D());
}

void fsCNative3dScene::renderDo()
{
	auto* const renderer = ax::Director::getInstance()->getRenderer();
#ifdef AXMOL_V3
	const auto* const previousVisitingCamera = ax::Camera::getVisitingCamera();
#endif
	const ax::Viewport previousCameraViewport = ax::Camera::getDefaultViewport();
	const ax::Viewport activeViewport = renderer->getViewport();
	const fsSViewportState viewportState = viewportStateGet();
#ifdef AXMOL_V3
const ax::Mat4 identityEye = matrixIdentityGet();
#else
	const ax::Mat4 identityEye = matrixIdentityGet();
	ax::Mat4 shiftedProjection = matrixIdentityGet();
	const ax::Mat4* projectionOverride = nullptr;
#endif

	// Scene::render() reapplies Camera::_defaultViewport for each camera. When
	// drawing into the screen RTT we must keep the RTT viewport active or the
	// 3D scene is projected as if it were rendering directly to the backbuffer.
	ax::Camera::setDefaultViewport(viewportState.camera);

	if (mWorldCamera)
	{
		mWorldCamera->setNearPlane(mCameraNear);
		mWorldCamera->setFarPlane(mCameraFar);
		mWorldCamera->setFOV(effectiveFovGet());
		mWorldCamera->setAdditionalTransform(static_cast<const ax::Mat4*>(nullptr));
#ifdef AXMOL_V3
		mWorldCamera->setAdditionalProjection(mProjectionMatrix);
#else
		ax::Mat4::multiply(mProjectionMatrix, mWorldCamera->getProjectionMatrix(), &shiftedProjection);
		projectionOverride = &shiftedProjection;
#endif
	}

	// Scene traversal can refresh the root transform after matrixApplyDo().
	// Reassert the intended transform immediately before rendering.
	sceneTransformsApply(viewportState.fixedAspectActive);

	if (viewportState.fixedAspectActive)
	{
		cameraFixedAspectApply(viewportState.logical);
	}

#if defined fsScreenTextureEffect
	auto* const levelRenderTarget = fsCAppCoreMain::instanceGet()->mLevelRenderTarget;
	levelRenderTarget->partialEnd();

#ifndef AXMOL_V3
	renderer->clear(ax::ClearFlag::DEPTH_AND_STENCIL, ax::Color4F::BLACK, 1, 0, 0);
#else
	// RenderTexturePass applies any backend-specific projection adjustment to
	// the visiting camera selected when the pass begins.
	ax::Camera::setVisitingCamera(mWorldCamera);
#endif

#ifdef AXMOL_V3
	// partialStart() opens a RenderTexturePass and clears depth/stencil inside
	// it. Submit all 3D commands before partialEnd() closes and flushes the pass.
#endif
	levelRenderTarget->partialStart();

#ifdef AXMOL_V3
	mWorldCamera->apply();
	mScene->visit(renderer, identityEye, 0);
#else
	mScene->render(renderer, identityEye, projectionOverride);
#endif

	levelRenderTarget->partialEnd();

#ifdef AXMOL_V3
	ax::Camera::setVisitingCamera(const_cast<ax::Camera*>(previousVisitingCamera));
#endif
	levelRenderTarget->partialStart();
#else
	renderer->render();
#ifdef AXMOL_V3
	ax::Camera::setVisitingCamera(mWorldCamera);
	mWorldCamera->apply();
	mWorldCamera->clearBackground();
	mScene->visit(renderer, identityEye, 0);
	renderer->render();
	ax::Camera::setVisitingCamera(const_cast<ax::Camera*>(previousVisitingCamera));
#else
	mScene->render(renderer, identityEye, projectionOverride);
#endif
#endif

#ifdef AXMOL_V3
	renderer->setViewport(
		activeViewport.x,
		activeViewport.y,
		static_cast<unsigned int>(activeViewport.width),
		static_cast<unsigned int>(activeViewport.height));
#else
	renderer->setViewPort(
		activeViewport.x,
		activeViewport.y,
		static_cast<unsigned int>(activeViewport.width),
		static_cast<unsigned int>(activeViewport.height));
#endif
	ax::Camera::setDefaultViewport(previousCameraViewport);
}

void fsCNative3dScene::matrixApplyDo(const fsAffineMtx2d& pRenderMatrix)
{
	const fsAffineMtx2d displayMatrix = fsIDisplay::instanceGet()->renderMatrixGet();
	const fsSViewportState viewportState = viewportStateGet();
	fsAffineMtx2d sceneMatrix = displayMatrix.inverseGet() * pRenderMatrix;
	const auto sceneScale = sceneMatrix.scaleGet();
	const fsVec2d sceneTranslate = sceneMatrix.translateGet();
	const fsVec2d screenTranslate = pRenderMatrix.translateGet();

	mZoomScale = (sceneScale.x + sceneScale.y) * 0.5f;
	if (mZoomScale < 0.0001f)
	{
		mZoomScale = 1.0f;
	}

	if (mZoomScale > 0.0001f)
	{
		sceneMatrix.set(0, 0, sceneMatrix.get(0, 0) / mZoomScale);
		sceneMatrix.set(0, 1, sceneMatrix.get(0, 1) / mZoomScale);
		sceneMatrix.set(1, 0, sceneMatrix.get(1, 0) / mZoomScale);
		sceneMatrix.set(1, 1, sceneMatrix.get(1, 1) / mZoomScale);
	}

	if (mWorldCamera)
	{
		mWorldCamera->setNearPlane(mCameraNear);
		mWorldCamera->setFarPlane(mCameraFar);
		mWorldCamera->setFOV(effectiveFovGet());
		mWorldCamera->setAdditionalTransform(static_cast<const ax::Mat4*>(nullptr));
	}

	mDisplayMatrix.m[12] = displayMatrix.get(0, 2);
	mDisplayMatrix.m[13] = displayMatrix.get(1, 2);
	mDisplayMatrix.m[0] = displayMatrix.get(0, 0);
	mDisplayMatrix.m[1] = displayMatrix.get(1, 0);
	mDisplayMatrix.m[4] = displayMatrix.get(0, 1);
	mDisplayMatrix.m[5] = displayMatrix.get(1, 1);

	mProjectionMatrix = matrixIdentityGet();
	if (!mEyeBaseSet || fsNMaths::fabsF32(mEyeBaseZoomScale - mZoomScale) > 0.05f)
	{
		mEyeBaseSet = true;
		mSceneBaseTranslate = sceneTranslate;
		mScreenBaseTranslate = screenTranslate;
		mEyeBaseZoomScale = mZoomScale;
	}

	const fsVec2d screenDelta = screenTranslate - mScreenBaseTranslate;

	if (mWorldCamera)
	{
		// Split the incoming 2D transform:
		// - zoom becomes camera FOV
		// - drag since the current zoom baseline becomes a projection shift
		const fsF32 projectionWidth = viewportState.logical.width > 0.0001f
			? static_cast<fsF32>(viewportState.logical.width)
			: static_cast<fsF32>(fsIDisplay::instanceGet()->visibleCanvasWidthGet());
		const fsF32 projectionHeight = viewportState.logical.height > 0.0001f
			? static_cast<fsF32>(viewportState.logical.height)
			: static_cast<fsF32>(fsIDisplay::instanceGet()->visibleCanvasHeightGet());
		if (projectionWidth > 0.0001f && projectionHeight > 0.0001f)
		{
			ax::Mat4 projectionShift = matrixIdentityGet();
			projectionShift.m[12] = (screenDelta.x * 2.0f) / projectionWidth;
			projectionShift.m[13] = (screenDelta.y * 2.0f) / projectionHeight;
			mProjectionMatrix = projectionShift;
		}
	}
	mEyeMatrix = matrixIdentityGet();

	mRenderMatrix.m[12] = mSceneBaseTranslate.x;
	mRenderMatrix.m[13] = mSceneBaseTranslate.y;

	mRenderMatrix.m[0] = sceneMatrix.get(0, 0);
	mRenderMatrix.m[1] = sceneMatrix.get(1, 0);
	mRenderMatrix.m[4] = sceneMatrix.get(0, 1);
	mRenderMatrix.m[5] = sceneMatrix.get(1, 1);

	sceneTransformsApply(viewportState.fixedAspectActive);
}

void fsCNative3dScene::cameraBaseStore(const ax::Mat4& pWorldTransform, const ax::Vec3& pPosition)
{
	ax::Vec3 worldForward;
	ax::Vec3 worldUp;
	pWorldTransform.getForwardVector(&worldForward);
	pWorldTransform.getUpVector(&worldUp);
	cameraBaseStore(pPosition, worldForward, worldUp);
}

void fsCNative3dScene::cameraBaseStore(const ax::Vec3& pPosition, ax::Vec3 pForward, ax::Vec3 pUp)
{
	pForward.normalize();
	pUp.normalize();
	if (pForward.lengthSquared() < 0.0001f)
	{
		pForward = ax::Vec3(0.0f, 0.0f, -1.0f);
	}
	if (pUp.lengthSquared() < 0.0001f)
	{
		pUp = ax::Vec3::UNIT_Y;
	}

	mCameraBaseSet = true;
	mCameraBasePosition = pPosition;
	mCameraBaseForward = pForward;
	mCameraBaseUp = pUp;
}

void fsCNative3dScene::sceneTransformsApply(fsBool pDesktopFixedAspectActive)
{
	const ax::Mat4 sceneDisplayRootMatrix = pDesktopFixedAspectActive ? matrixIdentityGet() : mDisplayMatrix;
	mSceneDisplayRoot->setAdditionalTransform(static_cast<const ax::Mat4*>(nullptr));
	mSceneDisplayRoot->setNodeToParentTransform(sceneDisplayRootMatrix);
	mSceneRoot->setAdditionalTransform(static_cast<const ax::Mat4*>(nullptr));
	mSceneRoot->setNodeToParentTransform(mRenderMatrix);
	helperPathVisibilityApplyRecursive(mSceneRoot);
}

void fsCNative3dScene::cameraFixedAspectApply(const ax::Viewport& pLogicalViewport)
{
	if (!mWorldCamera || !mCameraBaseSet)
	{
		return;
	}

	// Keep the fixed-aspect camera aligned with the scene-root x transform.
	ax::Vec3 cameraPosition = mCameraBasePosition;
	ax::Vec3 cameraTarget = mCameraBasePosition + mCameraBaseForward * 100.0f;
	const ax::Vec3 cameraBaseTarget = cameraTarget;
	const ax::Vec3 cameraUp = mCameraBaseUp;
	const ax::Mat4 sceneTransform = mSceneRoot->getNodeToWorldTransform();
	ax::Vec3 transformedPosition = cameraPosition;
	ax::Vec3 transformedTarget = cameraTarget;
	sceneTransform.transformPoint(&transformedPosition);
	sceneTransform.transformPoint(&transformedTarget);
	const fsF32 visibleCanvasH = static_cast<fsF32>(fsIDisplay::instanceGet()->visibleCanvasHeightGet());
	fsF32 horizontalCorrectionWeight =
		visibleCanvasH > 0.0f ? pLogicalViewport.height / visibleCanvasH : 1.0f;
	if (mZoomScale > 0.0001f)
	{
		horizontalCorrectionWeight /= mZoomScale;
	}
	cameraPosition.x += (transformedPosition.x - cameraPosition.x) * horizontalCorrectionWeight;
	cameraTarget.x += (transformedTarget.x - cameraTarget.x) * horizontalCorrectionWeight;
	cameraPosition.y = mCameraBasePosition.y;
	cameraTarget.y = cameraBaseTarget.y;
	mWorldCamera->setPosition3D(cameraPosition);
	mWorldCamera->lookAt(cameraTarget, cameraUp);
}

axmol::Node* fsCNative3dScene::implGet() const
{
	return mScene;
}

fsCNative3dScene::fsCNative3dScene() :
fsINative(),
mScene(nullptr),
mWorldCamera(nullptr),
mSceneDisplayRoot(nullptr),
mExplicitCameraSet(false),
mCameraBaseSet(false),
mEyeBaseSet(false),
mCameraBasePosition(ax::Vec3::ZERO),
mCameraBaseForward(ax::Vec3(0.0f, 0.0f, -1.0f)),
mCameraBaseUp(ax::Vec3::UNIT_Y),
mSceneBaseTranslate(0.0f, 0.0f),
mScreenBaseTranslate(0.0f, 0.0f),
mEyeBaseZoomScale(1.0f),
mZoomScale(1.0f),
mCameraFov(60.0f),
mCameraNear(1.0f),
mCameraFar(1000.0f)
{
	mSceneDisplayRoot = axmol::Node::create();
	mSceneDisplayRoot->retain();

	mSceneRoot = axmol::Node::create();
    mSceneRoot->retain();

	mScene = axmol::Scene::create();
	mScene->retain();
	mScene->setCameraMask(static_cast<int>(eSCENE_FLAG::ALL_MODELS),true);

#if defined fsScreenTextureEffect	
#endif

	mScene->addChild(mSceneDisplayRoot);
	mSceneDisplayRoot->addChild(mSceneRoot);
	mDisplayMatrix = matrixIdentityGet();
	mEyeMatrix = matrixIdentityGet();
	mProjectionMatrix = matrixIdentityGet();
	mRenderMatrix = matrixIdentityGet();
	mSceneDisplayRoot->setNodeToParentTransform(matrixIdentityGet());
	mSceneRoot->setNodeToParentTransform(matrixIdentityGet());
	mScene->onEnter();
}

fsCNative3dScene::~fsCNative3dScene()
{
	std::for_each(std::begin(mLights), std::end(mLights), [&](auto light) {	ligthtRemove(light.get()); });

    if (mWorldCamera)
    {
        mWorldCamera->onExit();
//        mWorldCamera->release();
    }
	mScene->onExit();
	mScene->release();
}

#endif