Example #1
0
 public void Update(DoubleVector3 cameraLocation, DoubleVector3 planetLocation)
 {
     foreach (var face in _faces)
     {
         face.Update(cameraLocation, planetLocation);
     }
 }
Example #2
0
        // TODO: push this data in through the constructor, probably in a QuadMeshDefintion class, and make
        // this method private.  Except that would do real work in construction.  Hmmm.
        public void Initialize(double planetRadius, DoubleVector3 planeNormalVector, DoubleVector3 uVector, DoubleVector3 vVector, QuadNodeExtents extents, int level)
        {
            _planetRadius = planetRadius;
            _planeNormalVector = planeNormalVector;
            _uVector = uVector;
            _vVector = vVector;
            _extents = extents;
            _level = level;

            // TODO: get this from the QuadNode instead
            _locationRelativeToPlanet = (_planeNormalVector) + (_uVector * (_extents.North + (_extents.Width / 2.0))) + (_vVector * (_extents.West + (_extents.Width / 2.0)));
            _locationRelativeToPlanet = _locationRelativeToPlanet.ProjectUnitPlaneToUnitSphere() * _planetRadius;

            _meshStride = _extents.Width / (_gridSize - 1);

            // TODO: cover this in specs
            _boundingBox.Min = new Vector3(float.MaxValue);
            _boundingBox.Max = new Vector3(float.MinValue);

            GenerateIndices();
            GenerateMeshVertices();
            CollectMeshSamples();

            _renderer.Initialize(_vertices, _indices, _boundingBox);

            TrimUnneededMemory();
        }
Example #3
0
 public void Draw(DoubleVector3 cameraLocation, BoundingFrustum originBasedViewFrustum, Matrix originBasedViewMatrix, Matrix projectionMatrix)
 {
     foreach (var face in _faces)
     {
         face.Draw(cameraLocation, originBasedViewFrustum, originBasedViewMatrix, projectionMatrix);
     }
 }
Example #4
0
 public double GetGroundHeight(DoubleVector3 observerLocation)
 {
     // TODO: should probably delegate this responsibility to the terrain object
     // TODO: what about water?
     var planetUnitVector = DoubleVector3.Normalize(observerLocation - _location);
     var height = _generator.GetHeight(planetUnitVector, 19, 8000);
     return _radius + height;
 }
Example #5
0
 public void Draw(DoubleVector3 cameraLocation, BoundingFrustum originBasedViewFrustum, Matrix originBasedViewMatrix, Matrix projectionMatrix)
 {
     // TODO: better spec coverage here
     if (IsAboveHorizonToCamera && IsVisibleToCamera(cameraLocation, originBasedViewFrustum))
     {
         _renderer.Draw(_locationRelativeToPlanet, cameraLocation, originBasedViewMatrix, projectionMatrix);
     }
 }
Example #6
0
        public Planet(DoubleVector3 location, double radius, ITerrain terrain, IPlanetRenderer renderer, IHeightfieldGenerator generator, ISettings settings, Statistics statistics)
        {
            _location = location;
            _radius = radius;

            _terrain = terrain;
            _renderer = renderer;
            _generator = generator;
            _settings = settings;
            _statistics = statistics;
        }
Example #7
0
        public Planet(DoubleVector3 location, double radius, ITerrain terrain, IPlanetRenderer renderer, IHeightfieldGenerator generator, Statistics statistics)
        {
            _location = location;
            _radius = radius;

            _terrain = terrain;
            _renderer = renderer;
            _generator = generator;
            _statistics = statistics;

            _clippingPlanes = new ClippingPlanes();
        }
        public void StreamResourcesForBuiltInCamera(Camera streamingCamera)
        {
            m_nativePluginRunner.StreamResourcesForBuiltInCamera();

            // re-center the camera for ECEF
            if (m_coordinateSystem == CoordinateSystem.ECEF)
            {
                var mapSpaceCameraPosition = m_root.transform.InverseTransformPoint(streamingCamera.transform.position);
                m_originECEF += mapSpaceCameraPosition;
                streamingCamera.transform.position = m_root.transform.position;
            }
        }
        //--------------------//

        #region Perspective change
        /// <inheritdoc/>
        public override void PerspectiveChange(float panX, float panY, float rotation, float zoom)
        {
            double x = panX * Radius;
            double y = panY * Radius;

            Target += new DoubleVector3(
                Math.Sin(_horizontalRotation) * y - Math.Cos(_horizontalRotation) * x,
                0,
                Math.Sin(_horizontalRotation) * x + Math.Cos(_horizontalRotation) * y);

            Radius             *= zoom;
            HorizontalRotation += rotation;
        }
        public DoubleVector3 CalculateInterestPoint(Camera cameraECEF, DoubleVector3 cameraOriginECEF)
        {
            if (m_hasInterestPointFromNativeController)
            {
                m_hasInterestPointFromNativeController = false;
                return(m_interestPointECEF);
            }

            var cameraToMapSpaceMatrix = m_mapTransform.worldToLocalMatrix * cameraECEF.transform.localToWorldMatrix;
            var mapSpaceViewDirection  = cameraToMapSpaceMatrix.MultiplyVector(Vector3.forward);

            return(CalculateEstimatedInterestPoint(mapSpaceViewDirection, cameraECEF.nearClipPlane, cameraECEF.farClipPlane, cameraOriginECEF));
        }
Example #11
0
        public void Add(string id, DoubleVector3 originECEF, Vector3 translationOffsetECEF, Quaternion orientationECEF, GameObject rootGameObject)
        {
            if (Contains(id))
            {
                return; // :TODO: fix
            }

            var record = new GameObjectRecord {
                OriginECEF = originECEF, TranslationOffsetECEF = translationOffsetECEF, OrientationECEF = orientationECEF, RootGameObject = rootGameObject
            };

            m_gameObjectsById.Add(id, record);
        }
Example #12
0
        private DoubleVector3 ScaleInterestPointWithEnvironmentFlattening(DoubleVector3 interestPoint)
        {
            var environmentFlatteningScale = 1.0f;

            if (m_indoorMapsApi.GetActiveIndoorMap() == null)
            {
                environmentFlatteningScale = m_environmentFlatteningApi.GetCurrentScale();
            }

            var scaledPointEcef = DoubleVector3.Lerp(interestPoint.normalized * EarthConstants.Radius, interestPoint, environmentFlatteningScale);

            return(scaledPointEcef);
        }
Example #13
0
        public static bool ClampInterestPointToValidRangeIfRequired(ref DoubleVector3 interestPointEcef)
        {
            double magnitudeSquared = interestPointEcef.sqrMagnitude;

            if (magnitudeSquared > MaximumInterestPointAltitudeSquared)
            {
                interestPointEcef *= MaximumInterestPointAltitude / Math.Sqrt(magnitudeSquared);

                return(true);
            }

            return(false);
        }
Example #14
0
        public DoubleVector2 Project(DoubleVector3 input)
        {
            var p           = ToNumerics4(input);
            var cameraSpace = Vector4.Transform(p, worldToCamera);
//         return new DoubleVector2(width * (1.0 + cameraSpace.X / cameraSpace.Z) / 2.0, height * (1.0 + cameraSpace.Y / cameraSpace.Z) / 2.0);
            var viewSpace = Vector4.Transform(cameraSpace, cameraToView);

            viewSpace /= viewSpace.W; // I'm doing something wrong.
//         Console.WriteLine(p + " " + cameraSpace + " " + viewSpace + " " + (viewSpace / viewSpace.W));

            return(new DoubleVector2(width * (-viewSpace.X + 1.0) / 2.0, height * (-viewSpace.Y + 1.0) / 2.0));
//         return new DoubleVector2(viewSpace.X, viewSpace.Y);
        }
        public void Add(string id, DoubleVector3 originEcef, GameObject[] gameObjects)
        {
            if (Contains(id))
            {
                return; // :TODO: fix
            }

            var record = new GameObjectRecord {
                OriginECEF = originEcef, GameObjects = gameObjects
            };

            m_gameObjectsById.Add(id, record);
        }
        public DoubleVector3 GetPointEcefOnPolyline(DoubleVector3[] polylinePoints, double[] polylineParams, double t)
        {
            var polylineParamsGCHandle = GCHandle.Alloc(polylineParams, GCHandleType.Pinned);
            var polylineParamsPtr      = polylineParamsGCHandle.AddrOfPinnedObject();

            int    i0;
            int    i1;
            double s;

            NativeTransportApi_GetLinearInterpolationParams(NativePluginRunner.API, polylineParamsPtr, polylinePoints.Length, t, out i0, out i1, out s);

            polylineParamsGCHandle.Free();
            return(DoubleVector3.Lerp(polylinePoints[i0], polylinePoints[i1], s));
        }
Example #17
0
        private static PerspectiveProjector CreateCanvasProjector()
        {
            var rotation    = 95 * Math.PI / 180.0;
            var displaySize = new Size((int)(bounds.Width * renderScale), (int)(bounds.Height * renderScale));
            var center      = new DoubleVector3(0, 0, 0);
            var projector   = new PerspectiveProjector(
                center + DoubleVector3.FromRadiusAngleAroundXAxis(1000, rotation),
                center,
                DoubleVector3.FromRadiusAngleAroundXAxis(1, rotation - Math.PI / 2),
                displaySize.Width,
                displaySize.Height);

            return(projector);
        }
Example #18
0
        public void AddObjectsForMeshes(Mesh[] meshes, DoubleVector3 originECEF, string materialName)
        {
            var id = meshes[0].name;

            if (m_gameObjectRepository.Contains(id))
            {
                return;
            }

            var material    = m_materialRepository.LoadOrCreateMaterial(id, materialName);
            var gameObjects = m_gameObjectCreator.CreateGameObjects(meshes, material, m_collisions);

            m_gameObjectRepository.Add(id, originECEF, gameObjects);
        }
Example #19
0
 public void DrawPoint(DoubleVector3 point, StrokeStyle strokeStyle)
 {
     BatchDraw(() => {
         var p = Project(point);
         var x = (float)p.X;
         var y = (float)p.Y;
         var pointTransformed = Vector3.Transform(new Vector3((float)point.X, (float)point.Y, (float)point.Z), Transform).ToOpenMobaVector();
         var radius           = ProjectThickness(pointTransformed, strokeStyle.Thickness) / 2.0f;
         var rect             = new RectangleF(x - radius, y - radius, radius * 2, radius * 2);
         using (var brush = new SolidBrush(strokeStyle.Color)) {
             g.FillEllipse(brush, rect);
         }
     });
 }
        public void Draw(DoubleVector3 location, DoubleVector3 cameraLocation, Matrix originBasedViewMatrix, Matrix projectionMatrix)
        {
            // TODO: Calculate a dynamic scaling factor based on the distance of the object from the camera?  See
            // the Interactive Visualization paper, page 24.

            Matrix translationMatrix = Matrix.CreateTranslation(location - cameraLocation);
            Matrix worldMatrix = translationMatrix;

            _effect.View = originBasedViewMatrix;
            _effect.Projection = projectionMatrix;
            _effect.World = worldMatrix;

            _effect.VertexColorEnabled = true;
            _effect.PreferPerPixelLighting = true;

            _effect.FogEnabled = false;
            _effect.FogColor = new Vector3(0.5f, 0.5f, 0.6f);
            _effect.FogStart = 0f;
            _effect.FogEnd = 300000f;

            _effect.DirectionalLight0.DiffuseColor = Vector3.One;
            _effect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(1.0f, -1.0f, -1.0f));
            _effect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
            _effect.LightingEnabled = true;

            if (_settings.ShouldDrawWireframe)
            {
                if (_graphicsDevice.RasterizerState.FillMode != FillMode.WireFrame)
                {
                    _graphicsDevice.RasterizerState = new RasterizerState() { FillMode = FillMode.WireFrame };
                }
            }
            else
            {
                if (_graphicsDevice.RasterizerState.FillMode != FillMode.Solid)
                {
                    _graphicsDevice.RasterizerState = new RasterizerState() { FillMode = FillMode.Solid };
                }
            }

            _effect.CurrentTechnique.Passes[0].Apply();
            foreach (EffectPass pass in _effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                _graphicsDevice.Indices = _indexBuffer;
                _graphicsDevice.SetVertexBuffer(_vertexBuffer);
                _graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _numberOfVertices, 0, _numberOfIndices / 3);
            }
        }
Example #21
0
        public static Matrix GenerateOriginBasedViewMatrix(DoubleVector3 location, float yaw, float pitch, float roll)
        {
            Matrix yawMatrix   = Matrix.CreateRotationY(yaw);
            Matrix pitchMatrix = Matrix.CreateRotationX(pitch);
            Matrix rollMatrix  = Matrix.CreateRotationZ(roll);

            Vector3 rotation = Vector3.Transform(Vector3.Forward, pitchMatrix);

            rotation = Vector3.Transform(rotation, yawMatrix);
            Vector3 lookAt = rotation;
            Vector3 up     = Vector3.Transform(Vector3.UnitY, rollMatrix);

            return(Matrix.CreateLookAt(Vector3.Zero, lookAt, up));
        }
Example #22
0
 public DoubleVector3 MapToScreen(DoubleVector3 p)
 {
     switch (this.Orientation)
     {
         case TileControlOrientation.XY:
             return p;
         case TileControlOrientation.XZ:
             return new DoubleVector3(p.X, -p.Z, p.Y);
         case TileControlOrientation.ZY:
             return new DoubleVector3(p.Z, p.Y, p.X);
         default:
             throw new NotImplementedException();
     }
 }
Example #23
0
        public PerspectiveProjector(DoubleVector3 position, DoubleVector3 lookat, DoubleVector3 up, double width, double height)
        {
            this.position      = position;
            this.lookat        = lookat;
            this.up            = up;
            this.width         = width;
            this.height        = height;
            this.worldToCamera =
                Matrix4x4.CreateTranslation(ToNumerics3(-1.0 * position)) *
                Matrix4x4.CreateLookAt(ToNumerics3(DoubleVector3.Zero), ToNumerics3(position.To(lookat)), ToNumerics3(up)) *
                Matrix4x4.CreateScale(-1, 1, 1);
            this.cameraToView = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI * 2 / 4, (float)(width / height), 1f, 10000f);
//          this.cameraToView = Matrix4x4.CreatePerspectiveOffCenter(0, (float)width, (float)height, 0, 1.0f, 1000.0f);
            transform = cameraToView * worldToCamera;
        }
        public IPlanet Create(DoubleVector3 location, double radius)
        {
            // TODO: should we inject into the factory everything it will need to inject
            // into the planets?  That reduces calls to the container but makes an assumption
            // about dependency lifetimes.

            var terrain = _terrainFactory.Create(radius);
            var renderer = CreateRenderer(radius);
            var generator = ObjectFactory.GetInstance<IHeightfieldGenerator>();
            var statistics = ObjectFactory.GetInstance<Statistics>();

            var planet = new Planet(location, radius, terrain, renderer, generator, statistics);

            return planet;
        }
        private void SetCentralPoint(DoubleVector3 ecefOrigin, LatLongAltitude latLongAltOrigin)
        {
            m_originECEF = ecefOrigin;

            var upEcef      = m_originECEF.normalized;
            var northPole   = new DoubleVector3(0.0, 1.0, 0.0);
            var toNorthPole = (northPole - upEcef).normalized;

            m_upECEF      = upEcef.ToSingleVector();
            m_rightECEF   = -DoubleVector3.Cross(toNorthPole, upEcef).normalized.ToSingleVector();
            m_forwardECEF = -Vector3.Cross(m_upECEF, m_rightECEF);

            ECEFToLocalRotation = CreateQuaternionFromBasisVectors(m_rightECEF, m_upECEF, m_forwardECEF);
            LocalToECEFRotation = Quaternion.Inverse(ECEFToLocalRotation);
        }
Example #26
0
        /// <summary>
        /// Creates a new <see cref="WaterViewSource"/>
        /// </summary>
        /// <param name="height">The height of the <see cref="Water"/> planes (Y axis)</param>
        /// <param name="baseView">The <see cref="View"/> the <see cref="Water"/> planes are shown in</param>
        /// <param name="clipTolerance">How far to shift the clip plane along its normal vector to reduce graphical glitches at corners</param>
        private WaterViewSource(double height, View baseView, float clipTolerance)
        {
            Height        = height;
            BaseView      = baseView;
            ClipTolerance = clipTolerance;

            // Create child views
            var position = new DoubleVector3(0, height, 0);

            RefractedView = WaterView.CreateRefraction(baseView, new DoublePlane(position, -1 * UpVector), clipTolerance);
            ReflectedView = WaterView.CreateReflection(baseView, new DoublePlane(position, UpVector), clipTolerance);

            // Load shaders
            RefractionOnlyShader       = new WaterShader(RefractedView);
            RefractionReflectionShader = new WaterShader(RefractedView, ReflectedView);
        }
        public bool ContainsPoint(HoleInstanceMetadata instanceMetadata, DoubleVector3 pointWorld, double agentRadius)
        {
            var pointLocal3 = Vector3.Transform(pointWorld.ToDotNetVector(), instanceMetadata.WorldTransformInv);
            var pointLocal  = new IntVector2((int)pointLocal3.X, (int)pointLocal3.Y);

            if (!dilatedPunchResultByAgentRadius.TryGetValue(agentRadius, out var dilatedPunchedLand))
            {
                dilatedPunchedLand = PolygonOperations.Offset()
                                     .Include(punchResult.FlattenToPolygonAndIsHoles())
                                     .Dilate(agentRadius)
                                     .Execute();
                dilatedPunchResultByAgentRadius[agentRadius] = dilatedPunchedLand;
            }

            return(dilatedPunchedLand.PointInPolytree(pointLocal, out var _));
        }
        /// <summary>
        /// Update cached versions of <see cref="View"/> and related matrices.
        /// </summary>
        protected override void UpdateView()
        {
            // Only execute this if the view has changed
            if (!ViewDirty)
            {
                return;
            }

            // Keep radius within boundaries
            if (_radius < _minRadius)
            {
                _radius = _minRadius;
            }
            if (_radius > _maxRadius)
            {
                _radius = _maxRadius;
            }

            // Calculate variable vertical rotation based on current radius
            double vRotation = (_minAngle - _maxAngle) / (_minRadius - _maxRadius) * _radius +
                               _minAngle - (_minAngle - _maxAngle) / (_minRadius - _maxRadius) * _minRadius;

            while (vRotation > 2 * Math.PI)
            {
                vRotation -= 2 * Math.PI;
            }
            while (vRotation < 0)
            {
                vRotation += 2 * Math.PI;
            }

            // (radius * Math.Cos(vRotation)) is the temporary radius after the y component shift
            var newPosition = new DoubleVector3(
                _radius * Math.Cos(vRotation) * -Math.Sin(_horizontalRotation),
                _radius * Math.Sin(vRotation),
                _radius * Math.Cos(vRotation) * -Math.Cos(_horizontalRotation));

            // Translate these coordinates by the target object's spacial location
            PositionCached = newPosition + Target;

            // Prevent camera from going under terrain
            PositionCached.Y = Math.Max(PositionCached.Y, _heightController(PositionCached));

            base.UpdateView();

            ViewDirty = false;
        }
Example #29
0
        public GameObject[] AddObjectsForMeshes(string objectID, Mesh[] meshes, DoubleVector3 originECEF, Vector3 translationOffsetECEF, Quaternion rotationECEF, string materialName)
        {
            if (m_gameObjectRepository.Contains(objectID))
            {
                return(null);
            }

            var material = m_materialRepository.LoadOrCreateMaterial(objectID, materialName);
            var parent   = new GameObject(objectID);

            parent.transform.SetParent(m_gameObjectRepository.Root.transform, false);
            var gameObjects = m_gameObjectCreator.CreateGameObjects(meshes, material, parent.transform, m_collisions);

            m_gameObjectRepository.Add(objectID, originECEF, translationOffsetECEF, rotationECEF, parent);

            return(gameObjects);
        }
        public DoubleVector3 MapToScreen(DoubleVector3 p)
        {
            switch (this.Orientation)
            {
            case TileControlOrientation.XY:
                return(p);

            case TileControlOrientation.XZ:
                return(new DoubleVector3(p.X, -p.Z, p.Y));

            case TileControlOrientation.ZY:
                return(new DoubleVector3(p.Z, p.Y, p.X));

            default:
                throw new NotImplementedException();
            }
        }
        public DoubleVector3 ScreenToMap(DoubleVector3 v)
        {
            switch (this.Orientation)
            {
            case TileControlOrientation.XY:
                return(v);

            case TileControlOrientation.XZ:
                return(new DoubleVector3(v.X, v.Z, -v.Y));

            case TileControlOrientation.ZY:
                return(new DoubleVector3(v.Z, v.Y, v.X));

            default:
                throw new NotImplementedException();
            }
        }
Example #32
0
    public void AppendRealtimeWithDownSampling(double x, double y, double slideTime = 0f)
    {
        if (graph == null)
        {
            return;
        }
        bool show = false;

        if (mData.Count == 0)
        {
            show = true;
        }
        else
        {
            double viewX = mData[mData.Count - 1].x;
            double pageStartThreshold = currentPagePosition - mCurrentPageSizeFactor;
            double pageEndThreshold   = currentPagePosition + mCurrentPageSizeFactor - graph.DataSource.HorizontalViewSize;
            if (viewX >= pageStartThreshold && viewX <= pageEndThreshold)
            {
                show = true;
            }
        }
        var v = new DoubleVector2(x, y);

        mData.Add(v);
        if (show)
        {
            if (currentDownSampleCount >= RealtimeDownSampleCount)
            {
                RestartDownSampleCount();
                graph.DataSource.AddPointToCategoryRealtime(Category, x, y, slideTime);
            }
            DownSampleSum += v.ToDoubleVector3();
            currentDownSampleCount++;
            var avarage = DownSampleSum * 1.0 / (double)currentDownSampleCount;
            if (currentDownSampleCount != 1)
            {
                graph.DataSource.UpdateLastPointInCategoryRealtime(Category, avarage.x, avarage.y, slideTime);
            }
        }
        else
        {
            RestartDownSampleCount();
        }
    }
Example #33
0
        internal void CalculateCameraParameters(NativeCameraState nativeCameraState, out DoubleVector3 cameraPositionECEF, out DoubleVector3 interestPointECEF, out Vector3 cameraUpECEF)
        {
            var scaledInterestPoint = ScaleInterestPointWithEnvironmentFlattening(nativeCameraState.interestPointECEF);

            Vector3       forward, up;
            DoubleVector3 positionECEF;

            CameraHelpers.CalculateLookAt(
                scaledInterestPoint,
                nativeCameraState.interestBasisForwardECEF,
                nativeCameraState.pitchDegrees * Mathf.Deg2Rad,
                nativeCameraState.distanceToInterestPoint,
                out positionECEF, out forward, out up);

            interestPointECEF  = scaledInterestPoint;
            cameraPositionECEF = positionECEF;
            cameraUpECEF       = up;
        }
 public TransportPositionerPointOnGraph(
     bool isMatched,
     bool isWayReversed,
     TransportDirectedEdgeId directedEdgeId,
     double parameterizedPointOnWay,
     DoubleVector3 pointOnWay,
     DoubleVector3 directionOnWay,
     double headingOnWayDegrees
     )
 {
     IsMatched               = isMatched;
     IsWayReversed           = isWayReversed;
     DirectedEdgeId          = directedEdgeId;
     ParameterizedPointOnWay = parameterizedPointOnWay;
     PointOnWay              = pointOnWay;
     DirectionOnWay          = directionOnWay;
     HeadingOnWayDegrees     = headingOnWayDegrees;
 }
        // Ridged multifractal
        // See "Texturing & Modeling, A Procedural Approach", Chapter 12
        public double AccumulateNoise(DoubleVector3 sampleLocation, int numberOfOctaves, double lacunarity, double gain, double offset)
        {
            double sum = 0; // The return result
            double amp = 0.5; // Reduce the amplitude per octave of noise
            double prev = 1.0;

            for (int i = 0; i < numberOfOctaves; i++)
            {
                double n = ridge(_noiseGenerator.GetNoise(sampleLocation), offset);
                sum += n * amp * prev;
                prev = n;
                sampleLocation *= lacunarity;
                amp *= gain;
            }

            // Return the result
            return sum * 1.25 * 2 - 1;
        }
        public double GetHeight(DoubleVector3 location, int level, double scale)
        {
            var heightVariance1 = _varianceGenerator1.GetNoise(location, 5, 4, 2.0, 0.5);
            heightVariance1 = (heightVariance1 + 1);

            var heightVariance2 = _varianceGenerator2.GetNoise(location, 15, 4, 3.0, 0.5);
            heightVariance2 = (heightVariance2 + 1);

            var heightVariance = DoubleMathHelper.Clamp(heightVariance1 * heightVariance2, 0, 2);

            _sampleCount++;
            if (_sampleCount % 1000 == 0)
            {
                Debug.WriteLine(heightVariance);
            }

            var height = heightVariance * scale;
            return height;
        }
Example #37
0
        DoubleVector3 GetFleeVector(IEnumerable <ILivingObject> enemies)
        {
            var fleeVector = enemies.Aggregate(new DoubleVector3(),
                                               (accu, enemy) =>
            {
                var v = new DoubleVector3(this.Worker.Location - enemy.Location);

                // XXX if null vector, flee up. (which probably leads to fleeing in some parallel direction).
                if (v.IsNull)
                {
                    return(accu + new DoubleVector3(0, 0, 1));
                }

                v = v * 100 / v.SquaredLength;
                return(accu + v);
            });

            return(fleeVector);
        }
Example #38
0
 /// <summary>
 /// Adds a new particle
 /// </summary>
 /// <param name="position">The initial position of the particle</param>
 /// <param name="parameters1">The initial configuration of this particle</param>
 /// <param name="parameters2">The configuration this particle will take in its "second life"</param>
 private void AddParticle(DoubleVector3 position, CpuParticleParametersStruct parameters1, CpuParticleParametersStruct parameters2)
 {
     if (_deadParticles.Count > 0)
     {
         CpuParticle particle = _deadParticles.Pop();
         particle.Alive       = true;
         particle.Position    = position;
         particle.Velocity    = default(Vector3);
         particle.Parameters1 = parameters1;
         particle.Parameters2 = parameters2;
         particle.Color       = parameters1.Color;
         particle.SecondLife  = false;
         _firstLifeParticles.Add(particle);
     }
     else
     {
         _firstLifeParticles.Add(new CpuParticle(position, parameters1, parameters2));
     }
 }
Example #39
0
        public bool TryFetchECEFLocationForPositioner(Positioner positioner, out DoubleVector3 positionerECEFLocation)
        {
            DoubleVector3Interop positionerECEFLocationInterop = new DoubleVector3Interop();

            var success = NativePositionerApi_TryFetchECEFLocationForPositioner(NativePluginRunner.API, positioner.Id, ref positionerECEFLocationInterop);

            if (success)
            {
                positionerECEFLocation.x = positionerECEFLocationInterop.x;
                positionerECEFLocation.y = positionerECEFLocationInterop.y;
                positionerECEFLocation.z = positionerECEFLocationInterop.z;

                return(true);
            }

            positionerECEFLocation = DoubleVector3.zero;

            return(false);
        }
        internal static void OnHighlightMeshUpload(IntPtr highlightIdPtr, ulong meshId, int highlightRequestId, IntPtr highlightPtr)
        {
            string highlightIdString = Marshal.PtrToStringAnsi(highlightIdPtr);

            HighlightInterop highlight       = MarshalHighlightInterop(highlightPtr);
            string           highlightMeshId = GetHighlightGameObjectId(highlightIdString, meshId);
            Mesh             mesh            = CreateHighlightMesh(highlightMeshId, highlight);

            var originEcef = new DoubleVector3(highlight.OriginEcefX, highlight.OriginEcefY, highlight.OriginEcefZ);

            HighlightStreamer.AddObjectsForMeshes(new Mesh[] { mesh }, originEcef, "highlight");

            var request = HighlightRequests[highlightRequestId];

            HighlightIdsToAdd.Add(highlightMeshId);
            var gameObject = HighlightStreamer.GetObjects(highlightMeshId)[0];

            gameObject.GetComponent <MeshRenderer>().sharedMaterial = request.material;
        }
        public void Draw(DoubleVector3 location, DoubleVector3 cameraLocation, Matrix originBasedViewMatrix, Matrix projectionMatrix)
        {
            _effect.View = originBasedViewMatrix;
            _effect.Projection = projectionMatrix;
            _effect.World = GetWorldMatrix(location, cameraLocation);

            // TODO: we shouldn't have to set all of these every time - could be optimized
            SetLightingEffects();
            SetFogEffects();
            SetFillMode();

            DrawMesh();
            if (_settings.ShouldDrawMeshBoundingBoxes)
            {
                DrawBoundingBox();
            }

            _statistics.NumberOfQuadMeshesRendered++;
        }
Example #42
0
    // Update is called once per frame
    void Update()
    {
        if (graph == null) // no graph attached to this script for some reason
        {
            return;
        }
        Vector2 mousePos = Input.mousePosition;
        double  mouseX, mouseY;

        graph.PointToClient(mousePos, out mouseX, out mouseY);
        if (CompareWithError(mousePos, mZoomBasePosition) == false) // the mouse has moved beyond the erroo
        {
            mZoomBasePosition = mousePos;
            graph.PointToClient(mousePos, out mouseX, out mouseY);
            mZoomBaseChartSpace = new DoubleVector3(mouseX, mouseY);
            ResetZoomAnchor();
        }
        else
        {
            mousePos = mZoomBasePosition;
        }

        float delta = Input.mouseScrollDelta.y;

        totalZoom += delta;    //accumilate the delta change for the currnet positions

        if (delta != 0 && graph.PointToClient(mousePos, out mouseX, out mouseY))
        {
            DoubleVector3 ViewCenter = InitialOrigin + InitalScrolling;
            DoubleVector3 trans      = new DoubleVector3((mZoomBaseChartSpace.x - ViewCenter.x), (mZoomBaseChartSpace.y - ViewCenter.y));
            float         growFactor = Mathf.Pow(2, totalZoom / ZoomSpeed);
            double        hSize      = InitalViewSize.x * growFactor;
            double        vSize      = InitalViewSize.y * growFactor;
            if (hSize < MaxViewSize && hSize > MinViewSize && vSize < MaxViewSize && vSize > MinViewSize)
            {
                graph.HorizontalScrolling           = InitalScrolling.x + trans.x - (trans.x * growFactor);
                graph.VerticalScrolling             = InitalScrolling.y + trans.y - (trans.y * growFactor);
                graph.DataSource.HorizontalViewSize = hSize;
                graph.DataSource.VerticalViewSize   = vSize;
            }
        }
    }
Example #43
0
 public void Draw(DoubleVector3 cameraLocation, BoundingFrustum originBasedViewFrustum, Matrix originBasedViewMatrix, Matrix projectionMatrix)
 {
     if (_hasSubnodes)
     {
         // TODO: we'd like to stop traversing into subnodes if this node's mesh isn't visibile, but our
         // horizon culling algorithm isn't that great right now and the primary faces are so large that
         // sometimes all of their sample points are below the horizon even though we're above that face
         // and would want to draw its children.  For now, we'll scan all subnodes regardless.  The child
         // node's meshes will do visibility culling on an individual basis.
         foreach (var subnode in _subnodes)
         {
             subnode.Draw(cameraLocation, originBasedViewFrustum, originBasedViewMatrix, projectionMatrix);
         }
     }
     else
     {
         _renderer.Draw(_locationRelativeToPlanet, cameraLocation, originBasedViewMatrix, projectionMatrix);
         _mesh.Draw(cameraLocation, originBasedViewFrustum, originBasedViewMatrix, projectionMatrix);
     }
 }
Example #44
0
        public void Draw(DoubleVector3 cameraLocation, Matrix originBasedViewMatrix, Matrix projectionMatrix)
        {
            if (!_mesh.IsVisibleToCamera)
            {
                return;
            }

            if (_hasSubnodes)
            {
                foreach (var subnode in _subnodes)
                {
                    subnode.Draw(cameraLocation, originBasedViewMatrix, projectionMatrix);
                }
            }
            else
            {
                _renderer.Draw(_locationRelativeToPlanet, cameraLocation, originBasedViewMatrix, projectionMatrix);
                _mesh.Draw(cameraLocation, originBasedViewMatrix, projectionMatrix);
            }
        }
        public double GetNoise(DoubleVector3 location)
        {
            // Taken from Interactive Visualization paper

            uint xHash = (uint)location.X.GetHashCode();
            uint yHash = (uint)location.Y.GetHashCode();
            uint zHash = (uint)location.Z.GetHashCode();

            uint result = GetFromPool(0);
            while (xHash > 0 || yHash > 0 || zHash > 0)
            {
                result += GetFromPool(xHash + GetFromPool(yHash + GetFromPool(zHash)));

                xHash >>= 16;
                yHash >>= 16;
                zHash >>= 16;
            }

            return (result % _poolSize) / (double)(_poolSize / 2) - 1.0;
        }
Example #46
0
        public static void CalculateLookAt(
            DoubleVector3 interestPointEcef,
            Vector3 interestBasisFoward,
            float pitchRadians,
            float distanceCameraToInterest,
            out DoubleVector3 cameraLocation,
            out Vector3 cameraDirection,
            out Vector3 cameraUp)
        {
            var interestBasis = new EcefTangentBasis(interestPointEcef, interestBasisFoward);

            var q = Quaternion.AngleAxis(pitchRadians * Mathf.Rad2Deg, interestBasis.Right);

            cameraDirection = q.RotatePoint(interestBasis.Forward);

            var toCamera = -cameraDirection * distanceCameraToInterest;

            cameraLocation = interestBasis.PointEcef + new DoubleVector3(toCamera.x, toCamera.y, toCamera.z);
            cameraUp       = Vector3.Cross(cameraDirection, interestBasis.Right);
        }
        double AccumulateNoise(DoubleVector3 location, int numberOfOctaves, double lacunarity, double gain)
        {
            double noiseSum = 0;
            double amplitude = 1;
            double amplitudeSum = 0;

            DoubleVector3 sampleLocation = location;

            for (int x = 0; x < numberOfOctaves; x++)
            {
                noiseSum += amplitude * _noiseGenerator.GetNoise(sampleLocation);
                amplitudeSum += amplitude;

                amplitude *= gain;
                sampleLocation *= lacunarity;
            }

            noiseSum /= amplitudeSum;

            return noiseSum * 1.35;
        }
        double AccumulateNoise(DoubleVector3 location, int numberOfOctaves, double lacunarity, double gain)
        {
            double weight = 1;
            double noise = 0;
            double amplitude = 1;

            for (int x = 0; x < numberOfOctaves; x++)
            {
                double signal = _noiseGenerator.GetNoise(location);
                signal = 1 - Math.Abs(signal);
                signal *= signal * weight;

                weight = signal / gain;
                weight = DoubleMathHelper.Clamp(weight, 0, 1);

                noise += (signal * amplitude);

                location *= lacunarity;
                amplitude *= gain;
            }

            return (noise * 1.25) - 1.0; ;
        }
Example #49
0
 public void MoveRight(double distance)
 {
     var translationVector = new DoubleVector3((distance * Math.Sin(_cameraYaw + (Math.PI / 2))), 0.0, (distance * Math.Cos(_cameraYaw + (Math.PI / 2))));
     _cameraLocation += translationVector;
     CreateViewMatrix();
 }
Example #50
0
 bool IsStraightUp(DoubleVector3 vector)
 {
     return (vector.X == 0 && vector.Z == 0 && vector.Y > 0);
 }
Example #51
0
        MeshDistance GetDistanceFrom(DoubleVector3 location)
        {
            double closestDistanceSquared = double.MaxValue;
            double furthestDistanceSquared = double.MinValue;
            DoubleVector3 closestVertex = _vertexSamples[0];
            DoubleVector3 furthestVertex = _vertexSamples[0];

            foreach (var vertex in _vertexSamples)
            {
                var distanceSquared = DoubleVector3.DistanceSquared(location, vertex);
                if (distanceSquared < closestDistanceSquared)
                {
                    closestDistanceSquared = distanceSquared;
                    closestVertex = vertex;
                }
                if (distanceSquared > furthestDistanceSquared)
                {
                    furthestDistanceSquared = distanceSquared;
                    furthestVertex = vertex;
                }
            }

            // TODO: We're spamming the garbage collector with this.  Allocate one instance per mesh and reuse.
            return new MeshDistance()
            {
                ClosestDistance = Math.Sqrt(closestDistanceSquared),
                ClosestVertex = closestVertex,
                FurthestDistance = Math.Sqrt(furthestDistanceSquared),
                FurthestVertex = furthestVertex
            };
        }
Example #52
0
 Matrix CreateOriginBasedLookAt(DoubleVector3 location, DoubleVector3 lookAt)
 {
     Matrix rotationMatrix = Matrix.CreateLookAt(Vector3.Zero, lookAt - location, Vector3.Up);
     return rotationMatrix;
 }
Example #53
0
 bool IsStraightDown(DoubleVector3 vector)
 {
     return (vector.X == 0 && vector.Z == 0 && vector.Y < 0);
 }
Example #54
0
        public void SetViewParameters(DoubleVector3 location, float yaw, float pitch, float roll)
        {
            _cameraLocation = location;
            _cameraYaw = yaw;
            _cameraPitch = pitch;
            _cameraRoll = roll;

            CreateViewMatrix();
        }
Example #55
0
        public void SetViewParameters(DoubleVector3 location, DoubleVector3 lookAt)
        {
            _cameraLocation = location;

            // To convert from a look-at vector to Euler angles, we'll go
            // via a rotation matrix.  There may be a shorter way, but
            // this works.

            Matrix rotationMatrix = CreateOriginBasedLookAt(location, lookAt);
            DoubleVector3 lookDirection = lookAt - location;

            if (IsStraightUp(lookDirection))
            {
                // singularity at north pole
                _cameraYaw = (float)Math.Atan2(rotationMatrix.M13, rotationMatrix.M33);
                _cameraPitch = MaximumPitch;
                _cameraRoll = 0;
            }
            else if (IsStraightDown(lookDirection))
            {
                // singularity at south pole
                _cameraYaw = (float)Math.Atan2(rotationMatrix.M13, rotationMatrix.M33);
                _cameraPitch = MinimumPitch;
                _cameraRoll = 0;
            }
            else
            {
                // Normal conversion
                _cameraYaw = (float)Math.Atan2(-rotationMatrix.M31, rotationMatrix.M11);
                _cameraPitch = (float)Math.Atan2(-rotationMatrix.M23, rotationMatrix.M22);
                _cameraRoll = (float)Math.Asin(rotationMatrix.M21);
            }

            ClampPitch();

            CreateViewMatrix();
        }
Example #56
0
        // TODO: push this data in through the constructor, probably in a QuadMeshDefintion class, and make
        // this method private.  Except that would do real work in construction.  Hmmm.
        public void Initialize(double planetRadius, DoubleVector3 planeNormalVector, DoubleVector3 uVector, DoubleVector3 vVector, QuadNodeExtents extents, int level)
        {
            _planetRadius = planetRadius;
            _planeNormalVector = planeNormalVector;
            _uVector = uVector;
            _vVector = vVector;
            _extents = extents;
            _level = level;

            _locationRelativeToPlanet = (_planeNormalVector) + (_uVector * ((_extents.West + (_extents.Width / 2.0)))) + (_vVector * ((_extents.North + (_extents.Width / 2.0))));
            _locationRelativeToPlanet = _locationRelativeToPlanet.ProjectUnitPlaneToUnitSphere() * _planetRadius;

            _meshStride = _extents.Width / (_gridSize - 1);

            GenerateMeshVertices();
            CollectMeshSamples();

            _renderer.Initialize(_vertices, _indices);
        }
 public double GetNoise(DoubleVector3 location)
 {
     return 1 - Math.Abs(_sourceGenerator.GetNoise(location));
 }
Example #58
0
 public void MoveForwardHorizontally(double distance)
 {
     distance = -distance;
     var translationVector = new DoubleVector3((distance * Math.Sin(_cameraYaw)), 0.0, (distance * Math.Cos(_cameraYaw)));
     _cameraLocation += translationVector;
     CreateViewMatrix();
 }
Example #59
0
 public void Draw(DoubleVector3 cameraLocation, Matrix originBasedViewMatrix, Matrix projectionMatrix)
 {
     _renderer.Draw(_locationRelativeToPlanet, cameraLocation, originBasedViewMatrix, projectionMatrix);
 }
Example #60
0
 public void MoveUp(double distance)
 {
     var translationVector = new DoubleVector3(0.0, distance, 0.0);
     _cameraLocation += translationVector;
     CreateViewMatrix();
 }