├── PSAR ├── psar.py └── table.csv ├── README.md ├── ZeroMQ_Protobuf_PublishSubscribe ├── CSharpPublisher │ ├── CSPublish.csproj │ ├── CSPublish.sln │ ├── Program.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── TimestampData.cs │ └── app.config └── PythonSubscriber │ ├── PySubscribe.py │ ├── TimestampData.proto │ └── TimestampData_pb2.py ├── ZeroMQ_StringPublishSubscribe ├── CSharpStringPublisher.sln ├── CSharpStringPublisher │ ├── App.config │ ├── CSharpStringPublisher.csproj │ ├── Program.cs │ └── Properties │ │ └── AssemblyInfo.cs └── PythonStringSubscriber.py └── javascript3D ├── CrazyBox ├── OrbitControls.js ├── crazybox.html ├── crazybox.js └── three.min.js └── Rosenbrock ├── rosenbrock.html ├── rosenbrock.js └── three.min.js /PSAR/psar.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | http://virtualizedfrog.wordpress.com/ 2014 5 | 6 | 7 | Translated from http://www.amibroker.com/library/detail.php?id=268 8 | Requires pandas to load csv files, and matplotlib to chart the data 9 | 10 | The main expects table.csv file. Valid files can be downloaded on Yahoo Finance 11 | eg: http://real-chart.finance.yahoo.com/table.csv?s=%5EGSPC&ignore=.csv 12 | """ 13 | 14 | import pandas as pd 15 | from datetime import datetime 16 | import matplotlib.pyplot as plt 17 | 18 | def psar(barsdata, iaf = 0.02, maxaf = 0.2): 19 | length = len(barsdata) 20 | dates = list(barsdata['Date']) 21 | high = list(barsdata['High']) 22 | low = list(barsdata['Low']) 23 | close = list(barsdata['Close']) 24 | psar = close[0:len(close)] 25 | psarbull = [None] * length 26 | psarbear = [None] * length 27 | bull = True 28 | af = iaf 29 | ep = low[0] 30 | hp = high[0] 31 | lp = low[0] 32 | 33 | for i in range(2,length): 34 | if bull: 35 | psar[i] = psar[i - 1] + af * (hp - psar[i - 1]) 36 | else: 37 | psar[i] = psar[i - 1] + af * (lp - psar[i - 1]) 38 | 39 | reverse = False 40 | 41 | if bull: 42 | if low[i] < psar[i]: 43 | bull = False 44 | reverse = True 45 | psar[i] = hp 46 | lp = low[i] 47 | af = iaf 48 | else: 49 | if high[i] > psar[i]: 50 | bull = True 51 | reverse = True 52 | psar[i] = lp 53 | hp = high[i] 54 | af = iaf 55 | 56 | if not reverse: 57 | if bull: 58 | if high[i] > hp: 59 | hp = high[i] 60 | af = min(af + iaf, maxaf) 61 | if low[i - 1] < psar[i]: 62 | psar[i] = low[i - 1] 63 | if low[i - 2] < psar[i]: 64 | psar[i] = low[i - 2] 65 | else: 66 | if low[i] < lp: 67 | lp = low[i] 68 | af = min(af + iaf, maxaf) 69 | if high[i - 1] > psar[i]: 70 | psar[i] = high[i - 1] 71 | if high[i - 2] > psar[i]: 72 | psar[i] = high[i - 2] 73 | 74 | if bull: 75 | psarbull[i] = psar[i] 76 | else: 77 | psarbear[i] = psar[i] 78 | 79 | return {"dates":dates, "high":high, "low":low, "close":close, "psar":psar, "psarbear":psarbear, "psarbull":psarbull} 80 | 81 | if __name__ == "__main__": 82 | import sys 83 | import os 84 | 85 | if len(sys.argv) < 2: 86 | sys.exit("Usage: %s datafile.csv" % sys.argv[0]) 87 | if not os.path.exists(sys.argv[1]): 88 | sys.exit("Error: can't open file '%s': No such file" % sys.argv[1]) 89 | 90 | barsdata = pd.read_csv(sys.argv[1]) 91 | #Reindex the data: ascending dates are expected in the function 92 | barsdata = barsdata.reindex(index=barsdata.index[::-1]) 93 | #Convert strings to actual timestamps 94 | barsdata['Date'] = [datetime.strptime(x, '%Y-%m-%d') for x in barsdata['Date']] 95 | 96 | startidx = 0 97 | endidx = len(barsdata) 98 | 99 | result = psar(barsdata) 100 | dates = result['dates'][startidx:endidx] 101 | close = result['close'][startidx:endidx] 102 | psarbear = result['psarbear'][startidx:endidx] 103 | psarbull = result['psarbull'][startidx:endidx] 104 | 105 | plt.plot(dates, close) 106 | plt.plot(dates, psarbull) 107 | plt.plot(dates, psarbear) 108 | plt.grid() 109 | plt.show() 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | blog_code 2 | ========= 3 | Blog Related Code: see virtualizedfrog.wordpress.com 4 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/CSharpPublisher/CSPublish.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | x86 6 | 8.0.30703 7 | 2.0 8 | {6CB059FB-3230-4944-9B73-625CF9BB35F7} 9 | Exe 10 | Properties 11 | CSPublish 12 | CSPublish 13 | v4.5 14 | 15 | 16 | 512 17 | 18 | 19 | x86 20 | true 21 | full 22 | false 23 | bin\Debug\ 24 | DEBUG;TRACE 25 | prompt 26 | 4 27 | false 28 | 29 | 30 | x86 31 | pdbonly 32 | true 33 | bin\Release\ 34 | TRACE 35 | prompt 36 | 4 37 | false 38 | 39 | 40 | 41 | ..\..\..\clrzmq\clrzmq.dll 42 | 43 | 44 | ..\..\..\Protobuf-net-test\Protobuf-net-test\bin\Debug\protobuf-net.dll 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 70 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/CSharpPublisher/CSPublish.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSPublish", "CSPublish.csproj", "{6CB059FB-3230-4944-9B73-625CF9BB35F7}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|x86 = Debug|x86 9 | Release|x86 = Release|x86 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {6CB059FB-3230-4944-9B73-625CF9BB35F7}.Debug|x86.ActiveCfg = Debug|x86 13 | {6CB059FB-3230-4944-9B73-625CF9BB35F7}.Debug|x86.Build.0 = Debug|x86 14 | {6CB059FB-3230-4944-9B73-625CF9BB35F7}.Release|x86.ActiveCfg = Release|x86 15 | {6CB059FB-3230-4944-9B73-625CF9BB35F7}.Release|x86.Build.0 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/CSharpPublisher/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | 6 | using ZeroMQ; 7 | using ProtoBuf; 8 | 9 | namespace CSPublish 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | bool publish = true; 16 | Task.Run(async () => 17 | { 18 | Random random = new Random(); 19 | using (var context = ZmqContext.Create()) 20 | { 21 | using (var socket = context.CreateSocket(SocketType.PUB)) 22 | { 23 | socket.Bind("tcp://127.0.0.1:5000"); 24 | using (var stream = new MemoryStream()) 25 | { 26 | while (publish) 27 | { 28 | var data = new TimestampData 29 | { 30 | Timestamp = DateTime.Now.Ticks, 31 | Key = "SYM", 32 | Data = random.NextDouble() 33 | }; 34 | 35 | Serializer.Serialize(stream, data); 36 | byte[] bytes = stream.ToArray(); 37 | socket.Send(bytes); 38 | 39 | stream.SetLength(0); 40 | await Task.Delay(1); 41 | } 42 | } 43 | } 44 | } 45 | }); 46 | Console.ReadLine(); 47 | publish = false; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/CSharpPublisher/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSPublish")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSPublish")] 13 | [assembly: AssemblyCopyright("Copyright © VirtualizedFrog 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("6542b1e9-5b94-4b02-bc9e-ca6bc6b27ef8")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/CSharpPublisher/TimestampData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ProtoBuf; 3 | 4 | namespace CSPublish 5 | { 6 | [ProtoContract] 7 | class TimestampData 8 | { 9 | [ProtoMember(1)] 10 | public Int64 Timestamp { get; set; } 11 | [ProtoMember(2)] 12 | public string Key { get; set; } 13 | [ProtoMember(3)] 14 | public double Data { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/CSharpPublisher/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/PythonSubscriber/PySubscribe.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | import zmq 5 | import datetime 6 | import TimestampData_pb2 7 | 8 | context = zmq.Context() 9 | socket = context.socket(zmq.SUB) 10 | socket.connect("tcp://127.0.0.1:5000") 11 | socket.setsockopt(zmq.SUBSCRIBE, "") 12 | 13 | while True: 14 | rawdata = socket.recv() 15 | data = TimestampData_pb2.TimestampData() 16 | data.ParseFromString(rawdata) 17 | print datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds = data.Timestamp / 10), data.Key, data.Data 18 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/PythonSubscriber/TimestampData.proto: -------------------------------------------------------------------------------- 1 | package pysub; 2 | 3 | message TimestampData { 4 | required int64 Timestamp = 1; 5 | required string Key = 2; 6 | required double Data = 3; 7 | } 8 | -------------------------------------------------------------------------------- /ZeroMQ_Protobuf_PublishSubscribe/PythonSubscriber/TimestampData_pb2.py: -------------------------------------------------------------------------------- 1 | # Generated by the protocol buffer compiler. DO NOT EDIT! 2 | # source: TimestampData.proto 3 | 4 | from google.protobuf import descriptor as _descriptor 5 | from google.protobuf import message as _message 6 | from google.protobuf import reflection as _reflection 7 | from google.protobuf import descriptor_pb2 8 | # @@protoc_insertion_point(imports) 9 | 10 | 11 | 12 | 13 | DESCRIPTOR = _descriptor.FileDescriptor( 14 | name='TimestampData.proto', 15 | package='pysub', 16 | serialized_pb='\n\x13TimestampData.proto\x12\x05pysub\"=\n\rTimestampData\x12\x11\n\tTimestamp\x18\x01 \x02(\x03\x12\x0b\n\x03Key\x18\x02 \x02(\t\x12\x0c\n\x04\x44\x61ta\x18\x03 \x02(\x01') 17 | 18 | 19 | 20 | 21 | _TIMESTAMPDATA = _descriptor.Descriptor( 22 | name='TimestampData', 23 | full_name='pysub.TimestampData', 24 | filename=None, 25 | file=DESCRIPTOR, 26 | containing_type=None, 27 | fields=[ 28 | _descriptor.FieldDescriptor( 29 | name='Timestamp', full_name='pysub.TimestampData.Timestamp', index=0, 30 | number=1, type=3, cpp_type=2, label=2, 31 | has_default_value=False, default_value=0, 32 | message_type=None, enum_type=None, containing_type=None, 33 | is_extension=False, extension_scope=None, 34 | options=None), 35 | _descriptor.FieldDescriptor( 36 | name='Key', full_name='pysub.TimestampData.Key', index=1, 37 | number=2, type=9, cpp_type=9, label=2, 38 | has_default_value=False, default_value=unicode("", "utf-8"), 39 | message_type=None, enum_type=None, containing_type=None, 40 | is_extension=False, extension_scope=None, 41 | options=None), 42 | _descriptor.FieldDescriptor( 43 | name='Data', full_name='pysub.TimestampData.Data', index=2, 44 | number=3, type=1, cpp_type=5, label=2, 45 | has_default_value=False, default_value=0, 46 | message_type=None, enum_type=None, containing_type=None, 47 | is_extension=False, extension_scope=None, 48 | options=None), 49 | ], 50 | extensions=[ 51 | ], 52 | nested_types=[], 53 | enum_types=[ 54 | ], 55 | options=None, 56 | is_extendable=False, 57 | extension_ranges=[], 58 | serialized_start=30, 59 | serialized_end=91, 60 | ) 61 | 62 | DESCRIPTOR.message_types_by_name['TimestampData'] = _TIMESTAMPDATA 63 | 64 | class TimestampData(_message.Message): 65 | __metaclass__ = _reflection.GeneratedProtocolMessageType 66 | DESCRIPTOR = _TIMESTAMPDATA 67 | 68 | # @@protoc_insertion_point(class_scope:pysub.TimestampData) 69 | 70 | 71 | # @@protoc_insertion_point(module_scope) 72 | -------------------------------------------------------------------------------- /ZeroMQ_StringPublishSubscribe/CSharpStringPublisher.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Express 2013 for Windows Desktop 4 | VisualStudioVersion = 12.0.21005.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpStringPublisher", "CSharpStringPublisher\CSharpStringPublisher.csproj", "{A9B62A70-2B31-4F9C-820F-A18CEB38F79F}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {A9B62A70-2B31-4F9C-820F-A18CEB38F79F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {A9B62A70-2B31-4F9C-820F-A18CEB38F79F}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {A9B62A70-2B31-4F9C-820F-A18CEB38F79F}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {A9B62A70-2B31-4F9C-820F-A18CEB38F79F}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /ZeroMQ_StringPublishSubscribe/CSharpStringPublisher/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ZeroMQ_StringPublishSubscribe/CSharpStringPublisher/CSharpStringPublisher.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {A9B62A70-2B31-4F9C-820F-A18CEB38F79F} 8 | Exe 9 | Properties 10 | CSharpStringPublisher 11 | CSharpStringPublisher 12 | v4.5 13 | 512 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\..\..\..\..\..\..\Program Files\libs\clrzmq\clrzmq.dll 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 61 | -------------------------------------------------------------------------------- /ZeroMQ_StringPublishSubscribe/CSharpStringPublisher/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using System.Text; 6 | using ZeroMQ; 7 | 8 | namespace CSharpStringPublisher 9 | { 10 | class Program 11 | { 12 | private static ZmqContext context_ = null; 13 | private static ZmqSocket socket_ = null; 14 | 15 | static void Main(string[] args) 16 | { 17 | context_ = ZmqContext.Create(); 18 | socket_ = context_.CreateSocket(SocketType.PUB); 19 | socket_.Bind("tcp://127.0.0.1:5000"); 20 | 21 | bool publish = true; 22 | Task.Run(() => { 23 | while (publish) 24 | { 25 | string timestring = DateTime.Now.ToString("u"); 26 | Console.WriteLine("Sending '{0}' to subscribers", timestring); 27 | socket_.Send(timestring, Encoding.Unicode); 28 | Thread.Sleep(1000); 29 | } 30 | }); 31 | Console.ReadLine(); 32 | publish = false; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ZeroMQ_StringPublishSubscribe/CSharpStringPublisher/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharpStringPublisher")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharpStringPublisher")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("514da02f-31f8-4813-a793-914d27c6018d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /ZeroMQ_StringPublishSubscribe/PythonStringSubscriber.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import zmq 4 | 5 | context = zmq.Context() 6 | socket = context.socket(zmq.SUB) 7 | 8 | socket.setsockopt(zmq.SUBSCRIBE, "") 9 | socket.connect("tcp://127.0.0.1:5000") 10 | 11 | while True: 12 | timestring = socket.recv_string() 13 | print timestring -------------------------------------------------------------------------------- /javascript3D/CrazyBox/OrbitControls.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author qiao / https://github.com/qiao 3 | * @author mrdoob / http://mrdoob.com 4 | * @author alteredq / http://alteredqualia.com/ 5 | * @author WestLangley / https://github.com/WestLangley 6 | */ 7 | 8 | THREE.OrbitControls = function ( object, domElement ) { 9 | 10 | THREE.EventDispatcher.call( this ); 11 | 12 | this.object = object; 13 | this.domElement = ( domElement !== undefined ) ? domElement : document; 14 | 15 | // API 16 | 17 | this.center = new THREE.Vector3(); 18 | 19 | this.userZoom = true; 20 | this.userZoomSpeed = 1.0; 21 | 22 | this.userRotate = true; 23 | this.userRotateSpeed = 1.0; 24 | 25 | this.autoRotate = false; 26 | this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 27 | 28 | this.minPolarAngle = 0; // radians 29 | this.maxPolarAngle = Math.PI; // radians 30 | 31 | this.minDistance = 0; 32 | this.maxDistance = Infinity; 33 | 34 | // internals 35 | 36 | var scope = this; 37 | 38 | var EPS = 0.000001; 39 | var PIXELS_PER_ROUND = 1800; 40 | 41 | var rotateStart = new THREE.Vector2(); 42 | var rotateEnd = new THREE.Vector2(); 43 | var rotateDelta = new THREE.Vector2(); 44 | 45 | var zoomStart = new THREE.Vector2(); 46 | var zoomEnd = new THREE.Vector2(); 47 | var zoomDelta = new THREE.Vector2(); 48 | 49 | var phiDelta = 0; 50 | var thetaDelta = 0; 51 | var scale = 1; 52 | 53 | var lastPosition = new THREE.Vector3(); 54 | 55 | var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 }; 56 | var state = STATE.NONE; 57 | 58 | // events 59 | 60 | var changeEvent = { type: 'change' }; 61 | 62 | 63 | this.rotateLeft = function ( angle ) { 64 | 65 | if ( angle === undefined ) { 66 | 67 | angle = getAutoRotationAngle(); 68 | 69 | } 70 | 71 | thetaDelta -= angle; 72 | 73 | }; 74 | 75 | this.rotateRight = function ( angle ) { 76 | 77 | if ( angle === undefined ) { 78 | 79 | angle = getAutoRotationAngle(); 80 | 81 | } 82 | 83 | thetaDelta += angle; 84 | 85 | }; 86 | 87 | this.rotateUp = function ( angle ) { 88 | 89 | if ( angle === undefined ) { 90 | 91 | angle = getAutoRotationAngle(); 92 | 93 | } 94 | 95 | phiDelta -= angle; 96 | 97 | }; 98 | 99 | this.rotateDown = function ( angle ) { 100 | 101 | if ( angle === undefined ) { 102 | 103 | angle = getAutoRotationAngle(); 104 | 105 | } 106 | 107 | phiDelta += angle; 108 | 109 | }; 110 | 111 | this.zoomIn = function ( zoomScale ) { 112 | 113 | if ( zoomScale === undefined ) { 114 | 115 | zoomScale = getZoomScale(); 116 | 117 | } 118 | 119 | scale /= zoomScale; 120 | 121 | }; 122 | 123 | this.zoomOut = function ( zoomScale ) { 124 | 125 | if ( zoomScale === undefined ) { 126 | 127 | zoomScale = getZoomScale(); 128 | 129 | } 130 | 131 | scale *= zoomScale; 132 | 133 | }; 134 | 135 | this.update = function () { 136 | 137 | var position = this.object.position; 138 | var offset = position.clone().sub( this.center ) 139 | 140 | // angle from z-axis around y-axis 141 | 142 | var theta = Math.atan2( offset.x, offset.z ); 143 | 144 | // angle from y-axis 145 | 146 | var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y ); 147 | 148 | if ( this.autoRotate ) { 149 | 150 | this.rotateLeft( getAutoRotationAngle() ); 151 | 152 | } 153 | 154 | theta += thetaDelta; 155 | phi += phiDelta; 156 | 157 | // restrict phi to be between desired limits 158 | phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); 159 | 160 | // restrict phi to be betwee EPS and PI-EPS 161 | phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) ); 162 | 163 | var radius = offset.length() * scale; 164 | 165 | // restrict radius to be between desired limits 166 | radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) ); 167 | 168 | offset.x = radius * Math.sin( phi ) * Math.sin( theta ); 169 | offset.y = radius * Math.cos( phi ); 170 | offset.z = radius * Math.sin( phi ) * Math.cos( theta ); 171 | 172 | position.copy( this.center ).add( offset ); 173 | 174 | this.object.lookAt( this.center ); 175 | 176 | thetaDelta = 0; 177 | phiDelta = 0; 178 | scale = 1; 179 | 180 | if ( lastPosition.distanceTo( this.object.position ) > 0 ) { 181 | 182 | this.dispatchEvent( changeEvent ); 183 | 184 | lastPosition.copy( this.object.position ); 185 | 186 | } 187 | 188 | }; 189 | 190 | 191 | function getAutoRotationAngle() { 192 | 193 | return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; 194 | 195 | } 196 | 197 | function getZoomScale() { 198 | 199 | return Math.pow( 0.95, scope.userZoomSpeed ); 200 | 201 | } 202 | 203 | function onMouseDown( event ) { 204 | 205 | if ( !scope.userRotate ) return; 206 | 207 | event.preventDefault(); 208 | 209 | if ( event.button === 0 || event.button === 2 ) { 210 | 211 | state = STATE.ROTATE; 212 | 213 | rotateStart.set( event.clientX, event.clientY ); 214 | 215 | } else if ( event.button === 1 ) { 216 | 217 | state = STATE.ZOOM; 218 | 219 | zoomStart.set( event.clientX, event.clientY ); 220 | 221 | } 222 | 223 | document.addEventListener( 'mousemove', onMouseMove, false ); 224 | document.addEventListener( 'mouseup', onMouseUp, false ); 225 | 226 | } 227 | 228 | function onMouseMove( event ) { 229 | 230 | event.preventDefault(); 231 | 232 | if ( state === STATE.ROTATE ) { 233 | 234 | rotateEnd.set( event.clientX, event.clientY ); 235 | rotateDelta.subVectors( rotateEnd, rotateStart ); 236 | 237 | scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed ); 238 | scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed ); 239 | 240 | rotateStart.copy( rotateEnd ); 241 | 242 | } else if ( state === STATE.ZOOM ) { 243 | 244 | zoomEnd.set( event.clientX, event.clientY ); 245 | zoomDelta.subVectors( zoomEnd, zoomStart ); 246 | 247 | if ( zoomDelta.y > 0 ) { 248 | 249 | scope.zoomIn(); 250 | 251 | } else { 252 | 253 | scope.zoomOut(); 254 | 255 | } 256 | 257 | zoomStart.copy( zoomEnd ); 258 | 259 | } 260 | 261 | } 262 | 263 | function onMouseUp( event ) { 264 | 265 | if ( ! scope.userRotate ) return; 266 | 267 | document.removeEventListener( 'mousemove', onMouseMove, false ); 268 | document.removeEventListener( 'mouseup', onMouseUp, false ); 269 | 270 | state = STATE.NONE; 271 | 272 | } 273 | 274 | function onMouseWheel( event ) { 275 | 276 | if ( ! scope.userZoom ) return; 277 | 278 | var delta = 0; 279 | 280 | if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9 281 | 282 | delta = event.wheelDelta; 283 | 284 | } else if ( event.detail ) { // Firefox 285 | 286 | delta = - event.detail; 287 | 288 | } 289 | 290 | if ( delta > 0 ) { 291 | 292 | scope.zoomOut(); 293 | 294 | } else { 295 | 296 | scope.zoomIn(); 297 | 298 | } 299 | 300 | } 301 | 302 | this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); 303 | this.domElement.addEventListener( 'mousedown', onMouseDown, false ); 304 | this.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); 305 | this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox 306 | 307 | }; 308 | -------------------------------------------------------------------------------- /javascript3D/CrazyBox/crazybox.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Crazy Box 8 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /javascript3D/CrazyBox/crazybox.js: -------------------------------------------------------------------------------- 1 | var controls, renderer, scene, camera; 2 | var objects = []; 3 | var g = 9.8; 4 | var count = 500; 5 | 6 | init(); 7 | animate(); 8 | 9 | function setup(i){ 10 | o = objects[i]; 11 | 12 | o.speed = 20 + Math.random() * 70; 13 | o.anglea = Math.random() * 90 * Math.PI / 180.0; 14 | o.angleb = Math.random() * 360 * Math.PI / 180.0; 15 | o.ticks = 0; 16 | o.sphere.position.x = 0; 17 | o.sphere.position.y = 0; 18 | o.sphere.position.z = 0; 19 | 20 | o.sx = o.speed * Math.cos(o.angleb); 21 | o.sy = o.speed * Math.sin(o.anglea); 22 | o.sz = o.speed * Math.sin(o.angleb); 23 | } 24 | 25 | function init(){ 26 | renderer = new THREE.WebGLRenderer(); 27 | 28 | renderer.setSize( window.innerWidth - 15, window.innerHeight - 15 ); 29 | document.getElementById('container').appendChild(renderer.domElement); 30 | 31 | scene = new THREE.Scene(); 32 | 33 | camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000 ); 34 | camera.position.set(0, 0, 1500); 35 | scene.add(camera); 36 | 37 | controls = new THREE.OrbitControls(camera); 38 | controls.addEventListener( 'change', render ); 39 | 40 | box = new THREE.Mesh(new THREE.CubeGeometry(30, 30, 30), new THREE.MeshNormalMaterial()); 41 | box.position.x = 0; 42 | box.position.y = 0; 43 | box.position.z = 0; 44 | box.overdraw = true; 45 | scene.add(box); 46 | 47 | scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); 48 | 49 | for (var i = 0; i < count; i++) 50 | { 51 | sphere = new THREE.Mesh(new THREE.SphereGeometry(5, 10, 10), new THREE.MeshNormalMaterial()); 52 | sphere.overdraw = true; 53 | 54 | var object = {sphere:sphere, anglea:0, angleb:0, ticks:0, speed:0, sx:0, sy:0, sz:0}; 55 | 56 | objects.push(object); 57 | 58 | setup(i); 59 | 60 | scene.add(sphere); 61 | } 62 | 63 | window.addEventListener( 'resize', onWindowResize, false ); 64 | } 65 | 66 | function onWindowResize() { 67 | 68 | camera.aspect = window.innerWidth / window.innerHeight; 69 | camera.updateProjectionMatrix(); 70 | 71 | renderer.setSize( window.innerWidth, window.innerHeight ); 72 | 73 | render(); 74 | } 75 | 76 | function animate(){ 77 | render(); 78 | 79 | requestAnimationFrame( animate ); 80 | 81 | for (var i = 0; i < count; i++) 82 | { 83 | o = objects[i] 84 | 85 | o.ticks++; 86 | t = o.ticks / 10.0; 87 | 88 | o.sphere.position.x = o.sx * t; 89 | o.sphere.position.y = -0.5 * g * t * t + o.sy * t; 90 | o.sphere.position.z = o.sz * t; 91 | 92 | if (o.sphere.position.y < -1000) 93 | { 94 | setup(i); 95 | } 96 | } 97 | 98 | box.rotation.x += 0.02 * 10; 99 | box.rotation.y += 0.0225 * 10; 100 | box.rotation.z += 0.0175 * 10; 101 | 102 | controls.update(); 103 | } 104 | 105 | function render() { 106 | renderer.render(scene, camera); 107 | } -------------------------------------------------------------------------------- /javascript3D/Rosenbrock/rosenbrock.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Rosenbrock 6 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /javascript3D/Rosenbrock/rosenbrock.js: -------------------------------------------------------------------------------- 1 | var mouseX = 0, mouseY = 0, 2 | windowHalfX = window.innerWidth / 2, 3 | windowHalfY = window.innerHeight / 2, 4 | 5 | camera, scene, renderer, solutions = [], 6 | 7 | particlecount = 20, 8 | xlowerbound = -2, 9 | xupperbound = 2, 10 | zlowerbound = -1, 11 | zupperbound = 3, 12 | xstep = 10, 13 | zstep = 10; 14 | 15 | init(); 16 | animate(); 17 | 18 | function rosenbrock(x, y) { 19 | var a = 1 - x 20 | var b = y - x * x 21 | return (a * a + 100.0 * b * b) / 1000.0; 22 | } 23 | 24 | var PI2 = Math.PI * 2; 25 | 26 | var solutionmaterial = new THREE.SpriteCanvasMaterial( { 27 | color: 0xff0000, 28 | program: function ( context ) { 29 | context.beginPath(); 30 | context.arc( 0, 0, 0.5, 0, PI2, true ); 31 | context.fill(); 32 | } 33 | } ); 34 | 35 | var bestsolutionmaterial = new THREE.SpriteCanvasMaterial( { 36 | color: 0x00ff00, 37 | program: function ( context ) { 38 | context.beginPath(); 39 | context.arc( 0, 0, 0.5, 0, PI2, true ); 40 | context.fill(); 41 | } 42 | } ); 43 | 44 | function init() { 45 | var particle; 46 | 47 | renderer = new THREE.CanvasRenderer(); 48 | renderer.setSize( window.innerWidth - 15, window.innerHeight - 15 ); 49 | document.getElementById('container').appendChild(renderer.domElement); 50 | 51 | scene = new THREE.Scene(); 52 | 53 | camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 ); 54 | camera.position.z = 5; 55 | scene.add( camera ); 56 | 57 | // particles 58 | 59 | var material = new THREE.SpriteCanvasMaterial( { 60 | color: 0xffffff, 61 | program: function ( context ) { 62 | context.beginPath(); 63 | context.arc( 0, 0, 0.5, 0, PI2, true ); 64 | context.fill(); 65 | } 66 | } ); 67 | 68 | var geometry = new THREE.Geometry(); 69 | 70 | for ( var i = xlowerbound * xstep; i <= xupperbound * xstep; i++ ) { 71 | x = i / xstep; 72 | for ( var j = zlowerbound * zstep; j <= zupperbound * zstep; j++ ) { 73 | z = j / zstep; 74 | particle = new THREE.Sprite( material ); 75 | particle.position.x = x; 76 | particle.position.z = z; 77 | particle.position.y = rosenbrock(x, z); 78 | particle.scale.x = particle.scale.y = 0.01; 79 | 80 | scene.add( particle ); 81 | } 82 | } 83 | 84 | for ( var i = 0; i < particlecount; i++ ) { 85 | x = Math.random() * 4 - 2; 86 | z = Math.random() * 4 - 1; 87 | particle = new THREE.Sprite( solutionmaterial ); 88 | particle.position.x = x; 89 | particle.position.z = z; 90 | particle.position.y = rosenbrock(x, z); 91 | particle.scale.x = particle.scale.y = 0.05; 92 | 93 | scene.add( particle ); 94 | 95 | var solution = {particle:particle, score:particle.position.z, xspeed:0.001, zspeed:0.001}; 96 | solutions.push( solution ); 97 | } 98 | 99 | document.addEventListener( 'mousemove', onDocumentMouseMove, false ); 100 | 101 | window.addEventListener( 'resize', onWindowResize, false ); 102 | } 103 | 104 | function onWindowResize() { 105 | windowHalfX = window.innerWidth / 2; 106 | windowHalfY = window.innerHeight / 2; 107 | 108 | camera.aspect = window.innerWidth / window.innerHeight; 109 | camera.updateProjectionMatrix(); 110 | 111 | renderer.setSize( window.innerWidth, window.innerHeight ); 112 | } 113 | 114 | function onDocumentMouseMove(event) { 115 | mouseX = event.clientX - windowHalfX; 116 | mouseY = event.clientY - windowHalfY; 117 | } 118 | 119 | function animate() { 120 | render(); 121 | requestAnimationFrame( animate ); 122 | 123 | //find best index 124 | var bestindex = -1; 125 | for (var i = 0; i < particlecount; i++) 126 | { 127 | if (bestindex == -1 || solutions[i].particle.position.y < solutions[bestindex].particle.position.y) { 128 | bestindex = i; 129 | } 130 | } 131 | 132 | for (var i = 0; i < particlecount; i++) 133 | { 134 | if (i != bestindex) 135 | { 136 | xdist = solutions[bestindex].particle.position.x - solutions[i].particle.position.x; 137 | zdist = solutions[bestindex].particle.position.z - solutions[i].particle.position.z; 138 | solutions[i].xspeed = solutions[i].xspeed + Math.random() * xdist / 1000; 139 | solutions[i].zspeed = solutions[i].zspeed + Math.random() * zdist / 1000; 140 | solutions[i].particle.material = solutionmaterial; 141 | } 142 | else 143 | { 144 | solutions[i].particle.material = bestsolutionmaterial; 145 | } 146 | solutions[i].particle.position.x += solutions[i].xspeed; 147 | solutions[i].particle.position.z += solutions[i].zspeed; 148 | solutions[i].particle.position.y = rosenbrock(solutions[i].particle.position.x, solutions[i].particle.position.z); 149 | 150 | if (solutions[i].particle.position.x < xlowerbound) 151 | solutions[i].particle.position.x = xlowerbound; 152 | if (solutions[i].particle.position.x > xupperbound) 153 | solutions[i].particle.position.x = xupperbound; 154 | if (solutions[i].particle.position.z < zlowerbound) 155 | solutions[i].particle.position.z = zlowerbound; 156 | if (solutions[i].particle.position.z > zupperbound) 157 | solutions[i].particle.position.z = zupperbound; 158 | } 159 | } 160 | 161 | function render() { 162 | camera.position.x = mouseX / 100; 163 | camera.position.z = 4; 164 | camera.position.y = 4; 165 | camera.lookAt( scene.position ); 166 | 167 | renderer.render( scene, camera ); 168 | } --------------------------------------------------------------------------------