sfml.js 0.0.1-preview.27 → 0.0.1-preview.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/binding.gyp CHANGED
@@ -104,6 +104,7 @@
104
104
 
105
105
  "./src/sound/music.cc",
106
106
  "./src/sound/sound.cc",
107
+ "./src/sound/sound_buffer.cc",
107
108
  "./src/sound/sound_source.cc"
108
109
  ],
109
110
  "dependencies": [
package/lib/common.js CHANGED
@@ -19,15 +19,26 @@ function validateTypeOf(arg, name, type, optional = false) {
19
19
  return;
20
20
  }
21
21
 
22
- if (typeof type !== 'string') {
23
- if (!(arg instanceof type)) {
24
- throw new TypeError(`Parameter \`${name}\` has wrong type.`);
25
- }
26
- } else {
27
- if (typeof arg !== type) {
28
- throw new TypeError(`Parameter \`${name}\` should be type of ${type}.`);
22
+ if (!Array.isArray(type)) {
23
+ type = [ type ];
24
+ }
25
+
26
+ for (const t of type) {
27
+ if (typeof t !== 'string') {
28
+ if (arg instanceof t) {
29
+ return;
30
+ }
31
+ } else {
32
+ if (typeof arg === t) {
33
+ return;
34
+ }
29
35
  }
30
36
  }
37
+
38
+ throw new TypeError(`Parameter \`${name}\` should be type of ${type.map(t => {
39
+ if (typeof t === 'string') return t;
40
+ return t.name;
41
+ }).join(', ')}.`);
31
42
  }
32
43
 
33
44
  module.exports = {
@@ -81,6 +81,25 @@ function setTransformable(proto) {
81
81
  validateTypeOf(y, 'y', 'number');
82
82
  return this._raw().move(xOrOffset, y);
83
83
  },
84
+
85
+ scale(xOrFactor, y) {
86
+ if (arguments.length === 1) {
87
+ if (!(xOrFactor instanceof Vector2F)) {
88
+ xOrFactor = new Vector2F(xOrFactor?.x, xOrFactor?.y);
89
+ }
90
+
91
+ return this._raw().scale(xOrFactor);
92
+ }
93
+
94
+ validateTypeOf(xOrFactor, 'x', 'number');
95
+ validateTypeOf(y, 'y', 'number');
96
+ return this._raw().scale(xOrFactor, y);
97
+ },
98
+
99
+ rotate(rotation) {
100
+ validateTypeOf(rotation, 'rotation', 'number');
101
+ this._raw().rotate(rotation);
102
+ },
84
103
  };
85
104
 
86
105
  for (const key in ret) {
package/lib/sfml.d.ts CHANGED
@@ -21,3 +21,6 @@ export * from './drawable/text';
21
21
 
22
22
  export * from './sound/music';
23
23
  export * from './sound/sound';
24
+ export * from './sound/sound_buffer';
25
+
26
+ export * from './poll_event';
package/lib/sfml.js CHANGED
@@ -26,4 +26,5 @@ module.exports = {
26
26
  // sound
27
27
  ...require('./sound/music'),
28
28
  ...require('./sound/sound'),
29
+ ...require('./sound/sound_buffer'),
29
30
  };
@@ -8,3 +8,7 @@ export class Music extends SoundSource {
8
8
  setLoop(loop: boolean): void;
9
9
  getLoop(): boolean;
10
10
  }
11
+
12
+ export namespace Music {
13
+ type Status = SoundSource.Status;
14
+ }
@@ -55,4 +55,5 @@ class Music extends SoundSource {
55
55
  }
56
56
  }
57
57
 
58
+ Music.Status = SoundSource.Status;
58
59
  module.exports = { Music };
@@ -1,8 +1,16 @@
1
+ import { SoundBuffer } from './sound_buffer';
1
2
  import { SoundSource } from './base';
2
3
 
3
4
  export class Sound extends SoundSource {
4
- constructor(buffer?: Buffer);
5
+ constructor(buffer?: Buffer | SoundBuffer);
6
+
7
+ setBuffer(buffer: Buffer | SoundBuffer): void;
8
+ getBuffer(): SoundBuffer;
5
9
 
6
10
  setLoop(loop: boolean): void;
7
11
  getLoop(): boolean;
8
12
  }
13
+
14
+ export namespace Sound {
15
+ type Status = SoundSource.Status;
16
+ }
@@ -3,20 +3,29 @@
3
3
  const util = require('util');
4
4
 
5
5
  const { validateTypeOf } = require('../common');
6
+ const { SoundBuffer } = require('./sound_buffer');
6
7
  const { SoundSource } = require('./base');
7
8
 
8
9
  const GET_LOOP = Symbol('Sound::getLoop');
10
+ const SOUND_BUFFER = Symbol('Sound::soundBuffer');
9
11
 
10
12
  class Sound extends SoundSource {
11
13
  [util.inspect.custom](depth, opts) {
12
14
  return `${Sound.name} ${util.inspect({
13
15
  [GET_LOOP]: this.getLoop(),
16
+ [SOUND_BUFFER]: this[SOUND_BUFFER],
14
17
  ...super.toJSON(),
15
18
  }, opts)}`;
16
19
  }
17
20
 
18
21
  constructor(buffer) {
22
+ validateTypeOf(buffer, 'buffer', [ Buffer, SoundBuffer ], true);
23
+ if (Buffer.isBuffer(buffer)) {
24
+ buffer = new SoundBuffer(buffer);
25
+ }
26
+
19
27
  super('Sound', buffer);
28
+ this[SOUND_BUFFER] = buffer || null;
20
29
  }
21
30
 
22
31
  setLoop(loop) {
@@ -27,6 +36,20 @@ class Sound extends SoundSource {
27
36
  getLoop() {
28
37
  return this._raw().getLoop();
29
38
  }
39
+
40
+ setBuffer(buffer) {
41
+ validateTypeOf(buffer, 'buffer', [ Buffer, SoundBuffer ]);
42
+ if (Buffer.isBuffer(buffer)) {
43
+ buffer = new SoundBuffer(buffer);
44
+ }
45
+ this._raw().setBuffer(buffer);
46
+ this[SOUND_BUFFER] = buffer;
47
+ }
48
+
49
+ getBuffer() {
50
+ return this[SOUND_BUFFER];
51
+ }
30
52
  }
31
53
 
54
+ Sound.Status = SoundSource.Status;
32
55
  module.exports = { Sound };
@@ -0,0 +1,14 @@
1
+ import { _Time } from '../time';
2
+
3
+ export class SoundBuffer {
4
+ constructor(buffer?: Buffer);
5
+ loadFromMemory(buffer: Buffer): boolean;
6
+ loadFromSamples(samples: number[] | Int16Array, channelCount: number, sampleRate: number): boolean;
7
+ duplicateSamples(): Int16Array;
8
+ getSampleCount(): number;
9
+ getSampleRate(): number;
10
+ getChannelCount(): number;
11
+ getDuration(): _Time;
12
+
13
+ saveToFile(filename: string): Promise<void>;
14
+ }
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const util = require('util');
5
+
6
+ const { milliseconds } = require('../time');
7
+
8
+ const { SoundBuffer: _SoundBuffer } = require('../../build/Release/binding.node');
9
+ const { createDeferred, validateTypeOf } = require('../common');
10
+
11
+ const SAMPLES = Symbol('SoundBuffer#samples');
12
+ const DURATION = Symbol('SoundBuffer#duration');
13
+ const SAMPLE_COUNT = Symbol('SoundBuffer#sampleCount');
14
+ const SAMPLE_RATE = Symbol('SoundBuffer#sampleRate');
15
+ const CHANNEL_COUNT = Symbol('SoundBuffer#channelCount');
16
+
17
+ class SoundBuffer extends _SoundBuffer {
18
+ [util.inspect.custom](depth, opts) {
19
+ return `${SoundBuffer.name} ${util.inspect({
20
+ [SAMPLES]: this.duplicateSamples(),
21
+ [DURATION]: this.getDuration(),
22
+ [SAMPLE_COUNT]: this.getSampleCount(),
23
+ [SAMPLE_RATE]: this.getSampleRate(),
24
+ [CHANNEL_COUNT]: this.getChannelCount(),
25
+ }, opts)}`;
26
+ }
27
+
28
+ constructor(buffer) {
29
+ if (!buffer) {
30
+ super();
31
+ } else {
32
+ validateTypeOf(buffer, 'buffer', Buffer);
33
+ super(buffer);
34
+ }
35
+ }
36
+
37
+ loadFromMemory(buffer) {
38
+ validateTypeOf(buffer, 'buffer', Buffer);
39
+ return super.loadFromMemory(buffer);
40
+ }
41
+
42
+ loadFromSamples(samples, channelCount, sampleRate) {
43
+ validateTypeOf(samples, 'samples', [ Array, Int16Array ]);
44
+ validateTypeOf(channelCount, 'channelCount', 'number');
45
+ validateTypeOf(sampleRate, 'sampleRate', 'number');
46
+ if (sampleRate < 0 || channelCount < 0) {
47
+ throw new RangeError('channelCount and sampleRate should >= 0.');
48
+ }
49
+
50
+ return super.loadFromSamples(samples, channelCount, sampleRate);
51
+ }
52
+
53
+ getDuration() {
54
+ const dur = super.getDuration();
55
+ return milliseconds(dur);
56
+ }
57
+
58
+ async saveToFile(filename) {
59
+ const { promise, resolve, reject } = createDeferred();
60
+ validateTypeOf(filename, 'filename', 'string');
61
+ filename = path.resolve(process.cwd(), filename);
62
+ const err = super.saveToFile(filename, err => {
63
+ if (err) {
64
+ reject(err);
65
+ } else {
66
+ resolve();
67
+ }
68
+ });
69
+
70
+ if (err) {
71
+ process.nextTick(() => { reject(err); });
72
+ }
73
+
74
+ return promise;
75
+ }
76
+ }
77
+
78
+ module.exports = { SoundBuffer };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sfml.js",
3
- "version": "0.0.1-preview.27",
3
+ "version": "0.0.1-preview.30",
4
4
  "description": "SFML's Node.js binding.",
5
5
  "main": "lib/sfml.js",
6
6
  "scripts": {
@@ -50,5 +50,6 @@
50
50
  "third_party/sfml/platform/macOS/Frameworks/**/*",
51
51
  "tools/*",
52
52
  "tsconfig.json"
53
- ]
53
+ ],
54
+ "__npminstall_done": false
54
55
  }
@@ -9,8 +9,8 @@ namespace node_sfml {
9
9
  template <typename T>
10
10
  struct ReleasedResizableBuffer {
11
11
  T* buffer;
12
- int length;
13
- int byte_length;
12
+ size_t length;
13
+ size_t byte_length;
14
14
  };
15
15
 
16
16
  template <typename T>
@@ -71,7 +71,7 @@ class ResizableBuffer {
71
71
  size_t byte_length = _byte_length;
72
72
 
73
73
  _buff = nullptr;
74
- length = byte_length = 0;
74
+ _length = _byte_length = 0;
75
75
 
76
76
  return {buffer, length, byte_length};
77
77
  }
package/src/sfml.cc CHANGED
@@ -21,6 +21,8 @@
21
21
 
22
22
  #include "sound/music.h"
23
23
  #include "sound/sound.h"
24
+ #include "sound/sound_buffer.h"
25
+ #include "sound/sound_source.h"
24
26
 
25
27
  namespace node_sfml {
26
28
 
@@ -47,6 +49,7 @@ void Init(v8::Local<v8::Object> target) {
47
49
  // sound
48
50
  sound::Music::Init(target);
49
51
  sound::Sound::Init(target);
52
+ sound::SoundBuffer::Init(target);
50
53
 
51
54
  // rect
52
55
  rect::IntRect::Init(target);
@@ -56,6 +59,9 @@ void Init(v8::Local<v8::Object> target) {
56
59
  vector2::Vector2I::Init(target);
57
60
  vector2::Vector2U::Init(target);
58
61
  vector2::Vector2F::Init(target);
62
+
63
+ node::AddEnvironmentCleanupHook(
64
+ target->GetIsolate(), sound::SoundSource::AtExit, nullptr);
59
65
  }
60
66
 
61
67
  } // namespace node_sfml
@@ -93,10 +93,8 @@ NAN_METHOD(Music::OpenFromFileSync) {
93
93
  info.GetReturnValue().Set(music->music().openFromFile(*filename));
94
94
  }
95
95
 
96
- Music::Music() : SoundSource(new sf::Music()) {}
97
- Music::~Music() {
98
- music().stop();
99
- }
96
+ Music::Music() : SoundSource(SoundSource::SoundType::kMusic, new sf::Music()) {}
97
+ Music::~Music() {}
100
98
 
101
99
  } // namespace sound
102
100
  } // namespace node_sfml
package/src/sound/music.h CHANGED
@@ -31,4 +31,4 @@ class Music : public SoundSource, public BaseClassWithLoading {
31
31
  } // namespace sound
32
32
  } // namespace node_sfml
33
33
 
34
- #endif // SRC_MUSIC_H_
34
+ #endif // SRC_SOUND_MUSIC_H_
@@ -23,6 +23,8 @@ NAN_MODULE_INIT(Sound::Init) {
23
23
  Nan::SetPrototypeMethod(tpl, "setLoop", SetLoop);
24
24
  Nan::SetPrototypeMethod(tpl, "getLoop", GetLoop);
25
25
 
26
+ Nan::SetPrototypeMethod(tpl, "setBuffer", SetBuffer);
27
+
26
28
  sound::SoundSource::SetCommonPrototype(&tpl);
27
29
 
28
30
  tpl->SetClassName(name);
@@ -36,21 +38,12 @@ NAN_MODULE_INIT(Sound::Init) {
36
38
 
37
39
  NAN_METHOD(Sound::New) {
38
40
  Sound* sound = nullptr;
39
- if (info.Length() == 0) {
41
+ if (info.Length() == 0 || info[0]->IsNullOrUndefined()) {
40
42
  sound = new Sound();
41
- } else if (info.Length() == 1) {
42
- node::Buffer::HasInstance(info[0].As<Object>());
43
- if (node::Buffer::HasInstance(info[0])) {
44
- char* buf = node::Buffer::Data(info[0]);
45
- int len = node::Buffer::Length(info[0]);
46
-
47
- std::shared_ptr<sf::SoundBuffer> sound_buffer =
48
- std::make_shared<sf::SoundBuffer>();
49
- sound_buffer.get()->loadFromMemory(buf, len);
50
- sound = new Sound(sound_buffer);
51
- }
52
-
53
- // TODO(XadillaX): SoundBuffer
43
+ } else if (info.Length() >= 1) {
44
+ SoundBuffer* sb =
45
+ Nan::ObjectWrap::Unwrap<SoundBuffer>(info[0].As<Object>());
46
+ sound = new Sound(sb);
54
47
  }
55
48
 
56
49
  if (!sound) {
@@ -62,6 +55,15 @@ NAN_METHOD(Sound::New) {
62
55
  info.GetReturnValue().Set(info.This());
63
56
  }
64
57
 
58
+ NAN_METHOD(Sound::SetBuffer) {
59
+ Sound* sound = Nan::ObjectWrap::Unwrap<Sound>(info.Holder());
60
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info[0].As<Object>());
61
+ sound->sound().setBuffer(sb->sound_buffer());
62
+
63
+ sound->_sound_buffer = sb;
64
+ sound->_sound_buffer_object.Reset(sb->handle());
65
+ }
66
+
65
67
  NAN_METHOD(Sound::SetLoop) {
66
68
  Sound* sound = Nan::ObjectWrap::Unwrap<Sound>(info.Holder());
67
69
  bool val = Nan::To<bool>(info[0]).FromJust();
@@ -94,15 +96,20 @@ inline void SoundStop(SoundSource* ss) {
94
96
  }
95
97
 
96
98
  Sound::Sound()
97
- : SoundSource(new sf::Sound(), {SoundPlay, SoundPause, SoundStop}) {}
99
+ : SoundSource(SoundSource::SoundType::kSound,
100
+ new sf::Sound(),
101
+ {SoundPlay, SoundPause, SoundStop}),
102
+ _sound_buffer(nullptr) {}
98
103
 
99
- Sound::Sound(const std::shared_ptr<sf::SoundBuffer>& sound_buffer)
100
- : SoundSource(new sf::Sound(*sound_buffer.get()),
104
+ Sound::Sound(SoundBuffer* sound_buffer)
105
+ : SoundSource(SoundSource::SoundType::kSound,
106
+ new sf::Sound(sound_buffer->sound_buffer()),
101
107
  {SoundPlay, SoundPause, SoundStop}),
102
- _sfml_sound_buffer(sound_buffer) {}
108
+ _sound_buffer(sound_buffer),
109
+ _sound_buffer_object(sound_buffer->handle()) {}
103
110
 
104
111
  Sound::~Sound() {
105
- sound().stop();
112
+ _sound_buffer_object.Reset();
106
113
  }
107
114
 
108
115
  } // namespace sound
package/src/sound/sound.h CHANGED
@@ -4,6 +4,7 @@
4
4
  #include <SFML/Audio/Sound.hpp>
5
5
  #include <SFML/Audio/SoundBuffer.hpp>
6
6
 
7
+ #include "sound_buffer.h"
7
8
  #include "sound_source.h"
8
9
 
9
10
  namespace node_sfml {
@@ -19,21 +20,19 @@ class Sound : public SoundSource {
19
20
  static NAN_METHOD(New);
20
21
  static NAN_METHOD(SetLoop);
21
22
  static NAN_METHOD(GetLoop);
23
+ static NAN_METHOD(SetBuffer);
22
24
 
23
25
  inline const sf::Sound& sound() const { return sound_source<sf::Sound>(); }
24
26
  inline sf::Sound& sound() { return sound_source<sf::Sound>(); }
25
27
 
26
28
  private:
27
29
  Sound();
28
- explicit Sound(const std::shared_ptr<sf::SoundBuffer>& sound_buffer);
30
+ explicit Sound(SoundBuffer* sound_buffer);
29
31
  virtual ~Sound();
30
32
 
31
33
  private:
32
- // Should store sound buffer by self because `sf::Sound` only holds its
33
- // pointer.
34
- std::shared_ptr<sf::SoundBuffer> _sfml_sound_buffer;
35
- // TODO(XadillaX): SoundBuffer object of JavaScript should be attached here
36
- // also.
34
+ SoundBuffer* _sound_buffer;
35
+ Nan::Persistent<v8::Object> _sound_buffer_object;
37
36
  };
38
37
 
39
38
  } // namespace sound
@@ -0,0 +1,257 @@
1
+ #include "sound_buffer.h"
2
+ #include "../resizable_buffer.h"
3
+
4
+ namespace node_sfml {
5
+ namespace sound {
6
+
7
+ using std::string;
8
+ using v8::Array;
9
+ using v8::ArrayBuffer;
10
+ using v8::BigInt;
11
+ using v8::Function;
12
+ using v8::FunctionTemplate;
13
+ using v8::Int16Array;
14
+ using v8::Isolate;
15
+ using v8::Local;
16
+ using v8::MaybeLocal;
17
+ using v8::Object;
18
+ using v8::String;
19
+ using v8::Value;
20
+
21
+ namespace {
22
+ Nan::Persistent<Function> constructor;
23
+
24
+ class SaveToFileWorker : public Nan::AsyncWorker {
25
+ public:
26
+ SaveToFileWorker(SoundBuffer* sound_buffer,
27
+ const string& filename,
28
+ Nan::Callback* callback)
29
+ : Nan::AsyncWorker(callback),
30
+ _filename(filename),
31
+ _saved(false),
32
+ _sound_buffer(sound_buffer),
33
+ _async_resource("save_to_file_worker") {
34
+ _object.Reset(sound_buffer->handle());
35
+ }
36
+
37
+ ~SaveToFileWorker() { _object.Reset(); }
38
+
39
+ inline virtual void Execute() {
40
+ _saved = _sound_buffer->sound_buffer().saveToFile(_filename);
41
+ if (!_saved) {
42
+ char error[1024];
43
+ snprintf(error,
44
+ sizeof error,
45
+ "Failed to save SoundBuffer to %s.",
46
+ this->_filename.c_str());
47
+ SetErrorMessage(error);
48
+ }
49
+ }
50
+
51
+ inline virtual void HandleOKCallback() {
52
+ Nan::HandleScope scope;
53
+ callback->Call(0, nullptr, &_async_resource);
54
+ }
55
+
56
+ inline virtual void HandleErrorCallback() {
57
+ Nan::HandleScope scope;
58
+ v8::Local<v8::Value> argv[1] = {Nan::Error(ErrorMessage())};
59
+ callback->Call(1, argv, &_async_resource);
60
+ }
61
+
62
+ inline Nan::AsyncResource* async_resource() { return &_async_resource; }
63
+
64
+ private:
65
+ string _filename;
66
+ bool _saved;
67
+ Nan::Persistent<v8::Object> _object;
68
+ SoundBuffer* _sound_buffer;
69
+ Nan::AsyncResource _async_resource;
70
+ };
71
+ } // namespace
72
+
73
+ NAN_MODULE_INIT(SoundBuffer::Init) {
74
+ Local<String> name = Nan::New("SoundBuffer").ToLocalChecked();
75
+
76
+ Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
77
+
78
+ Nan::SetPrototypeMethod(tpl, "duplicateSamples", DuplicateSamples);
79
+ Nan::SetPrototypeMethod(tpl, "loadFromSamples", LoadFromSamples);
80
+ Nan::SetPrototypeMethod(tpl, "loadFromMemory", LoadFromMemory);
81
+
82
+ Nan::SetPrototypeMethod(tpl, "getSampleCount", GetSampleCount);
83
+ Nan::SetPrototypeMethod(tpl, "getSampleRate", GetSampleRate);
84
+ Nan::SetPrototypeMethod(tpl, "getChannelCount", GetChannelCount);
85
+ Nan::SetPrototypeMethod(tpl, "getDuration", GetDuration);
86
+ Nan::SetPrototypeMethod(tpl, "saveToFile", SaveToFile);
87
+
88
+ tpl->SetClassName(name);
89
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
90
+
91
+ Local<Function> func = Nan::GetFunction(tpl).ToLocalChecked();
92
+ constructor.Reset(func);
93
+
94
+ Nan::Set(target, name, func);
95
+ }
96
+
97
+ NAN_METHOD(SoundBuffer::New) {
98
+ SoundBuffer* sb = nullptr;
99
+ if (info.Length() == 0 || info[0]->IsNullOrUndefined()) {
100
+ sb = new SoundBuffer();
101
+ } else if (info.Length() == 1) {
102
+ if (node::Buffer::HasInstance(info[0])) {
103
+ char* buf = node::Buffer::Data(info[0]);
104
+ int len = node::Buffer::Length(info[0]);
105
+ sb = new SoundBuffer(buf, len);
106
+ }
107
+
108
+ // TODO(XadillaX): SoundBuffer
109
+ }
110
+
111
+ if (!sb) {
112
+ Nan::ThrowError("Cannot create SoundBuffer instance.");
113
+ return;
114
+ }
115
+
116
+ sb->Wrap(info.This());
117
+ info.GetReturnValue().Set(info.This());
118
+ }
119
+
120
+ NAN_METHOD(SoundBuffer::LoadFromMemory) {
121
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
122
+
123
+ char* buf = node::Buffer::Data(info[0]);
124
+ int len = node::Buffer::Length(info[0]);
125
+
126
+ info.GetReturnValue().Set(sb->LoadFromMemory(buf, len));
127
+ }
128
+
129
+ NAN_METHOD(SoundBuffer::LoadFromSamples) {
130
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
131
+
132
+ ResizableBuffer<sf::Int16> buff;
133
+ if (info[0]->IsInt16Array()) {
134
+ Local<Int16Array> int16_array = info[0].As<Int16Array>();
135
+ size_t array_length = int16_array->Length();
136
+ buff.Realloc(array_length);
137
+ sf::Int16* ptr = buff.buffer();
138
+
139
+ Nan::TryCatch try_catch;
140
+ MaybeLocal<Value> maybe;
141
+ Local<Value> val;
142
+ for (size_t i = 0; i < array_length; i++) {
143
+ maybe = Nan::Get(int16_array, i);
144
+ if (try_catch.HasCaught()) {
145
+ try_catch.ReThrow();
146
+ return;
147
+ }
148
+
149
+ val = maybe.ToLocalChecked();
150
+ ptr[i] = static_cast<sf::Int16>(Nan::To<sf::Int32>(val).FromJust());
151
+ }
152
+ } else {
153
+ Local<Array> arr = info[0].As<Array>();
154
+ size_t array_length = arr->Length();
155
+ buff.Realloc(array_length);
156
+ sf::Int16* ptr = buff.buffer();
157
+
158
+ Nan::TryCatch try_catch;
159
+ MaybeLocal<Value> maybe;
160
+ Local<Value> val;
161
+ for (size_t i = 0; i < array_length; i++) {
162
+ maybe = Nan::Get(arr, i);
163
+ if (try_catch.HasCaught()) {
164
+ try_catch.ReThrow();
165
+ return;
166
+ }
167
+
168
+ val = maybe.ToLocalChecked();
169
+ if (!val->IsInt32()) {
170
+ Nan::ThrowTypeError("samples should be numbers.");
171
+ try_catch.ReThrow();
172
+ return;
173
+ }
174
+
175
+ sf::Int32 sample = Nan::To<sf::Int32>(val).FromJust();
176
+ if (sample < -32768 || sample > 32767) {
177
+ Nan::ThrowRangeError("samples should be Int16.");
178
+ try_catch.ReThrow();
179
+ return;
180
+ }
181
+
182
+ ptr[i] = static_cast<sf::Int16>(sample);
183
+ }
184
+ }
185
+
186
+ sf::Uint32 channel_count = Nan::To<sf::Uint32>(info[1]).FromJust();
187
+ sf::Uint32 sample_rate = Nan::To<sf::Uint32>(info[2]).FromJust();
188
+
189
+ info.GetReturnValue().Set(sb->_sound_buffer.loadFromSamples(
190
+ buff.buffer(), buff.length(), channel_count, sample_rate));
191
+ }
192
+
193
+ NAN_METHOD(SoundBuffer::DuplicateSamples) {
194
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
195
+ const sf::Int16* samples = sb->_sound_buffer.getSamples();
196
+ sf::Uint64 sample_count = sb->_sound_buffer.getSampleCount();
197
+
198
+ ResizableBuffer<sf::Int16> resizable(sample_count);
199
+ memcpy(resizable.buffer(), samples, resizable.byte_length());
200
+ ReleasedResizableBuffer<sf::Int16> rrb = resizable.Release();
201
+
202
+ Local<ArrayBuffer> ab = ArrayBuffer::New(
203
+ info.GetIsolate(),
204
+ ArrayBuffer::NewBackingStore(
205
+ rrb.buffer,
206
+ rrb.byte_length,
207
+ [](void* buff, size_t length, void* info) { free(buff); },
208
+ nullptr));
209
+
210
+ Local<Int16Array> i16a = Int16Array::New(ab, 0, rrb.length);
211
+ info.GetReturnValue().Set(i16a);
212
+ }
213
+
214
+ NAN_METHOD(SoundBuffer::GetSampleCount) {
215
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
216
+ info.GetReturnValue().Set(
217
+ static_cast<sf::Uint32>(sb->_sound_buffer.getSampleCount()));
218
+ }
219
+
220
+ NAN_METHOD(SoundBuffer::GetSampleRate) {
221
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
222
+ info.GetReturnValue().Set(sb->_sound_buffer.getSampleRate());
223
+ }
224
+
225
+ NAN_METHOD(SoundBuffer::GetChannelCount) {
226
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
227
+ info.GetReturnValue().Set(sb->_sound_buffer.getChannelCount());
228
+ }
229
+
230
+ NAN_METHOD(SoundBuffer::GetDuration) {
231
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
232
+ info.GetReturnValue().Set(sb->_sound_buffer.getDuration().asMilliseconds());
233
+ }
234
+
235
+ // TODO(XadillaX): Use Node.js fs API + Buffer in pure JavaScript side.
236
+ NAN_METHOD(SoundBuffer::SaveToFile) {
237
+ Local<String> v8_filename = info[0].As<String>();
238
+ Nan::Utf8String utf8_filename(v8_filename);
239
+ Nan::Callback* callback = new Nan::Callback(info[1].As<Function>());
240
+
241
+ SoundBuffer* sb = Nan::ObjectWrap::Unwrap<SoundBuffer>(info.Holder());
242
+ SaveToFileWorker* worker = new SaveToFileWorker(sb, *utf8_filename, callback);
243
+ Nan::AsyncQueueWorker(worker);
244
+ }
245
+
246
+ inline bool SoundBuffer::LoadFromMemory(const char* buff, size_t len) {
247
+ return _sound_buffer.loadFromMemory(buff, len);
248
+ }
249
+
250
+ SoundBuffer::SoundBuffer() : _sound_buffer() {}
251
+ SoundBuffer::SoundBuffer(const char* buff, size_t len) : SoundBuffer() {
252
+ LoadFromMemory(buff, len);
253
+ }
254
+ SoundBuffer::~SoundBuffer() {}
255
+
256
+ } // namespace sound
257
+ } // namespace node_sfml
@@ -0,0 +1,44 @@
1
+ #ifndef SRC_SOUND_SOUND_BUFFER_H_
2
+ #define SRC_SOUND_SOUND_BUFFER_H_
3
+
4
+ #include <nan.h>
5
+ #include <SFML/Audio/SoundBuffer.hpp>
6
+
7
+ namespace node_sfml {
8
+ namespace sound {
9
+
10
+ class SoundBuffer : public Nan::ObjectWrap {
11
+ public:
12
+ static NAN_MODULE_INIT(Init);
13
+
14
+ public:
15
+ static NAN_METHOD(New);
16
+ static NAN_METHOD(LoadFromMemory);
17
+ static NAN_METHOD(LoadFromSamples);
18
+ static NAN_METHOD(DuplicateSamples);
19
+
20
+ static NAN_METHOD(GetSampleCount);
21
+ static NAN_METHOD(GetSampleRate);
22
+ static NAN_METHOD(GetChannelCount);
23
+ static NAN_METHOD(GetDuration);
24
+
25
+ static NAN_METHOD(SaveToFile);
26
+
27
+ inline const sf::SoundBuffer& sound_buffer() const { return _sound_buffer; }
28
+ inline sf::SoundBuffer& sound_buffer() { return _sound_buffer; }
29
+
30
+ private:
31
+ SoundBuffer();
32
+ explicit SoundBuffer(const char* buff, size_t len);
33
+ virtual ~SoundBuffer();
34
+
35
+ inline bool LoadFromMemory(const char* buff, size_t len);
36
+
37
+ private:
38
+ sf::SoundBuffer _sound_buffer;
39
+ };
40
+
41
+ } // namespace sound
42
+ } // namespace node_sfml
43
+
44
+ #endif // SRC_SOUND_SOUND_BUFFER_H_
@@ -1,13 +1,49 @@
1
1
  #include "sound_source.h"
2
2
 
3
+ #include "music.h"
4
+ #include "sound.h"
5
+
3
6
  namespace node_sfml {
4
7
  namespace sound {
5
8
 
6
9
  using v8::Boolean;
7
10
  using v8::FunctionTemplate;
11
+ using v8::Isolate;
8
12
  using v8::Local;
9
13
  using v8::Number;
10
14
 
15
+ std::map<SoundSource*, SoundSource::SoundType> SoundSource::registered_sounds;
16
+
17
+ void SoundSource::Stop(SoundType type, SoundSource* source, bool delete_ptr) {
18
+ #define CASE(camel_case) \
19
+ case SoundType::k##camel_case: { \
20
+ if (delete_ptr) { \
21
+ sf::camel_case* val = \
22
+ reinterpret_cast<sf::camel_case*>(source->_sound_source.release()); \
23
+ val->stop(); \
24
+ delete val; \
25
+ } else { \
26
+ (reinterpret_cast<sf::camel_case*>(source->_sound_source.get())) \
27
+ ->stop(); \
28
+ } \
29
+ break; \
30
+ }
31
+
32
+ switch (type) {
33
+ CASE(Music)
34
+ CASE(Sound)
35
+ }
36
+ }
37
+
38
+ void SoundSource::AtExit(void* argv) {
39
+ for (auto it = registered_sounds.begin(); it != registered_sounds.end();
40
+ it++) {
41
+ SoundSource::Stop(it->second, it->first, true);
42
+ }
43
+
44
+ registered_sounds.clear();
45
+ }
46
+
11
47
  void SoundSource::SetCommonPrototype(Local<FunctionTemplate>* _tpl) {
12
48
  Local<FunctionTemplate>& tpl = *_tpl;
13
49
 
@@ -65,11 +101,24 @@ SIMPLE_ACTION(Stop, stop);
65
101
  SOUND_SOURCE_SIMPLE_SETTER_AND_GETTERS(SIMPLE_SETTER_GETTER);
66
102
  #undef SIMPLE_SETTER_GETTER
67
103
 
68
- SoundSource::SoundSource(sf::SoundSource* sound_source,
104
+ SoundSource::SoundSource(SoundType type,
105
+ sf::SoundSource* sound_source,
69
106
  SimpleActions simple_actions)
70
- : _sound_source(sound_source), _simple_actions(simple_actions) {}
107
+ : _sound_source(sound_source),
108
+ _simple_actions(simple_actions),
109
+ _type(type) {
110
+ registered_sounds[this] = type;
111
+ }
112
+
113
+ SoundSource::~SoundSource() {
114
+ auto it = registered_sounds.find(this);
115
+ if (it == registered_sounds.end()) {
116
+ return;
117
+ }
71
118
 
72
- SoundSource::~SoundSource() {}
119
+ SoundSource::Stop(it->second, this);
120
+ registered_sounds.erase(it);
121
+ }
73
122
 
74
123
  } // namespace sound
75
124
  } // namespace node_sfml
@@ -2,6 +2,7 @@
2
2
  #define SRC_SOUND_SOUND_SOURCE_H_
3
3
 
4
4
  #include <nan.h>
5
+ #include <map>
5
6
 
6
7
  #include <SFML/Audio/SoundSource.hpp>
7
8
 
@@ -9,14 +10,20 @@ namespace node_sfml {
9
10
  namespace sound {
10
11
 
11
12
  class SoundSource : public Nan::ObjectWrap {
13
+ public:
12
14
  struct SimpleActions {
13
15
  void (*play)(SoundSource*);
14
16
  void (*pause)(SoundSource*);
15
17
  void (*stop)(SoundSource*);
16
18
  };
17
19
 
18
- public:
20
+ enum SoundType {
21
+ kMusic,
22
+ kSound,
23
+ };
24
+
19
25
  static void SetCommonPrototype(v8::Local<v8::FunctionTemplate>* _tpl);
26
+ static void AtExit(void* argv);
20
27
 
21
28
  public:
22
29
  static NAN_METHOD(Play);
@@ -40,7 +47,8 @@ class SoundSource : public Nan::ObjectWrap {
40
47
  // TODO(XadillaX): SetPosition / GetPosition
41
48
 
42
49
  public:
43
- explicit SoundSource(sf::SoundSource* sound_source,
50
+ explicit SoundSource(SoundType type,
51
+ sf::SoundSource* sound_source,
44
52
  SimpleActions = {nullptr, nullptr, nullptr});
45
53
  ~SoundSource();
46
54
 
@@ -53,9 +61,17 @@ class SoundSource : public Nan::ObjectWrap {
53
61
  return *reinterpret_cast<T*>(_sound_source.get());
54
62
  }
55
63
 
64
+ private:
65
+ static void Stop(SoundType type,
66
+ SoundSource* source,
67
+ bool delete_ptr = false);
68
+
56
69
  protected:
57
70
  std::unique_ptr<sf::SoundSource> _sound_source;
58
71
  SimpleActions _simple_actions;
72
+ SoundType _type;
73
+
74
+ static std::map<SoundSource*, SoundType> registered_sounds;
59
75
  };
60
76
 
61
77
  } // namespace sound